From 1325a495df8bfe63cc142d84ab05218e2b378811 Mon Sep 17 00:00:00 2001 From: Vlad Gaydukov Date: Mon, 26 Mar 2018 20:28:00 +0300 Subject: [PATCH] compatibility with three.js v91 removed dublicated code from demo --- build/THREE.Terrain.js | 5 +- build/THREE.Terrain.min.js | 4 +- build/THREE.Terrain.min.js.map | 2 +- demo/index.js | 3 - demo/libs/three.js | 42585 ++++++++++++++++--------------- demo/libs/three.min.js | 1733 +- src/materials.js | 3 +- 7 files changed, 23281 insertions(+), 21054 deletions(-) diff --git a/build/THREE.Terrain.js b/build/THREE.Terrain.js index b278d94..edf2425 100644 --- a/build/THREE.Terrain.js +++ b/build/THREE.Terrain.js @@ -1,5 +1,5 @@ /** - * THREE.Terrain.js 1.5.0-20180318 + * THREE.Terrain.js 1.5.0-20180326 * * @author Isaac Sukin (http://www.isaacsukin.com/) * @license MIT @@ -1778,7 +1778,8 @@ THREE.Terrain.generateBlendedMaterial = function(textures) { THREE.ShaderChunk.emissivemap_pars_fragment, THREE.ShaderChunk.envmap_pars_fragment, THREE.ShaderChunk.bsdfs, - THREE.ShaderChunk.lights_pars, + THREE.ShaderChunk.lights_pars_begin, + THREE.ShaderChunk.lights_pars_maps, THREE.ShaderChunk.fog_pars_fragment, THREE.ShaderChunk.shadowmap_pars_fragment, THREE.ShaderChunk.shadowmask_pars_fragment, diff --git a/build/THREE.Terrain.min.js b/build/THREE.Terrain.min.js index 45e1547..eda573a 100644 --- a/build/THREE.Terrain.min.js +++ b/build/THREE.Terrain.min.js @@ -1,9 +1,9 @@ /** - * THREE.Terrain.js 1.5.0-20180318 + * THREE.Terrain.js 1.5.0-20180326 * * @author Isaac Sukin (http://www.isaacsukin.com/) * @license MIT */ -!function(a){function b(a,b,c){this.x=a,this.y=b,this.z=c}function c(a){return a*a*a*(a*(6*a-15)+10)}function d(a,b,c){return(1-c)*a+c*b}var e=a.noise={};b.prototype.dot2=function(a,b){return this.x*a+this.y*b},b.prototype.dot3=function(a,b,c){return this.x*a+this.y*b+this.z*c};var f=[new b(1,1,0),new b(-1,1,0),new b(1,-1,0),new b(-1,-1,0),new b(1,0,1),new b(-1,0,1),new b(1,0,-1),new b(-1,0,-1),new b(0,1,1),new b(0,-1,1),new b(0,1,-1),new b(0,-1,-1)],g=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180],h=new Array(512),i=new Array(512);e.seed=function(a){a>0&&a<1&&(a*=65536),a=Math.floor(a),a<256&&(a|=a<<8);for(var b=0;b<256;b++){var c;c=1&b?g[b]^255&a:g[b]^a>>8&255,h[b]=h[b+256]=c,i[b]=i[b+256]=f[c%12]}},e.seed(Math.random());var j=.5*(Math.sqrt(3)-1),k=(3-Math.sqrt(3))/6,l=1/3,m=1/6;e.simplex=function(a,b){var c,d,e,f=(a+b)*j,g=Math.floor(a+f),l=Math.floor(b+f),m=(g+l)*k,n=a-g+m,o=b-l+m,p,q;n>o?(p=1,q=0):(p=0,q=1);var r=n-p+k,s=o-q+k,t=n-1+2*k,u=o-1+2*k;g&=255,l&=255;var v=i[g+h[l]],w=i[g+p+h[l+q]],x=i[g+1+h[l+1]],y=.5-n*n-o*o;y<0?c=0:(y*=y,c=y*y*v.dot2(n,o));var z=.5-r*r-s*s;z<0?d=0:(z*=z,d=z*z*w.dot2(r,s));var A=.5-t*t-u*u;return A<0?e=0:(A*=A,e=A*A*x.dot2(t,u)),70*(c+d+e)},e.perlin=function(a,b){var e=Math.floor(a),f=Math.floor(b);a-=e,b-=f,e&=255,f&=255;var g=i[e+h[f]].dot2(a,b),j=i[e+h[f+1]].dot2(a,b-1),k=i[e+1+h[f]].dot2(a-1,b),l=i[e+1+h[f+1]].dot2(a-1,b-1),m=c(a);return d(d(g,k,m),d(j,l,m),c(b))}}(this),THREE.Terrain=function(a){var b={after:null,easing:THREE.Terrain.Linear,heightmap:THREE.Terrain.DiamondSquare,material:null,maxHeight:100,minHeight:-100,optimization:THREE.Terrain.NONE,frequency:2.5,steps:1,stretch:!0,turbulent:!1,useBufferGeometry:!1,xSegments:63,xSize:1024,ySegments:63,ySize:1024,_mesh:null};a=a||{};for(var c in b)b.hasOwnProperty(c)&&(a[c]=void 0===a[c]?b[c]:a[c]);a.material=a.material||new THREE.MeshBasicMaterial({color:15623731});var d=new THREE.Object3D;d.rotation.x=-.5*Math.PI;var e=a._mesh;if(e&&"PlaneGeometry"===e.geometry.type&&e.geometry.parameters.widthSegments===a.xSegments&&e.geometry.parameters.heightSegments===a.ySegments){e.material=a.material,e.scale.x=a.xSize/e.geometry.parameters.width,e.scale.y=a.ySize/e.geometry.parameters.height;for(var f=0,g=e.geometry.vertices.length;f1&&(THREE.Terrain.Step(c,b.steps),THREE.Terrain.Smooth(c,b)),THREE.Terrain.Clamp(c,b),"function"==typeof b.after&&b.after(c,b),a.geometry.verticesNeedUpdate=!0,a.geometry.normalsNeedUpdate=!0,a.geometry.computeBoundingSphere(),a.geometry.computeFaceNormals(),a.geometry.computeVertexNormals()},THREE.Terrain.NONE=0,THREE.Terrain.GEOMIPMAP=1,THREE.Terrain.GEOCLIPMAP=2,THREE.Terrain.POLYGONREDUCTION=3,THREE.Terrain.toArray2D=function(a,b){var c=new Array(b.xSegments),d=b.xSegments+1,e=b.ySegments+1,f,g;for(f=0;fg&&(g=a[i].z),a[i].zd&&(d=a[f].z);var g=d-c,h="number"!=typeof b.maxHeight?d:b.maxHeight,i="number"!=typeof b.minHeight?c:b.minHeight,j=b.stretch?h:di?c:i,l=j-k;for(j=0&&h+k>=0&&e+l=0&&j+k>=0&&g+l=0&&h+k>=0&&e+li&&(i=a[m].z))}var n=h*f+e;if("number"==typeof c){var o=.5*(i-j),p=j+o;i=p+o*c,j=p-o*c}d[n]=a[n].z>i?i:a[n].z=h[d].min&&l<=h[d].max){a[c].z=h[d].avg;break}}},THREE.Terrain.Turbulence=function(a,b){for(var c=b.maxHeight-b.minHeight,d=0,e=a.length;d=2;k/=2){var l=Math.round(.5*k),m=Math.round(k),n,o,p,q,r;for(f/=2,n=0;ng?a[o*n+m].z+=f:q<-g?a[o*n+m].z-=f:a[o*n+m].z+=Math.cos(q/g*Math.PI*2)*f}},THREE.Terrain.Hill=function(a,b,c,d){var e=2*b.frequency,f=e*e*10,g=b.maxHeight-b.minHeight,h=g/(e*e),i=g/e,j=Math.min(b.xSize,b.ySize),k=j/(e*e),l=j/e;c=c||THREE.Terrain.Influences.Hill;for(var m={x:0,y:0},n=0;nd)){var g=0,h=0,i=d,j=d,k=Math.floor(d/c),l=-k,m=-k;for(g=0;g<=i;g+=k){for(h=0;h<=j;h+=k){var n=h*i+g;if(f[n]=Math.random()*e,!(l<0&&m<0)){for(var o=f[n],p=f[h*i+(g-k)]||o,q=f[(h-k)*i+g]||o,r=f[(h-k)*i+(g-k)]||o,s=l;sMath.random())}else s=b.spread(j[r.a],q,r,m,o);if(s){if(r.normal.angleTo(l)>b.maxSlope)continue;var u=b.mesh.clone();if(u.position.copy(j[r.a]).add(j[r.b]).add(j[r.c]).divideScalar(3),b.maxTilt>0){var v=u.position.clone().add(r.normal);u.lookAt(v);var w=r.normal.angleTo(l);if(w>b.maxTilt){var x=b.maxTilt/w;u.rotation.x*=x,u.rotation.y*=x,u.rotation.z*=x}}if(u.rotation.x+=.5*Math.PI,u.rotateY(2*Math.random()*Math.PI),b.sizeVariance){var y=Math.random()*i-b.sizeVariance;u.scale.x=u.scale.z=1+y,u.scale.y+=y}k.push(u)}}var z,A;if(b.mesh.geometry instanceof THREE.Geometry){var B=new THREE.Geometry;for(z=0,A=k.length;zd)&&(g[h]=1);return function(){return g}},THREE.Terrain.Influences={Mesa:function(a){return 1.25*Math.min(.8,Math.exp(-a*a))},Hole:function(a){return-THREE.Terrain.Influences.Mesa(a)},Hill:function(a){return a<0?(a+1)*(a+1)*(3-2*(a+1)):1-a*a*(3-2*a)},Valley:function(a){return-THREE.Terrain.Influences.Hill(a)},Dome:function(a){return-(a+1)*(a-1)},Flat:function(a){return 0},Volcano:function(a){return.94-.32*(Math.abs(2*a)+Math.cos(2*Math.PI*Math.abs(a)+.4))}},THREE.Terrain.Influence=function(a,b,c,d,e,f,g,h,i){c=c||THREE.Terrain.Influences.Hill,d=void 0===d?.5:d,e=void 0===e?.5:e,f=void 0===f?64:f,g=void 0===g?64:g,h=void 0===h?THREE.NormalBlending:h,i=i||THREE.Terrain.EaseIn;for(var j=b.xSegments+1,k=b.ySegments+1,l=j*d,m=k*e,n=b.xSize/b.xSegments,o=b.ySize/b.ySegments,p=f/n,q=f/o,r=1/f,s=Math.ceil(l-p),t=Math.floor(l+p),u=Math.ceil(m-q),v=Math.floor(m+q),w=s;wf||void 0===a[y]||(h===THREE.AdditiveBlending?a[y].z+=F:h===THREE.SubtractiveBlending?a[y].z-=F:h===THREE.MultiplyBlending?a[y].z*=F:h===THREE.NoBlending?a[y].z=F:h===THREE.NormalBlending?a[y].z=i(C,D,E)*a[y].z+F:"function"==typeof h&&(a[y].z=h(a[y].z,F,C,D,E)))}}; +!function(a){function b(a,b,c){this.x=a,this.y=b,this.z=c}function c(a){return a*a*a*(a*(6*a-15)+10)}function d(a,b,c){return(1-c)*a+c*b}var e=a.noise={};b.prototype.dot2=function(a,b){return this.x*a+this.y*b},b.prototype.dot3=function(a,b,c){return this.x*a+this.y*b+this.z*c};var f=[new b(1,1,0),new b(-1,1,0),new b(1,-1,0),new b(-1,-1,0),new b(1,0,1),new b(-1,0,1),new b(1,0,-1),new b(-1,0,-1),new b(0,1,1),new b(0,-1,1),new b(0,1,-1),new b(0,-1,-1)],g=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180],h=new Array(512),i=new Array(512);e.seed=function(a){a>0&&a<1&&(a*=65536),a=Math.floor(a),a<256&&(a|=a<<8);for(var b=0;b<256;b++){var c;c=1&b?g[b]^255&a:g[b]^a>>8&255,h[b]=h[b+256]=c,i[b]=i[b+256]=f[c%12]}},e.seed(Math.random());var j=.5*(Math.sqrt(3)-1),k=(3-Math.sqrt(3))/6,l=1/3,m=1/6;e.simplex=function(a,b){var c,d,e,f=(a+b)*j,g=Math.floor(a+f),l=Math.floor(b+f),m=(g+l)*k,n=a-g+m,o=b-l+m,p,q;n>o?(p=1,q=0):(p=0,q=1);var r=n-p+k,s=o-q+k,t=n-1+2*k,u=o-1+2*k;g&=255,l&=255;var v=i[g+h[l]],w=i[g+p+h[l+q]],x=i[g+1+h[l+1]],y=.5-n*n-o*o;y<0?c=0:(y*=y,c=y*y*v.dot2(n,o));var z=.5-r*r-s*s;z<0?d=0:(z*=z,d=z*z*w.dot2(r,s));var A=.5-t*t-u*u;return A<0?e=0:(A*=A,e=A*A*x.dot2(t,u)),70*(c+d+e)},e.perlin=function(a,b){var e=Math.floor(a),f=Math.floor(b);a-=e,b-=f,e&=255,f&=255;var g=i[e+h[f]].dot2(a,b),j=i[e+h[f+1]].dot2(a,b-1),k=i[e+1+h[f]].dot2(a-1,b),l=i[e+1+h[f+1]].dot2(a-1,b-1),m=c(a);return d(d(g,k,m),d(j,l,m),c(b))}}(this),THREE.Terrain=function(a){var b={after:null,easing:THREE.Terrain.Linear,heightmap:THREE.Terrain.DiamondSquare,material:null,maxHeight:100,minHeight:-100,optimization:THREE.Terrain.NONE,frequency:2.5,steps:1,stretch:!0,turbulent:!1,useBufferGeometry:!1,xSegments:63,xSize:1024,ySegments:63,ySize:1024,_mesh:null};a=a||{};for(var c in b)b.hasOwnProperty(c)&&(a[c]=void 0===a[c]?b[c]:a[c]);a.material=a.material||new THREE.MeshBasicMaterial({color:15623731});var d=new THREE.Object3D;d.rotation.x=-.5*Math.PI;var e=a._mesh;if(e&&"PlaneGeometry"===e.geometry.type&&e.geometry.parameters.widthSegments===a.xSegments&&e.geometry.parameters.heightSegments===a.ySegments){e.material=a.material,e.scale.x=a.xSize/e.geometry.parameters.width,e.scale.y=a.ySize/e.geometry.parameters.height;for(var f=0,g=e.geometry.vertices.length;f1&&(THREE.Terrain.Step(c,b.steps),THREE.Terrain.Smooth(c,b)),THREE.Terrain.Clamp(c,b),"function"==typeof b.after&&b.after(c,b),a.geometry.verticesNeedUpdate=!0,a.geometry.normalsNeedUpdate=!0,a.geometry.computeBoundingSphere(),a.geometry.computeFaceNormals(),a.geometry.computeVertexNormals()},THREE.Terrain.NONE=0,THREE.Terrain.GEOMIPMAP=1,THREE.Terrain.GEOCLIPMAP=2,THREE.Terrain.POLYGONREDUCTION=3,THREE.Terrain.toArray2D=function(a,b){var c=new Array(b.xSegments),d=b.xSegments+1,e=b.ySegments+1,f,g;for(f=0;fg&&(g=a[i].z),a[i].zd&&(d=a[f].z);var g=d-c,h="number"!=typeof b.maxHeight?d:b.maxHeight,i="number"!=typeof b.minHeight?c:b.minHeight,j=b.stretch?h:di?c:i,l=j-k;for(j=0&&h+k>=0&&e+l=0&&j+k>=0&&g+l=0&&h+k>=0&&e+li&&(i=a[m].z))}var n=h*f+e;if("number"==typeof c){var o=.5*(i-j),p=j+o;i=p+o*c,j=p-o*c}d[n]=a[n].z>i?i:a[n].z=h[d].min&&l<=h[d].max){a[c].z=h[d].avg;break}}},THREE.Terrain.Turbulence=function(a,b){for(var c=b.maxHeight-b.minHeight,d=0,e=a.length;d=2;k/=2){var l=Math.round(.5*k),m=Math.round(k),n,o,p,q,r;for(f/=2,n=0;ng?a[o*n+m].z+=f:q<-g?a[o*n+m].z-=f:a[o*n+m].z+=Math.cos(q/g*Math.PI*2)*f}},THREE.Terrain.Hill=function(a,b,c,d){var e=2*b.frequency,f=e*e*10,g=b.maxHeight-b.minHeight,h=g/(e*e),i=g/e,j=Math.min(b.xSize,b.ySize),k=j/(e*e),l=j/e;c=c||THREE.Terrain.Influences.Hill;for(var m={x:0,y:0},n=0;nd)){var g=0,h=0,i=d,j=d,k=Math.floor(d/c),l=-k,m=-k;for(g=0;g<=i;g+=k){for(h=0;h<=j;h+=k){var n=h*i+g;if(f[n]=Math.random()*e,!(l<0&&m<0)){for(var o=f[n],p=f[h*i+(g-k)]||o,q=f[(h-k)*i+g]||o,r=f[(h-k)*i+(g-k)]||o,s=l;sMath.random())}else s=b.spread(j[r.a],q,r,m,o);if(s){if(r.normal.angleTo(l)>b.maxSlope)continue;var u=b.mesh.clone();if(u.position.copy(j[r.a]).add(j[r.b]).add(j[r.c]).divideScalar(3),b.maxTilt>0){var v=u.position.clone().add(r.normal);u.lookAt(v);var w=r.normal.angleTo(l);if(w>b.maxTilt){var x=b.maxTilt/w;u.rotation.x*=x,u.rotation.y*=x,u.rotation.z*=x}}if(u.rotation.x+=.5*Math.PI,u.rotateY(2*Math.random()*Math.PI),b.sizeVariance){var y=Math.random()*i-b.sizeVariance;u.scale.x=u.scale.z=1+y,u.scale.y+=y}k.push(u)}}var z,A;if(b.mesh.geometry instanceof THREE.Geometry){var B=new THREE.Geometry;for(z=0,A=k.length;zd)&&(g[h]=1);return function(){return g}},THREE.Terrain.Influences={Mesa:function(a){return 1.25*Math.min(.8,Math.exp(-a*a))},Hole:function(a){return-THREE.Terrain.Influences.Mesa(a)},Hill:function(a){return a<0?(a+1)*(a+1)*(3-2*(a+1)):1-a*a*(3-2*a)},Valley:function(a){return-THREE.Terrain.Influences.Hill(a)},Dome:function(a){return-(a+1)*(a-1)},Flat:function(a){return 0},Volcano:function(a){return.94-.32*(Math.abs(2*a)+Math.cos(2*Math.PI*Math.abs(a)+.4))}},THREE.Terrain.Influence=function(a,b,c,d,e,f,g,h,i){c=c||THREE.Terrain.Influences.Hill,d=void 0===d?.5:d,e=void 0===e?.5:e,f=void 0===f?64:f,g=void 0===g?64:g,h=void 0===h?THREE.NormalBlending:h,i=i||THREE.Terrain.EaseIn;for(var j=b.xSegments+1,k=b.ySegments+1,l=j*d,m=k*e,n=b.xSize/b.xSegments,o=b.ySize/b.ySegments,p=f/n,q=f/o,r=1/f,s=Math.ceil(l-p),t=Math.floor(l+p),u=Math.ceil(m-q),v=Math.floor(m+q),w=s;wf||void 0===a[y]||(h===THREE.AdditiveBlending?a[y].z+=F:h===THREE.SubtractiveBlending?a[y].z-=F:h===THREE.MultiplyBlending?a[y].z*=F:h===THREE.NoBlending?a[y].z=F:h===THREE.NormalBlending?a[y].z=i(C,D,E)*a[y].z+F:"function"==typeof h&&(a[y].z=h(a[y].z,F,C,D,E)))}}; //# sourceMappingURL=THREE.Terrain.min.js.map \ No newline at end of file diff --git a/build/THREE.Terrain.min.js.map b/build/THREE.Terrain.min.js.map index 5b28acc..4dc01ed 100644 --- a/build/THREE.Terrain.min.js.map +++ b/build/THREE.Terrain.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["THREE.Terrain.js"],"names":["global","Grad","x","y","z","this","fade","t","lerp","a","b","module","noise","prototype","dot2","dot3","grad3","p","perm","Array","gradP","seed","Math","floor","i","v","random","F2","sqrt","G2","F3","G3","simplex","xin","yin","n0","n1","n2","s","j","x0","y0","i1","j1","x1","y1","x2","y2","gi0","gi1","gi2","t0","t1","t2","perlin","X","Y","n00","n01","n10","n11","u","THREE","Terrain","options","defaultOptions","after","easing","Linear","heightmap","DiamondSquare","material","maxHeight","minHeight","optimization","NONE","frequency","steps","stretch","turbulent","useBufferGeometry","xSegments","xSize","ySegments","ySize","_mesh","opt","hasOwnProperty","MeshBasicMaterial","color","scene","Object3D","rotation","PI","mesh","geometry","type","parameters","widthSegments","heightSegments","scale","width","height","l","vertices","length","Mesh","PlaneGeometry","HTMLCanvasElement","Image","fromHeightmap","console","warn","Normalize","BufferGeometry","fromGeometry","add","Turbulence","Step","Smooth","Clamp","verticesNeedUpdate","normalsNeedUpdate","computeBoundingSphere","computeFaceNormals","computeVertexNormals","GEOMIPMAP","GEOCLIPMAP","POLYGONREDUCTION","toArray2D","tgt","xl","yl","Float64Array","fromArray2D","src","toArray1D","fromArray1D","min","heightmapArray","method","arr","EaseIn","EaseOut","EaseInOut","InEaseOut","EaseInWeak","pow","EaseInStrong","g","canvas","document","createElement","context","getContext","rows","cols","spread","drawImage","data","getImageData","row","col","idx","toHeightmap","hasMax","hasMin","max","Infinity","max2","min2","k","d","createImageData","round","putImageData","actualRange","optMax","optMin","targetMax","targetMin","range","Edges","direction","distance","edges","numXSegments","numYSegments","peak","multiplier","k1","k2","top","bottom","left","right","RadialEdges","xl2","yl2","xSegmentSize","ySegmentSize","edgeRadius","vertexDistance","weight","sum","c","n","m","key","w","SmoothMedian","neighborValues","neighborKeys","sortByValue","push","sort","halfKey","median","SmoothConservative","kk","halfdiff","middle","levels","inc","heights","buckets","subset","slice","bl","avg","startHeight","abs","MultiPass","passes","clonedOptions","amp","amplitude","move","Curve","curve","scalar","Cosine","frequencyScalar","phase","cos","CosineLayers","segments","nextPowerOfTwo","size","smoothing","half","whole","e","Fault","iterations","displacement","smoothDistance","sin","Hill","feature","shape","numFeatures","heightRange","smallerSideLength","minRadius","maxRadius","Influences","coords","radius","maxX","maxY","Influence","AdditiveBlending","HillIsland","island","theta","deposit","currentKey","neighborKey","Particles","xDeviation","yDeviation","Perlin","divisor","PerlinDiamond","o","PerlinLayers","Simplex","SimplexLayers","WhiteNoise","lastX","lastY","px","py","r1","r2","kg","kd","Value","Weierstrass","dir1","dir2","r11","r12","r13","r14","r21","r22","r23","r24","exp","generateBlendedMaterial","textures","glslifyNumber","uniforms","UniformsUtils","merge","ShaderLib","lambert","declare","assign","t0Repeat","texture","repeat","t0Offset","offset","wrapS","wrapT","RepeatWrapping","needsUpdate","value","glsl","useLevels","tiRepeat","tiOffset","blendAmount","params","fog","lights","vertexShader","replace","fragmentShader","ShaderChunk","common","packing","dithering_pars_fragment","color_pars_fragment","uv_pars_fragment","uv2_pars_fragment","map_pars_fragment","alphamap_pars_fragment","aomap_pars_fragment","lightmap_pars_fragment","emissivemap_pars_fragment","envmap_pars_fragment","bsdfs","lights_pars","fog_pars_fragment","shadowmap_pars_fragment","shadowmask_pars_fragment","specularmap_pars_fragment","logdepthbuf_pars_fragment","clipping_planes_pars_fragment","clipping_planes_fragment","logdepthbuf_fragment","map_fragment","color_fragment","alphamap_fragment","alphatest_fragment","specularmap_fragment","emissivemap_fragment","lightmap_fragment","aomap_fragment","normal_flip","envmap_fragment","tonemapping_fragment","encodings_fragment","fog_fragment","premultiplied_alpha_fragment","dithering_fragment","join","ShaderMaterial","ScatterMeshes","error","smoothSpread","sizeVariance","randomness","maxSlope","maxTilt","h","spreadIsNumber","randomHeightmap","spreadRange","doubleSizeVariance","meshes","up","clone","applyAxisAngle","Vector3","f","faces","place","rv","normal","angleTo","position","copy","divideScalar","lookAt","tiltAngle","ratio","rotateY","variance","Geometry","updateMatrix","matrix","ScatterHelper","skip","threshold","Mesa","Hole","Valley","Dome","Flat","Volcano","r","NormalBlending","vx","vy","xw","yw","rx","ry","xs","ceil","xe","ys","ye","fdx","fdy","fd","fdr","fdxr","fdyr","SubtractiveBlending","MultiplyBlending","NoBlending"],"mappings":";;;;;;;CAgBA,SAAUA,GAGN,QAASC,GAAKC,EAAGC,EAAGC,GAChBC,KAAKH,EAAIA,EACTG,KAAKF,EAAIA,EACTE,KAAKD,EAAIA,EAsIb,QAASE,GAAKC,GACV,MAAOA,GAAEA,EAAEA,GAAGA,GAAK,EAAFA,EAAI,IAAI,IAG7B,QAASC,GAAKC,EAAGC,EAAGH,GAChB,OAAQ,EAAEA,GAAGE,EAAIF,EAAEG,EAhJvB,GAAIC,GAASX,EAAOY,QAQpBX,GAAKY,UAAUC,KAAO,SAASZ,EAAGC,GAC9B,MAAOE,MAAKH,EAAEA,EAAIG,KAAKF,EAAEA,GAG7BF,EAAKY,UAAUE,KAAO,SAASb,EAAGC,EAAGC,GACjC,MAAOC,MAAKH,EAAEA,EAAIG,KAAKF,EAAEA,EAAIE,KAAKD,EAAEA,EAGxC,IAAIY,IACA,GAAIf,GAAK,EAAE,EAAE,GAAG,GAAIA,IAAM,EAAE,EAAE,GAAG,GAAIA,GAAK,GAAG,EAAE,GAAG,GAAIA,IAAM,GAAG,EAAE,GACjE,GAAIA,GAAK,EAAE,EAAE,GAAG,GAAIA,IAAM,EAAE,EAAE,GAAG,GAAIA,GAAK,EAAE,GAAG,GAAG,GAAIA,IAAM,EAAE,GAAG,GACjE,GAAIA,GAAK,EAAE,EAAE,GAAG,GAAIA,GAAK,GAAG,EAAE,GAAG,GAAIA,GAAK,EAAE,GAAG,GAAG,GAAIA,GAAK,GAAG,GAAG,IAGjEgB,GAAK,IAAI,IAAI,IAAI,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,IAAI,EAAE,IAAI,IAAI,GAAG,IACnE,GAAG,GAAG,IAAI,EAAE,GAAG,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,EAAE,IAAI,IAAI,IAAI,IAAI,GAAG,EAAE,GAAG,IAAI,GAAG,GACpE,IAAI,IAAI,IAAI,IAAI,GAAG,GAAG,GAAG,GAAG,IAAI,GAAG,GAAG,IAAI,IAAI,GAAG,GAAG,IAAI,GAAG,IAAI,IAAI,IACnE,IAAI,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,IAAI,GAAG,GAAG,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,IACjE,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,GAAG,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,GAAG,GAAG,GAAG,IAClE,EAAE,IAAI,GAAG,GAAG,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IACjE,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,EAAE,GAAG,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,EAAE,IAAI,GAAG,IAChE,IAAI,IAAI,IAAI,GAAG,GAAG,IAAI,IAAI,IAAI,GAAG,IAAI,GAAG,GAAG,GAAG,GAAG,IAAI,IAAI,GAAG,GAAG,IAAI,IACnE,IAAI,IAAI,IAAI,IAAI,IAAI,EAAE,GAAG,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,GAAG,IAAI,EAAE,IACjE,GAAG,GAAG,IAAI,GAAG,GAAG,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,GAAG,IAClE,IAAI,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,IAAI,GAAG,GAAG,IAAI,IAAI,IAAI,GAAG,IACnE,IAAI,GAAG,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,IAAI,GAAG,GAAG,IAAI,EACnE,IAAI,IAAI,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,GAAG,GAAG,GAAG,GAAG,IAAI,IAAI,IAAI,IAAI,GAAG,GAAG,IACjE,GAAG,IAAI,KAEPC,EAAO,GAAIC,OAAM,KACjBC,EAAQ,GAAID,OAAM,IAItBR,GAAOU,KAAO,SAASA,GACfA,EAAO,GAAKA,EAAO,IAEnBA,GAAQ,OAGZA,EAAOC,KAAKC,MAAMF,GACdA,EAAO,MACPA,GAAQA,GAAQ,EAGpB,KAAK,GAAIG,GAAI,EAAGA,EAAI,IAAKA,IAAK,CAC1B,GAAIC,EAEAA,GADI,EAAJD,EACIP,EAAEO,GAAa,IAAPH,EAGRJ,EAAEO,GAAOH,GAAM,EAAK,IAG5BH,EAAKM,GAAKN,EAAKM,EAAI,KAAOC,EAC1BL,EAAMI,GAAKJ,EAAMI,EAAI,KAAOR,EAAMS,EAAI,MAI9Cd,EAAOU,KAAKC,KAAKI,SAGjB,IAAIC,GAAK,IAAKL,KAAKM,KAAK,GAAG,GACvBC,GAAM,EAAEP,KAAKM,KAAK,IAAI,EACtBE,EAAK,EAAE,EACPC,EAAK,EAAE,CAGXpB,GAAOqB,QAAU,SAASC,EAAKC,GAC3B,GAAIC,GAAIC,EAAIC,EAERC,GAAKL,EAAIC,GAAKP,EACdH,EAAIF,KAAKC,MAAMU,EAAIK,GACnBC,EAAIjB,KAAKC,MAAMW,EAAII,GACnB/B,GAAKiB,EAAEe,GAAGV,EACVW,EAAKP,EAAIT,EAAEjB,EACXkC,EAAKP,EAAIK,EAAEhC,EAGXmC,EAAIC,CACJH,GAAKC,GACLC,EAAK,EAAGC,EAAK,IAGbD,EAAK,EAAGC,EAAK,EAKjB,IAAIC,GAAKJ,EAAKE,EAAKb,EACfgB,EAAKJ,EAAKE,EAAKd,EACfiB,EAAKN,EAAK,EAAI,EAAIX,EAClBkB,EAAKN,EAAK,EAAI,EAAIZ,CAEtBL,IAAK,IACLe,GAAK,GACL,IAAIS,GAAM5B,EAAMI,EAAEN,EAAKqB,IACnBU,EAAM7B,EAAMI,EAAEkB,EAAGxB,EAAKqB,EAAEI,IACxBO,EAAM9B,EAAMI,EAAE,EAAEN,EAAKqB,EAAE,IAEvBY,EAAK,GAAMX,EAAGA,EAAGC,EAAGA,CACpBU,GAAK,EACLhB,EAAK,GAGLgB,GAAMA,EACNhB,EAAKgB,EAAKA,EAAKH,EAAIlC,KAAK0B,EAAIC,GAEhC,IAAIW,GAAK,GAAMR,EAAGA,EAAGC,EAAGA,CACpBO,GAAK,EACLhB,EAAK,GAGLgB,GAAMA,EACNhB,EAAKgB,EAAKA,EAAKH,EAAInC,KAAK8B,EAAIC,GAEhC,IAAIQ,GAAK,GAAMP,EAAGA,EAAGC,EAAGA,CAUxB,OATIM,GAAK,EACLhB,EAAK,GAGLgB,GAAMA,EACNhB,EAAKgB,EAAKA,EAAKH,EAAIpC,KAAKgC,EAAIC,IAIzB,IAAMZ,EAAKC,EAAKC,IAc3B1B,EAAO2C,OAAS,SAASpD,EAAGC,GAExB,GAAIoD,GAAIjC,KAAKC,MAAMrB,GACfsD,EAAIlC,KAAKC,MAAMpB,EAEnBD,IAAQqD,EACRpD,GAAQqD,EAERD,GAAQ,IACRC,GAAQ,GAGR,IAAIC,GAAMrC,EAAMmC,EAAErC,EAAKsC,IAAI1C,KAAKZ,EAAGC,GAC/BuD,EAAMtC,EAAMmC,EAAErC,EAAKsC,EAAE,IAAI1C,KAAKZ,EAAGC,EAAE,GACnCwD,EAAMvC,EAAMmC,EAAE,EAAErC,EAAKsC,IAAI1C,KAAKZ,EAAE,EAAGC,GACnCyD,EAAMxC,EAAMmC,EAAE,EAAErC,EAAKsC,EAAE,IAAI1C,KAAKZ,EAAE,EAAGC,EAAE,GAGvC0D,EAAIvD,EAAKJ,EAGb,OAAOM,GACHA,EAAKiD,EAAKE,EAAKE,GACfrD,EAAKkD,EAAKE,EAAKC,GACfvD,EAAKH,MAGdE,MA8EHyD,MAAMC,QAAU,SAASC,GACrB,GAAIC,IACAC,MAAO,KACPC,OAAQL,MAAMC,QAAQK,OACtBC,UAAWP,MAAMC,QAAQO,cACzBC,SAAU,KACVC,UAAW,IACXC,WAAY,IACZC,aAAcZ,MAAMC,QAAQY,KAC5BC,UAAW,IACXC,MAAO,EACPC,SAAS,EACTC,WAAW,EACXC,mBAAmB,EACnBC,UAAW,GACXC,MAAO,KACPC,UAAW,GACXC,MAAO,KACPC,MAAO,KAEXrB,GAAUA,KACV,KAAK,GAAIsB,KAAOrB,GACRA,EAAesB,eAAeD,KAC9BtB,EAAQsB,OAA+B,KAAjBtB,EAAQsB,GAAuBrB,EAAeqB,GAAOtB,EAAQsB,GAG3FtB,GAAQO,SAAWP,EAAQO,UAAY,GAAIT,OAAM0B,mBAAoBC,MAAO,UAI5E,IAAIC,GAAQ,GAAI5B,OAAM6B,QAEtBD,GAAME,SAAS1F,GAAK,GAAMoB,KAAKuE,EAI/B,IAAIC,GAAO9B,EAAQqB,KACnB,IAAIS,GAA+B,kBAAvBA,EAAKC,SAASC,MACdF,EAAKC,SAASE,WAAWC,gBAAkBlC,EAAQiB,WACnDa,EAAKC,SAASE,WAAWE,iBAAmBnC,EAAQmB,UAAW,CACvEW,EAAKvB,SAAWP,EAAQO,SACxBuB,EAAKM,MAAMlG,EAAI8D,EAAQkB,MAAQY,EAAKC,SAASE,WAAWI,MACxDP,EAAKM,MAAMjG,EAAI6D,EAAQoB,MAAQU,EAAKC,SAASE,WAAWK,MACxD,KAAK,GAAI9E,GAAI,EAAG+E,EAAIT,EAAKC,SAASS,SAASC,OAAQjF,EAAI+E,EAAG/E,IACtDsE,EAAKC,SAASS,SAAShF,GAAGpB,EAAI,MAIlC0F,GAAO,GAAIhC,OAAM4C,KACb,GAAI5C,OAAM6C,cAAc3C,EAAQkB,MAAOlB,EAAQoB,MAAOpB,EAAQiB,UAAWjB,EAAQmB,WACjFnB,EAAQO,SAwBhB,cArBOP,GAAQqB,MAGXrB,EAAQK,oBAAqBuC,oBAAqB5C,EAAQK,oBAAqBwC,OAC/E/C,MAAMC,QAAQ+C,cAAchB,EAAKC,SAASS,SAAUxC,GAElB,kBAAtBA,GAAQK,UACpBL,EAAQK,UAAUyB,EAAKC,SAASS,SAAUxC,GAG1C+C,QAAQC,KAAK,wDAA0DhD,EAAQK,WAEnFP,MAAMC,QAAQkD,UAAUnB,EAAM9B,GAE1BA,EAAQgB,oBACRc,EAAKC,UAAW,GAAKjC,OAAMoD,gBAAkBC,aAAarB,EAAKC,WAKnEL,EAAM0B,IAAItB,GACHJ,GAgBX5B,MAAMC,QAAQkD,UAAY,SAASnB,EAAM9B,GACrC,GAAIvC,GAAIqE,EAAKC,SAASS,QAClBxC,GAAQe,WACRjB,MAAMC,QAAQsD,WAAW5F,EAAGuC,GAE5BA,EAAQa,MAAQ,IAChBf,MAAMC,QAAQuD,KAAK7F,EAAGuC,EAAQa,OAC9Bf,MAAMC,QAAQwD,OAAO9F,EAAGuC,IAG5BF,MAAMC,QAAQyD,MAAM/F,EAAGuC,GAEM,kBAAlBA,GAAQE,OACfF,EAAQE,MAAMzC,EAAGuC,GAGrB8B,EAAKC,SAAS0B,oBAAqB,EACnC3B,EAAKC,SAAS2B,mBAAoB,EAClC5B,EAAKC,SAAS4B,wBACd7B,EAAKC,SAAS6B,qBACd9B,EAAKC,SAAS8B,wBAwDlB/D,MAAMC,QAAQY,KAAO,EACrBb,MAAMC,QAAQ+D,UAAY,EAC1BhE,MAAMC,QAAQgE,WAAa,EAC3BjE,MAAMC,QAAQiE,iBAAmB,EAkBjClE,MAAMC,QAAQkE,UAAY,SAASzB,EAAUxC,GACzC,GAAIkE,GAAM,GAAI/G,OAAM6C,EAAQiB,WACxBkD,EAAKnE,EAAQiB,UAAY,EACzBmD,EAAKpE,EAAQmB,UAAY,EACzB3D,EAAGe,CACP,KAAKf,EAAI,EAAGA,EAAI2G,EAAI3G,IAEhB,IADA0G,EAAI1G,GAAK,GAAI6G,cAAarE,EAAQmB,WAC7B5C,EAAI,EAAGA,EAAI6F,EAAI7F,IAChB2F,EAAI1G,GAAGe,GAAKiE,EAASjE,EAAI4F,EAAK3G,GAAGpB,CAGzC,OAAO8H,IAaXpE,MAAMC,QAAQuE,YAAc,SAAS9B,EAAU+B,GAC3C,IAAK,GAAI/G,GAAI,EAAG2G,EAAKI,EAAI9B,OAAQjF,EAAI2G,EAAI3G,IACrC,IAAK,GAAIe,GAAI,EAAG6F,EAAKG,EAAI/G,GAAGiF,OAAQlE,EAAI6F,EAAI7F,IACxCiE,EAASjE,EAAI4F,EAAK3G,GAAGpB,EAAImI,EAAI/G,GAAGe,IAqB5CuB,MAAMC,QAAQyE,UAAY,SAAShC,GAE/B,IAAK,GADD0B,GAAM,GAAIG,cAAa7B,EAASC,QAC3BjF,EAAI,EAAG+E,EAAI2B,EAAIzB,OAAQjF,EAAI+E,EAAG/E,IACnC0G,EAAI1G,GAAKgF,EAAShF,GAAGpB,CAEzB,OAAO8H,IAaXpE,MAAMC,QAAQ0E,YAAc,SAASjC,EAAU+B,GAC3C,IAAK,GAAI/G,GAAI,EAAG+E,EAAIjF,KAAKoH,IAAIlC,EAASC,OAAQ8B,EAAI9B,QAASjF,EAAI+E,EAAG/E,IAC9DgF,EAAShF,GAAGpB,EAAImI,EAAI/G,IAkB5BsC,MAAMC,QAAQ4E,eAAiB,SAASC,EAAQ5E,GAC5C,GAAI6E,GAAM,GAAI1H,QAAO6C,EAAQiB,UAAU,IAAMjB,EAAQmB,UAAU,IAC3DoB,EAAIsC,EAAIpC,OACRjF,CAMJ,KAAKA,EAAI,EAAGA,EAAI+E,EAAG/E,IACfqH,EAAIrH,IAAMpB,EAAG,EAOjB,KALA4D,EAAQS,UAAYT,EAAQS,WAAa,EACzCT,EAAQQ,cAAyC,KAAtBR,EAAQQ,UAA4B,EAAIR,EAAQQ,UAC3ER,EAAQc,QAAUd,EAAQc,UAAW,EACrC8D,EAAOC,EAAK7E,GACZF,MAAMC,QAAQyD,MAAMqB,EAAK7E,GACpBxC,EAAI,EAAGA,EAAI+E,EAAG/E,IACfqH,EAAIrH,GAAKqH,EAAIrH,GAAGpB,CAEpB,OAAOyI,IAMX/E,MAAMC,QAAQK,OAAS,SAASlE,GAC5B,MAAOA,IAIX4D,MAAMC,QAAQ+E,OAAS,SAAS5I,GAC5B,MAAOA,GAAEA,GAIb4D,MAAMC,QAAQgF,QAAU,SAAS7I,GAC7B,OAAQA,GAAKA,EAAI,IAMrB4D,MAAMC,QAAQiF,UAAY,SAAS9I,GAC/B,MAAOA,GAAEA,GAAG,EAAE,EAAEA,IAIpB4D,MAAMC,QAAQkF,UAAY,SAAS/I,GAC/B,GAAIC,GAAI,EAAED,EAAE,CACZ,OAAO,GAAMC,EAAEA,EAAEA,EAAI,IAIzB2D,MAAMC,QAAQmF,WAAa,SAAShJ,GAChC,MAAOoB,MAAK6H,IAAIjJ,EAAG,OAIvB4D,MAAMC,QAAQqF,aAAe,SAASlJ,GAClC,MAAOA,GAAEA,EAAEA,EAAEA,EAAEA,EAAEA,EAAEA,GAcvB4D,MAAMC,QAAQ+C,cAAgB,SAASuC,EAAGrF,GACtC,GAAIsF,GAASC,SAASC,cAAc,UAChCC,EAAUH,EAAOI,WAAW,MAC5BC,EAAO3F,EAAQmB,UAAY,EAC3ByE,EAAO5F,EAAQiB,UAAY,EAC3B4E,EAAS7F,EAAQQ,UAAYR,EAAQS,SACzC6E,GAAOjD,MAAQuD,EACfN,EAAOhD,OAASqD,EAChBF,EAAQK,UAAU9F,EAAQK,UAAW,EAAG,EAAGiF,EAAOjD,MAAOiD,EAAOhD,OAEhE,KAAK,GADDyD,GAAON,EAAQO,aAAa,EAAG,EAAGV,EAAOjD,MAAOiD,EAAOhD,QAAQyD,KAC1DE,EAAM,EAAGA,EAAMN,EAAMM,IAC1B,IAAK,GAAIC,GAAM,EAAGA,EAAMN,EAAMM,IAAO,CACjC,GAAI1I,GAAIyI,EAAML,EAAOM,EACjBC,EAAU,EAAJ3I,CACV6H,GAAE7H,GAAGpB,GAAK2J,EAAKI,GAAOJ,EAAKI,EAAI,GAAKJ,EAAKI,EAAI,IAAM,IAAMN,EAAS7F,EAAQS,YAoBtFX,MAAMC,QAAQqG,YAAc,SAASf,EAAGrF,GACpC,GAAIqG,OAAsC,KAAtBrG,EAAQQ,UACxB8F,MAAsC,KAAtBtG,EAAQS,UACxB8F,EAAMF,EAASrG,EAAQQ,WAAagG,EAAAA,EACpC9B,EAAM4B,EAAStG,EAAQS,UAAa+F,EAAAA,CACxC,KAAKH,IAAWC,EAAQ,CAGpB,IAAK,GAFDG,GAAOF,EACPG,EAAOhC,EACFiC,EAAI,EAAGpE,EAAI8C,EAAE5C,OAAQkE,EAAIpE,EAAGoE,IAC7BtB,EAAEsB,GAAGvK,EAAIqK,IAAMA,EAAOpB,EAAEsB,GAAGvK,GAC3BiJ,EAAEsB,GAAGvK,EAAIsK,IAAMA,EAAOrB,EAAEsB,GAAGvK,EAE9BiK,KAAQE,EAAME,GACdH,IAAQ5B,EAAMgC,GAEvB,GAAIpB,GAAStF,EAAQK,oBAAqBuC,mBAAoB5C,EAAQK,UAAYkF,SAASC,cAAc,UACrGC,EAAUH,EAAOI,WAAW,MAC5BC,EAAO3F,EAAQmB,UAAY,EAC3ByE,EAAO5F,EAAQiB,UAAY,EAC3B4E,EAAS7F,EAAQQ,UAAYR,EAAQS,SACzC6E,GAAOjD,MAAQuD,EACfN,EAAOhD,OAASqD,CAGhB,KAAK,GAFDiB,GAAInB,EAAQoB,gBAAgBvB,EAAOjD,MAAOiD,EAAOhD,QACjDyD,EAAOa,EAAEb,KACJE,EAAM,EAAGA,EAAMN,EAAMM,IAC1B,IAAK,GAAIC,GAAM,EAAGA,EAAMN,EAAMM,IAAO,CACjC,GAAI1I,GAAIyI,EAAML,EAAOM,EACrBC,EAAU,EAAJ3I,CACNuI,GAAKI,GAAOJ,EAAKI,EAAI,GAAKJ,EAAKI,EAAI,GAAK7I,KAAKwJ,OAAQzB,EAAE7H,GAAGpB,EAAI4D,EAAQS,WAAaoF,EAAU,KAC7FE,EAAKI,EAAI,GAAK,IAItB,MADAV,GAAQsB,aAAaH,EAAG,EAAG,GACpBtB,GAeXxF,MAAMC,QAAQyD,MAAQ,SAAS6B,EAAGrF,GAC9B,GAAI0E,GAAM8B,EAAAA,EACND,GAAOC,EAAAA,EACPjE,EAAI8C,EAAE5C,OACNjF,CAEJ,KADAwC,EAAQG,OAASH,EAAQG,QAAUL,MAAMC,QAAQK,OAC5C5C,EAAI,EAAGA,EAAI+E,EAAG/E,IACX6H,EAAE7H,GAAGpB,EAAIsI,IAAKA,EAAMW,EAAE7H,GAAGpB,GACzBiJ,EAAE7H,GAAGpB,EAAImK,IAAKA,EAAMlB,EAAE7H,GAAGpB,EAEjC,IAAI4K,GAAcT,EAAM7B,EACpBuC,EAAsC,gBAAtBjH,GAAQQ,UAAyB+F,EAAMvG,EAAQQ,UAC/D0G,EAAsC,gBAAtBlH,GAAQS,UAAyBiE,EAAM1E,EAAQS,UAC/D0G,EAAYnH,EAAQc,QAAUmG,EAAUV,EAAMU,EAASV,EAAMU,EAC7DG,EAAYpH,EAAQc,QAAUoG,EAAUxC,EAAMwC,EAASxC,EAAMwC,EAC7DG,EAAQF,EAAYC,CAKxB,KAJID,EAAYC,IACZD,EAAYF,EACZI,EAAQF,EAAYC,GAEnB5J,EAAI,EAAGA,EAAI+E,EAAG/E,IACf6H,EAAE7H,GAAGpB,EAAI4D,EAAQG,QAAQkF,EAAE7H,GAAGpB,EAAIsI,GAAOsC,GAAeK,EAAQH,GAmCxEpH,MAAMC,QAAQuH,MAAQ,SAASjC,EAAGrF,EAASuH,EAAWC,EAAUrH,EAAQsH,GACpE,GAAIC,GAAepK,KAAKC,MAAMiK,GAAYxH,EAAQkB,MAAQlB,EAAQiB,aAAe,EAC7E0G,EAAerK,KAAKC,MAAMiK,GAAYxH,EAAQoB,MAAQpB,EAAQmB,aAAe,EAC7EyG,EAAOL,EAAYvH,EAAQQ,UAAYR,EAAQS,UAC/C8F,EAAMgB,EAAYjK,KAAKiJ,IAAMjJ,KAAKoH,IAClCP,EAAKnE,EAAQiB,UAAY,EACzBmD,EAAKpE,EAAQmB,UAAY,EACzB3D,EAAGe,EAAGsJ,EAAYC,EAAIC,CAK1B,KAJA5H,EAASA,GAAUL,MAAMC,QAAQiF,UACZ,gBAAVyC,KACPA,GAASO,KAAK,EAAMC,QAAQ,EAAMC,MAAM,EAAMC,OAAO,IAEpD3K,EAAI,EAAGA,EAAI2G,EAAI3G,IAChB,IAAKe,EAAI,EAAGA,EAAIoJ,EAAcpJ,IAC1BsJ,EAAa1H,EAAO,EAAI5B,EAAIoJ,GAC5BG,EAAKvJ,EAAE4F,EAAK3G,EACZuK,GAAM/H,EAAQmB,UAAU5C,GAAG4F,EAAK3G,EAC5BiK,EAAMO,MACN3C,EAAEyC,GAAI1L,EAAImK,EAAIlB,EAAEyC,GAAI1L,GAAIwL,EAAOvC,EAAEyC,GAAI1L,GAAKyL,EAAaxC,EAAEyC,GAAI1L,IAE7DqL,EAAMQ,SACN5C,EAAE0C,GAAI3L,EAAImK,EAAIlB,EAAE0C,GAAI3L,GAAIwL,EAAOvC,EAAE0C,GAAI3L,GAAKyL,EAAaxC,EAAE0C,GAAI3L,GAIzE,KAAKoB,EAAI,EAAGA,EAAI4G,EAAI5G,IAChB,IAAKe,EAAI,EAAGA,EAAImJ,EAAcnJ,IAC1BsJ,EAAa1H,EAAO,EAAI5B,EAAImJ,GAC5BI,EAAKtK,EAAE2G,EAAG5F,EACVwJ,GAAM/H,EAAQmB,UAAU3D,GAAG2G,GAAMnE,EAAQiB,UAAU1C,GAC/CkJ,EAAMS,OACN7C,EAAEyC,GAAI1L,EAAImK,EAAIlB,EAAEyC,GAAI1L,GAAIwL,EAAOvC,EAAEyC,GAAI1L,GAAKyL,EAAaxC,EAAEyC,GAAI1L,IAE7DqL,EAAMU,QACN9C,EAAE0C,GAAI3L,EAAImK,EAAIlB,EAAE0C,GAAI3L,GAAIwL,EAAOvC,EAAE0C,GAAI3L,GAAKyL,EAAaxC,EAAE0C,GAAI3L,GAIzE0D,OAAMC,QAAQyD,MAAM6B,GAChB7E,UAAWR,EAAQQ,UACnBC,UAAWT,EAAQS,UACnBK,SAAS,KA+BjBhB,MAAMC,QAAQqI,YAAc,SAAS/C,EAAGrF,EAASuH,EAAWC,EAAUrH,GAClE,GAAIyH,GAAOL,EAAYvH,EAAQQ,UAAYR,EAAQS,UAC/C8F,EAAMgB,EAAYjK,KAAKiJ,IAAMjJ,KAAKoH,IAClCP,EAAMnE,EAAQiB,UAAY,EAC1BmD,EAAMpE,EAAQmB,UAAY,EAC1BkH,EAAW,GAALlE,EACNmE,EAAW,GAALlE,EACNmE,EAAevI,EAAQkB,MAAQlB,EAAQiB,UACvCuH,EAAexI,EAAQoB,MAAQpB,EAAQmB,UACvCsH,EAAsD,GAAzCnL,KAAKoH,IAAI1E,EAAQkB,MAAOlB,EAAQoB,OAAeoG,EAC5DhK,EAAGe,EAAGsJ,EAAYlB,EAAG+B,CACzB,KAAKlL,EAAI,EAAGA,EAAI2G,EAAI3G,IAChB,IAAKe,EAAI,EAAGA,EAAI+J,EAAK/J,IACjBoI,EAAIpI,EAAE4F,EAAK3G,EACXkL,EAAiBpL,KAAKoH,IAAI+D,EAAYnL,KAAKM,MAAMyK,EAAI7K,GAAG+K,GAAcF,EAAI7K,GAAG+K,GAAgBD,EAAI/J,GAAGiK,GAAcF,EAAI/J,GAAGiK,GAAgBhB,GACrIkB,EAAiB,IACrBb,EAAa1H,EAAOuI,EAAiBD,GACrCpD,EAAEsB,GAAGvK,EAAImK,EAAIlB,EAAEsB,GAAGvK,GAAIwL,EAAOvC,EAAEsB,GAAGvK,GAAKyL,EAAaxC,EAAEsB,GAAGvK,GAEzDuK,GAAK3G,EAAQmB,UAAU5C,GAAG4F,EAAK3G,EAC/B6H,EAAEsB,GAAGvK,EAAImK,EAAIlB,EAAEsB,GAAGvK,GAAIwL,EAAOvC,EAAEsB,GAAGvK,GAAKyL,EAAaxC,EAAEsB,GAAGvK,KAmBrE0D,MAAMC,QAAQwD,OAAS,SAAS8B,EAAGrF,EAAS2I,GAExC,IAAK,GADDtI,GAAY,GAAIgE,cAAagB,EAAE5C,QAC1BjF,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGmD,EAAKpE,EAAQmB,UAAY,EAAG3D,EAAI2G,EAAI3G,IAC5E,IAAK,GAAIe,GAAI,EAAGA,EAAI6F,EAAI7F,IAAK,CAGzB,IAAK,GAFDqK,GAAM,EACNC,EAAI,EACCC,GAAK,EAAGA,GAAK,EAAGA,IACrB,IAAK,GAAIC,IAAK,EAAGA,GAAK,EAAGA,IAAK,CAC1B,GAAIC,IAAOzK,EAAEuK,GAAG3E,EAAK3G,EAAIuL,MACH,KAAX1D,EAAE2D,IAAwBxL,EAAEuL,GAAK,GAAKxK,EAAEuK,GAAK,GAAKtL,EAAEuL,EAAI5E,GAAM5F,EAAEuK,EAAI1E,IAC3EwE,GAAOvD,EAAE2D,GAAK5M,EACdyM,KAIZxI,EAAU9B,EAAE4F,EAAK3G,GAAKoL,EAAMC,EAGpCF,EAASA,GAAU,CAEnB,KAAK,GADDM,GAAI,GAAK,EAAIN,GACRhC,EAAI,EAAGpE,EAAI8C,EAAE5C,OAAQkE,EAAIpE,EAAGoE,IACjCtB,EAAEsB,GAAGvK,GAAKiE,EAAUsG,GAAKtB,EAAEsB,GAAGvK,EAAIuM,GAAUM,GASpDnJ,MAAMC,QAAQmJ,aAAe,SAAS7D,EAAGrF,GAOrC,IAAK,GANDK,GAAY,GAAIgE,cAAagB,EAAE5C,QAC/B0G,KACAC,KACAC,EAAc,SAAS5M,EAAGC,GACtB,MAAOyM,GAAe1M,GAAK0M,EAAezM,IAEzCc,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGmD,EAAKpE,EAAQmB,UAAY,EAAG3D,EAAI2G,EAAI3G,IAC5E,IAAK,GAAIe,GAAI,EAAGA,EAAI6F,EAAI7F,IAAK,CACzB4K,EAAe1G,OAAS,EACxB2G,EAAa3G,OAAS,CACtB,KAAK,GAAIqG,IAAK,EAAGA,GAAK,EAAGA,IACrB,IAAK,GAAIC,IAAK,EAAGA,GAAK,EAAGA,IAAK,CAC1B,GAAIC,IAAOzK,EAAEuK,GAAG3E,EAAK3G,EAAIuL,MACH,KAAX1D,EAAE2D,IAAwBxL,EAAEuL,GAAK,GAAKxK,EAAEuK,GAAK,GAAKtL,EAAEuL,EAAI5E,GAAM5F,EAAEuK,EAAI1E,IAC3E+E,EAAeG,KAAKjE,EAAE2D,GAAK5M,GAC3BgN,EAAaE,KAAKN,IAI9BI,EAAaG,KAAKF,EAClB,IAAIG,GAAUlM,KAAKC,MAA0B,GAApB6L,EAAa3G,QAClCgH,CAEAA,GADAL,EAAa3G,OAAS,GAAM,EACnB4C,EAAE+D,EAAaI,IAAUpN,EAGqC,IAA7DiJ,EAAE+D,EAAaI,EAAQ,IAAIpN,EAAIiJ,EAAE+D,EAAaI,IAAUpN,GAEtEiE,EAAU9B,EAAE4F,EAAK3G,GAAKiM,EAG9B,IAAK,GAAI9C,GAAI,EAAGpE,EAAI8C,EAAE5C,OAAQkE,EAAIpE,EAAGoE,IACjCtB,EAAEsB,GAAGvK,EAAIiE,EAAUsG,IAoB3B7G,MAAMC,QAAQ2J,mBAAqB,SAASrE,EAAGrF,EAAS6H,GAEpD,IAAK,GADDxH,GAAY,GAAIgE,cAAagB,EAAE5C,QAC1BjF,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGmD,EAAKpE,EAAQmB,UAAY,EAAG3D,EAAI2G,EAAI3G,IAC5E,IAAK,GAAIe,GAAI,EAAGA,EAAI6F,EAAI7F,IAAK,CAGzB,IAAK,GAFDgI,IAAOC,EAAAA,EACP9B,EAAM8B,EAAAA,EACDsC,GAAK,EAAGA,GAAK,EAAGA,IACrB,IAAK,GAAIC,IAAK,EAAGA,GAAK,EAAGA,IAAK,CAC1B,GAAIC,IAAOzK,EAAEuK,GAAG3E,EAAK3G,EAAIuL,MACH,KAAX1D,EAAE2D,IAAwBF,GAAKC,GAAKvL,EAAEuL,GAAK,GAAKxK,EAAEuK,GAAK,GAAKtL,EAAEuL,EAAI5E,GAAM5F,EAAEuK,EAAI1E,IACjFiB,EAAE2D,GAAK5M,EAAIsI,IAAKA,EAAMW,EAAE2D,GAAK5M,GAC7BiJ,EAAE2D,GAAK5M,EAAImK,IAAKA,EAAMlB,EAAE2D,GAAK5M,IAI7C,GAAIuN,GAAKpL,EAAE4F,EAAK3G,CAChB,IAA0B,gBAAfqK,GAAyB,CAChC,GAAI+B,GAAyB,IAAbrD,EAAM7B,GAClBmF,EAASnF,EAAMkF,CACnBrD,GAAMsD,EAASD,EAAW/B,EAC1BnD,EAAMmF,EAASD,EAAW/B,EAE9BxH,EAAUsJ,GAAMtE,EAAEsE,GAAIvN,EAAImK,EAAMA,EAAOlB,EAAEsE,GAAIvN,EAAIsI,EAAMA,EAAMW,EAAEsE,GAAIvN,EAG3E,IAAK,GAAIuK,GAAI,EAAGpE,EAAI8C,EAAE5C,OAAQkE,EAAIpE,EAAGoE,IACjCtB,EAAEsB,GAAGvK,EAAIiE,EAAUsG,IAc3B7G,MAAMC,QAAQuD,KAAO,SAAS+B,EAAGyE,GAE7B,GAAItM,GAAI,EACJe,EAAI,EACJgE,EAAI8C,EAAE5C,OACNsH,EAAMzM,KAAKC,MAAMgF,EAAIuH,GACrBE,EAAU,GAAI7M,OAAMoF,GACpB0H,EAAU,GAAI9M,OAAM2M,EAIxB,SAHsB,KAAXA,IACPA,EAASxM,KAAKC,MAAMD,KAAK6H,IAAM,GAAF5C,EAAO,OAEnC/E,EAAI,EAAGA,EAAI+E,EAAG/E,IACfwM,EAAQxM,GAAK6H,EAAE7H,GAAGpB,CAGtB,KADA4N,EAAQT,KAAK,SAAS9M,EAAGC,GAAK,MAAOD,GAAIC,IACpCc,EAAI,EAAGA,EAAIsM,EAAQtM,IAAK,CAEzB,GAAI0M,GAASF,EAAQG,MAAM3M,EAAEuM,GAAMvM,EAAE,GAAGuM,GACpCnB,EAAM,EACNwB,EAAKF,EAAOzH,MAChB,KAAKlE,EAAI,EAAGA,EAAI6L,EAAI7L,IAChBqK,GAAOsB,EAAO3L,EAElB0L,GAAQzM,IACJkH,IAAKwF,EAAO,GACZ3D,IAAK2D,EAAOA,EAAOzH,OAAO,GAC1B4H,IAAKzB,EAAMwB,GAKnB,IAAK5M,EAAI,EAAGA,EAAI+E,EAAG/E,IAAK,CACpB,GAAI8M,GAAcjF,EAAE7H,GAAGpB,CACvB,KAAKmC,EAAI,EAAGA,EAAIuL,EAAQvL,IACpB,GAAI+L,GAAeL,EAAQ1L,GAAGmG,KAAO4F,GAAeL,EAAQ1L,GAAGgI,IAAK,CAChElB,EAAE7H,GAAGpB,EAAI6N,EAAQ1L,GAAG8L,GACpB,UAWhBvK,MAAMC,QAAQsD,WAAa,SAASgC,EAAGrF,GAEnC,IAAK,GADDqH,GAAQrH,EAAQQ,UAAYR,EAAQS,UAC/BjD,EAAI,EAAG+E,EAAI8C,EAAE5C,OAAQjF,EAAI+E,EAAG/E,IACjC6H,EAAE7H,GAAGpB,EAAI4D,EAAQS,UAAYnD,KAAKiN,IAAmC,GAA9BlF,EAAE7H,GAAGpB,EAAI4D,EAAQS,WAAiB4G,IA2BjFvH,MAAMC,QAAQyK,UAAY,SAASnF,EAAGrF,EAASyK,GAC3C,GAAIC,KACJ,KAAK,GAAIpJ,KAAOtB,GACRA,EAAQuB,eAAeD,KACvBoJ,EAAcpJ,GAAOtB,EAAQsB,GAIrC,KAAK,GADD+F,GAAQrH,EAAQQ,UAAYR,EAAQS,UAC/BjD,EAAI,EAAG+E,EAAIkI,EAAOhI,OAAQjF,EAAI+E,EAAG/E,IAAK,CAC3C,GAAImN,OAAqC,KAAxBF,EAAOjN,GAAGoN,UAA4B,EAAIH,EAAOjN,GAAGoN,UACjEC,EAAO,IAAOxD,EAAQA,EAAQsD,EAClCD,GAAclK,UAAYR,EAAQQ,UAAYqK,EAC9CH,EAAcjK,UAAYT,EAAQS,UAAYoK,EAC9CH,EAAc9J,cAA2C,KAAxB6J,EAAOjN,GAAGoD,UAA4BZ,EAAQY,UAAY6J,EAAOjN,GAAGoD,UACrG6J,EAAOjN,GAAGoH,OAAOS,EAAGqF,KAsB5B5K,MAAMC,QAAQ+K,MAAQ,SAASzF,EAAGrF,EAAS+K,GAGvC,IAAK,GAFD1D,GAAkD,IAAzCrH,EAAQQ,UAAYR,EAAQS,WACrCuK,EAAShL,EAAQY,WAAatD,KAAKoH,IAAI1E,EAAQiB,UAAWjB,EAAQmB,WAAa,GAC1E3D,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGmD,EAAKpE,EAAQmB,UAAY,EAAG3D,EAAI2G,EAAI3G,IAC5E,IAAK,GAAIe,GAAI,EAAGA,EAAI6F,EAAI7F,IACpB8G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAK2O,EAAMvN,EAAIwN,EAAQzM,EAAIyM,GAAU3D,GAU/DvH,MAAMC,QAAQkL,OAAS,SAAS5F,EAAGrF,GAI/B,IAAK,GAHD4K,GAAsD,IAAzC5K,EAAQQ,UAAYR,EAAQS,WACzCyK,EAAkBlL,EAAQY,UAAYtD,KAAKuE,IAAMvE,KAAKoH,IAAI1E,EAAQiB,UAAWjB,EAAQmB,WAAa,GAClGgK,EAAQ7N,KAAKI,SAAWJ,KAAKuE,GAAK,EAC7BrE,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGzD,EAAI2G,EAAI3G,IAChD,IAAK,GAAIe,GAAI,EAAG6F,EAAKpE,EAAQmB,UAAY,EAAG5C,EAAI6F,EAAI7F,IAChD8G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAKwO,GAAatN,KAAK8N,IAAI5N,EAAI0N,EAAkBC,GAAS7N,KAAK8N,IAAI7M,EAAI2M,EAAkBC,KAUnHrL,MAAMC,QAAQsL,aAAe,SAAShG,EAAGrF,GACrCF,MAAMC,QAAQyK,UAAUnF,EAAGrF,IACrB4E,OAAQ9E,MAAMC,QAAQkL,OAA0BrK,UAAY,MAC5DgE,OAAQ9E,MAAMC,QAAQkL,OAAQL,UAAW,GAAOhK,UAAY,KAC5DgE,OAAQ9E,MAAMC,QAAQkL,OAAQL,UAAW,IAAOhK,UAAY,KAC5DgE,OAAQ9E,MAAMC,QAAQkL,OAAQL,UAAW,KAAOhK,UAAY,OAiBtEd,MAAMC,QAAQO,cAAgB,SAAS+E,EAAGrF,GAGtC,GAAIsL,GAAWxL,MAAMxC,KAAKiO,eAAejO,KAAKiJ,IAAIvG,EAAQiB,UAAWjB,EAAQmB,WAAa,GAGtFqK,EAAOF,EAAW,EAClBjL,KACAoL,EAAazL,EAAQQ,UAAYR,EAAQS,UACzCjD,EACAe,EACA4F,EAAKnE,EAAQiB,UAAY,EACzBmD,EAAKpE,EAAQmB,UAAY,CAC7B,KAAK3D,EAAI,EAAGA,GAAK8N,EAAU9N,IACvB6C,EAAU7C,GAAK,GAAI6G,cAAaiH,EAAS,EAI7C,KAAK,GAAI/I,GAAI+I,EAAU/I,GAAK,EAAGA,GAAK,EAAG,CACnC,GAAImJ,GAAOpO,KAAKwJ,MAAQ,GAAFvE,GAClBoJ,EAAQrO,KAAKwJ,MAAMvE,GACnBrG,EACAC,EACAkO,EACAzD,EACAgF,CAGJ,KAFAH,GAAa,EAERvP,EAAI,EAAGA,EAAIoP,EAAUpP,GAAKyP,EAC3B,IAAKxP,EAAI,EAAGA,EAAImP,EAAUnP,GAAKwP,EAC3B/E,EAAItJ,KAAKI,SAAW+N,EAAY,EAAIA,EACpCpB,EAAMhK,EAAUnE,GAAGC,GACbkE,EAAUnE,EAAEyP,GAAOxP,GACnBkE,EAAUnE,GAAGC,EAAEwP,GACftL,EAAUnE,EAAEyP,GAAOxP,EAAEwP,GAC3BtB,GAAO,IACPhK,EAAUnE,EAAEwP,GAAMvP,EAAEuP,GAAQrB,EAAMzD,CAI1C,KAAK1K,EAAI,EAAGA,EAAIoP,EAAUpP,GAAKwP,EAC3B,IAAKvP,GAAKD,EAAEwP,GAAQnJ,EAAGpG,EAAImP,EAAUnP,GAAKoG,EACtCqE,EAAItJ,KAAKI,SAAW+N,EAAY,EAAIA,EACpCpB,EAAMhK,GAAWnE,EAAEwP,EAAKF,GAAMA,GAAMrP,GAC9BkE,GAAWnE,EAAEwP,GAAMF,GAAMrP,GACzBkE,EAAUnE,IAAIC,EAAEuP,GAAMF,GACtBnL,EAAUnE,IAAIC,EAAEuP,EAAKF,GAAMA,GACjCnB,GAAO,IACPA,GAAOzD,EACPvG,EAAUnE,GAAGC,GAAKkO,EAER,IAANnO,IAASmE,EAAUiL,GAAUnP,GAAKkO,GAC5B,IAANlO,IAASkE,EAAUnE,GAAGoP,GAAYjB,GAMlD,IAAK7M,EAAI,EAAGA,EAAI2G,EAAI3G,IAChB,IAAKe,EAAI,EAAGA,EAAI6F,EAAI7F,IAChB8G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAKiE,EAAU7C,GAAGe,IAgB5CuB,MAAMC,QAAQ8L,MAAQ,SAASxG,EAAGrF,GAM9B,IAAK,GALD4G,GAAItJ,KAAKM,KAAKoC,EAAQiB,UAAUjB,EAAQiB,UAAYjB,EAAQmB,UAAUnB,EAAQmB,WAC9E2K,EAAalF,EAAI5G,EAAQY,UACzByG,EAAkD,IAAzCrH,EAAQQ,UAAYR,EAAQS,WACrCsL,EAAe1E,EAAQyE,EACvBE,EAAiB1O,KAAKoH,IAAI1E,EAAQkB,MAAQlB,EAAQiB,UAAWjB,EAAQoB,MAAQpB,EAAQmB,WAAanB,EAAQY,UACrG+F,EAAI,EAAGA,EAAImF,EAAYnF,IAK5B,IAAK,GAJDlJ,GAAIH,KAAKI,SACTjB,EAAIa,KAAK2O,IAAIxO,EAAIH,KAAKuE,GAAK,GAC3BnF,EAAIY,KAAK8N,IAAI3N,EAAIH,KAAKuE,GAAK,GAC3BgH,EAAIvL,KAAKI,SAAWkJ,EAAM,GAAFA,EACnBpJ,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGzD,EAAI2G,EAAI3G,IAChD,IAAK,GAAIe,GAAI,EAAG6F,EAAKpE,EAAQmB,UAAY,EAAG5C,EAAI6F,EAAI7F,IAAK,CACrD,GAAIiJ,GAAW/K,EAAEe,EAAId,EAAE6B,EAAIsK,CACvBrB,GAAWwE,EACX3G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAK2P,EAEdvE,GAAYwE,EACjB3G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAK2P,EAGnB1G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAKkB,KAAK8N,IAAI5D,EAAWwE,EAAiB1O,KAAKuE,GAAK,GAAKkK,IAuC3FjM,MAAMC,QAAQmM,KAAO,SAAS7G,EAAGrF,EAASmM,EAASC,GAC/C,GAAIxL,GAAgC,EAApBZ,EAAQY,UACpByL,EAAczL,EAAYA,EAAY,GACtC0L,EAActM,EAAQQ,UAAYR,EAAQS,UAC1CA,EAAY6L,GAAe1L,EAAYA,GACvCJ,EAAY8L,EAAc1L,EAC1B2L,EAAoBjP,KAAKoH,IAAI1E,EAAQkB,MAAOlB,EAAQoB,OACpDoL,EAAYD,GAAqB3L,EAAYA,GAC7C6L,EAAYF,EAAoB3L,CACpCuL,GAAUA,GAAWrM,MAAMC,QAAQ2M,WAAWR,IAG9C,KAAK,GADDS,IAAWzQ,EAAG,EAAGC,EAAG,GACfqB,EAAI,EAAGA,EAAI6O,EAAa7O,IAAK,CAClC,GAAIoP,GAAStP,KAAKI,UAAY+O,EAAYD,GAAaA,EACnDlK,EAAShF,KAAKI,UAAY8C,EAAYC,GAAaA,EACnDiE,EAAM,EAAIkI,EACVC,EAAO7M,EAAQkB,MAAQ0L,EACvBE,EAAO9M,EAAQoB,MAAQwL,CAC3BD,GAAOzQ,EAAIoB,KAAKI,SAChBiP,EAAOxQ,EAAImB,KAAKI,SACK,kBAAV0O,IAAsBA,EAAMO,GACvC7M,MAAMC,QAAQgN,UACV1H,EAAGrF,EACHmM,EACAQ,EAAOzQ,EAAGyQ,EAAOxQ,EACjByQ,EAAQtK,EACRxC,MAAMkN,iBACNlN,MAAMC,QAAQqF,gBA6B1BtF,MAAMC,QAAQkN,WAAa,WACvB,GAAIC,GAAS,SAASP,GAClB,GAAIQ,GAAQ7P,KAAKI,SAAWJ,KAAKuE,GAAK,CACtC8K,GAAOzQ,EAAI,GAAMoB,KAAK8N,IAAI+B,GAASR,EAAOzQ,EAAI,GAC9CyQ,EAAOxQ,EAAI,GAAMmB,KAAK2O,IAAIkB,GAASR,EAAOxQ,EAAI,GAElD,OAAO,UAASkJ,EAAGrF,EAASmM,GACxBrM,MAAMC,QAAQmM,KAAK7G,EAAGrF,EAASmM,EAASe,OAIhD,WAII,QAASE,GAAQ/H,EAAG7H,EAAGe,EAAG4F,EAAI4H,GAG1B,IAAK,GAFDsB,GAAa9O,EAAI4F,EAAK3G,EAEjBmJ,EAAI,EAAGA,EAAI,EAAGA,IAAK,CAExB,OADQrJ,KAAKC,MAAsB,EAAhBD,KAAKI,WAEpB,IAAK,GAAGF,GAAK,MACb,KAAK,GAAGA,GAAK,MACb,KAAK,GAAGe,GAAK,MACb,KAAK,GAAGA,GAAK,MACb,KAAK,GAAGf,IAAKe,GAAK,MAClB,KAAK,GAAGf,IAAKe,GAAK,MAClB,KAAK,GAAGf,IAAKe,GAAK,MAClB,KAAK,GAAGf,IAAKe,GAAK,OAEtB,GAAI+O,GAAc/O,EAAI4F,EAAK3G,CAE3B,QAA8B,KAAnB6H,EAAEiI,IACT,GAAIjI,EAAEiI,GAAalR,EAAIiJ,EAAEgI,GAAYjR,EAEjC,MADAgR,GAAQ/H,EAAG7H,EAAGe,EAAG4F,EAAI4H,OACrB,OAIH,IAAIzO,KAAKI,SAAW,GAErB,MADA2H,GAAEgI,GAAYjR,GAAK2P,MACnB,GAGR1G,EAAEgI,GAAYjR,GAAK2P,EAkBvBjM,MAAMC,QAAQwN,UAAY,SAASlI,EAAGrF,GAQlC,IAAK,GAPD8L,GAAaxO,KAAKM,KAAKoC,EAAQiB,UAAUjB,EAAQiB,UAAYjB,EAAQmB,UAAUnB,EAAQmB,WAAanB,EAAQY,UAAY,IACxHuD,EAAKnE,EAAQiB,UAAY,EACzB8K,GAAgB/L,EAAQQ,UAAYR,EAAQS,WAAaqL,EAAa,IACtEtO,EAAIF,KAAKC,MAAMD,KAAKI,SAAWsC,EAAQiB,WACvC1C,EAAIjB,KAAKC,MAAMD,KAAKI,SAAWsC,EAAQmB,WACvCqM,EAA6B,GAAhBlQ,KAAKI,SAAiB,GACnC+P,EAA6B,GAAhBnQ,KAAKI,SAAiB,GAC9BiJ,EAAI,EAAGA,EAAImF,EAAYnF,IAAK,CACjCyG,EAAQ/H,EAAG7H,EAAGe,EAAG4F,EAAI4H,EACrB,IAAInF,GAAItJ,KAAKI,SAAWJ,KAAKuE,GAAK,CAC9B8E,GAAI,KAAS,IACb6G,EAA6B,GAAhBlQ,KAAKI,SAAiB,GACnC+P,EAA6B,GAAhBnQ,KAAKI,SAAiB,IAEnCiJ,EAAI,KAAQ,IACZnJ,EAAIF,KAAKC,MAAMyC,EAAQiB,WAAW,GAAIuM,GAAclQ,KAAK8N,IAAIxE,GAAKtJ,KAAKI,SAAWsC,EAAQiB,WAAW,GAAI3D,KAAKiN,IAAIiD,KAClHjP,EAAIjB,KAAKC,MAAMyC,EAAQmB,WAAW,GAAIsM,GAAcnQ,KAAK2O,IAAIrF,GAAKtJ,KAAKI,SAAWsC,EAAQmB,WAAW,GAAI7D,KAAKiN,IAAIkD,WAYlI3N,MAAMC,QAAQ2N,OAAS,SAASrI,EAAGrF,GAC/BpD,MAAMS,KAAKC,KAAKI,SAGhB,KAAK,GAFD2J,GAAkD,IAAzCrH,EAAQQ,UAAYR,EAAQS,WACrCkN,GAAWrQ,KAAKoH,IAAI1E,EAAQiB,UAAWjB,EAAQmB,WAAa,GAAKnB,EAAQY,UACpEpD,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGzD,EAAI2G,EAAI3G,IAChD,IAAK,GAAIe,GAAI,EAAG6F,EAAKpE,EAAQmB,UAAY,EAAG5C,EAAI6F,EAAI7F,IAChD8G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAKQ,MAAM0C,OAAO9B,EAAImQ,EAASpP,EAAIoP,GAAWtG,GAUxEvH,MAAMC,QAAQ6N,cAAgB,SAASvI,EAAGrF,GACtCF,MAAMC,QAAQyK,UAAUnF,EAAGrF,IACrB4E,OAAQ9E,MAAMC,QAAQ2N,SACtB9I,OAAQ9E,MAAMC,QAAQO,cAAesK,UAAW,MAChDhG,OAAQ,SAASS,EAAGwI,GAAK,MAAO/N,OAAMC,QAAQmJ,aAAa7D,EAAGwI,QASxE/N,MAAMC,QAAQ+N,aAAe,SAASzI,EAAGrF,GACrCF,MAAMC,QAAQyK,UAAUnF,EAAGrF,IACrB4E,OAAQ9E,MAAMC,QAAQ2N,OAAyB9M,UAAY,OAC3DgE,OAAQ9E,MAAMC,QAAQ2N,OAAQ9C,UAAW,IAAMhK,UAAY,MAC3DgE,OAAQ9E,MAAMC,QAAQ2N,OAAQ9C,UAAW,IAAMhK,UAAY,IAC3DgE,OAAQ9E,MAAMC,QAAQ2N,OAAQ9C,UAAW,IAAMhK,UAAW,OAYpEd,MAAMC,QAAQgO,QAAU,SAAS1I,EAAGrF,GAChCpD,MAAMS,KAAKC,KAAKI,SAGhB,KAAK,GAFD2J,GAAkD,IAAzCrH,EAAQQ,UAAYR,EAAQS,WACrCkN,EAAiE,GAAtDrQ,KAAKoH,IAAI1E,EAAQiB,UAAWjB,EAAQmB,WAAa,GAASnB,EAAQY,UACxEpD,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGzD,EAAI2G,EAAI3G,IAChD,IAAK,GAAIe,GAAI,EAAG6F,EAAKpE,EAAQmB,UAAY,EAAG5C,EAAI6F,EAAI7F,IAChD8G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAKQ,MAAMoB,QAAQR,EAAImQ,EAASpP,EAAIoP,GAAWtG,GAUzEvH,MAAMC,QAAQiO,cAAgB,SAAS3I,EAAGrF,GACtCF,MAAMC,QAAQyK,UAAUnF,EAAGrF,IACrB4E,OAAQ9E,MAAMC,QAAQgO,QAA4BnN,UAAY,OAC9DgE,OAAQ9E,MAAMC,QAAQgO,QAASnD,UAAW,GAAQhK,UAAY,MAC9DgE,OAAQ9E,MAAMC,QAAQgO,QAASnD,UAAW,IAAQhK,UAAY,IAC9DgE,OAAQ9E,MAAMC,QAAQgO,QAASnD,UAAW,KAAQhK,UAAW,KAC7DgE,OAAQ9E,MAAMC,QAAQgO,QAASnD,UAAW,MAAQhK,UAAW,OAIvE,WAWI,QAASqN,GAAW5I,EAAGrF,EAASoC,EAAOkJ,EAAUjE,EAAOtB,GACpD,KAAI3D,EAAQkJ,GAAZ,CACA,GAAI9N,GAAI,EACJe,EAAI,EACJ4F,EAAKmH,EACLlH,EAAKkH,EACLvB,EAAMzM,KAAKC,MAAM+N,EAAWlJ,GAC5B8L,GAASnE,EACToE,GAASpE,CAGb,KAAKvM,EAAI,EAAGA,GAAK2G,EAAI3G,GAAKuM,EAAK,CAC3B,IAAKxL,EAAI,EAAGA,GAAK6F,EAAI7F,GAAKwL,EAAK,CAC3B,GAAIpD,GAAIpI,EAAI4F,EAAK3G,CAEjB,IADAuI,EAAKY,GAAKrJ,KAAKI,SAAW2J,IACtB6G,EAAQ,GAAKC,EAAQ,GAAzB,CAWA,IAAK,GAPD5R,GAAIwJ,EAAKY,GACTpE,EAAIwD,EAAMxH,EAAS4F,GAAM3G,EAAEuM,KAASxN,EACpCG,EAAIqJ,GAAMxH,EAAEwL,GAAO5F,EAAM3G,IAAWjB,EACpCsM,EAAI9C,GAAMxH,EAAEwL,GAAO5F,GAAM3G,EAAEuM,KAASxN,EAI/BL,EAAIgS,EAAOhS,EAAIsB,EAAGtB,IACvB,IAAK,GAAIC,GAAIgS,EAAOhS,EAAIoC,EAAGpC,IACvB,GAAID,IAAMgS,GAAS/R,IAAMgS,EAAzB,CACA,GAAI/R,GAAID,EAAIgI,EAAKjI,CACjB,MAAIE,EAAI,GAAR,CACA,GAAIgS,IAAOlS,EAAEgS,GAASnE,EAClBsE,GAAOlS,EAAEgS,GAASpE,EAClBuE,EAAKF,EAAK1R,GAAK,EAAE0R,GAAMvF,EACvB0F,EAAKH,EAAK7R,GAAK,EAAE6R,GAAM7L,CAC3BwD,GAAK3J,GAAKiS,EAAKE,GAAM,EAAEF,GAAMC,GAGrCH,EAAQ5P,GAEZ2P,EAAQ1Q,EACR2Q,GAASpE,EAGb,IAAKvM,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGzD,EAAI2G,EAAI3G,IAC5C,IAAKe,EAAI,EAAG6F,EAAKpE,EAAQmB,UAAY,EAAG5C,EAAI6F,EAAI7F,IAAK,CAEjD,GAAIiQ,GAAKjQ,EAAI4F,EAAK3G,EACdiR,EAAKlQ,EAAI+M,EAAW9N,CACxB6H,GAAEmJ,GAAIpS,GAAK2J,EAAK0I,KAc5B3O,MAAMC,QAAQ2O,MAAQ,SAASrJ,EAAGrF,GAY9B,IAAK,GATDsL,GAAWxL,MAAMxC,KAAKiO,eAAejO,KAAKiJ,IAAIvG,EAAQiB,UAAWjB,EAAQmB,WAAa,GAKtF4E,EAAO,GAAI1B,eAAciH,EAAS,IAAIA,EAAS,IAG/CjE,EAAQrH,EAAQQ,UAAYR,EAAQS,UAC/BjD,EAAI,EAAGA,EAAI,EAAGA,IACnByQ,EAAW5I,EAAGrF,EAAS1C,KAAK6H,IAAI,EAAG3H,GAAI8N,EAAUjE,EAAQ/J,KAAK6H,IAAI,EAAG,IAAM,IAAF3H,GAAQuI,EAKrFjG,OAAMC,QAAQyD,MAAM6B,GAChB7E,UAAWR,EAAQQ,UACnBC,UAAWT,EAAQS,UACnBK,SAAS,QAcrBhB,MAAMC,QAAQ4O,YAAc,SAAStJ,EAAGrF,GAYpC,IAAK,GAXDqH,GAAkD,IAAzCrH,EAAQQ,UAAYR,EAAQS,WACrCmO,EAAOtR,KAAKI,SAAW,GAAM,GAAK,EAClCmR,EAAOvR,KAAKI,SAAW,GAAM,GAAK,EAClCoR,EAAQ,GAAwB,EAAhBxR,KAAKI,SACrBqR,EAAQ,GAAwB,EAAhBzR,KAAKI,SACrBsR,EAAQ,KAAwB,GAAhB1R,KAAKI,SACrBuR,EAAgC,EAAhB3R,KAAKI,SAAb,EACRwR,EAAQ,GAAwB,EAAhB5R,KAAKI,SACrByR,EAAQ,GAAwB,EAAhB7R,KAAKI,SACrB0R,EAAQ,KAAwB,GAAhB9R,KAAKI,SACrB2R,EAAgC,EAAhB/R,KAAKI,SAAb,EACHF,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGzD,EAAI2G,EAAI3G,IAChD,IAAK,GAAIe,GAAI,EAAG6F,EAAKpE,EAAQmB,UAAY,EAAG5C,EAAI6F,EAAI7F,IAAK,CAErD,IAAK,GADDqK,GAAM,EACDjC,EAAI,EAAGA,EAAI,GAAIA,IAAK,CACzB,GAAIzK,GAAIoB,KAAK6H,IAAI,EAAE2J,GAAMnI,GAAKrJ,KAAK2O,IAAI3O,KAAK6H,IAAI,EAAE4J,EAAKpI,IAAMnJ,EAAI,IAAKF,KAAK8N,IAAI7M,GAAK0Q,EAAI1Q,GAAKyQ,GACzF7S,EAAImB,KAAK6H,IAAI,EAAE+J,GAAMvI,GAAKrJ,KAAK2O,IAAI3O,KAAK6H,IAAI,EAAEgK,EAAKxI,IAAMpI,EAAI,IAAKjB,KAAK8N,IAAI5N,GAAK6R,EAAI7R,GAAK4R,EAC7FxG,IAAOtL,KAAKgS,IAAIV,EAAK1S,EAAEA,EAAI2S,EAAK1S,EAAEA,GAEtCkJ,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAKwM,EAAMvB,EAGjCvH,MAAMC,QAAQyD,MAAM6B,EAAGrF,IAwC3BF,MAAMC,QAAQwP,wBAA0B,SAASC,GAE7C,QAASC,GAAc3G,GACnB,MAAOA,MAAS,EAAFA,GAAOA,EAAE,KAAOA,EAAE,GAQpC,IAAK,GALD4G,GAAW5P,MAAM6P,cAAcC,OAAO9P,MAAM+P,UAAUC,QAAQJ,WAC9DK,EAAU,GACVC,EAAS,GACTC,EAAWT,EAAS,GAAGU,QAAQC,OAC/BC,EAAWZ,EAAS,GAAGU,QAAQG,OAC1B7S,EAAI,EAAG+E,EAAIiN,EAAS/M,OAAQjF,EAAI+E,EAAG/E,IAYxC,GAVAgS,EAAShS,GAAG0S,QAAQI,MAAQd,EAAShS,GAAG+S,MAAQzQ,MAAM0Q,eACtDhB,EAAShS,GAAG0S,QAAQO,aAAc,EAClCf,EAAS,WAAalS,IAClBwE,KAAM,IACN0O,MAAOlB,EAAShS,GAAG0S,SAKvBH,GAAW,6BAA+BvS,EAAI,MACpC,IAANA,EAAS,CACT,GAAIC,GAAI+R,EAAShS,GAAGsM,OAChB7M,EAAIuS,EAAShS,GAAGmT,KAChBC,MAAyB,KAANnT,EACnBoT,EAAWrB,EAAShS,GAAG0S,QAAQC,OAC/BW,EAAWtB,EAAShS,GAAG0S,QAAQG,MACnC,IAAIO,EAAW,CAGPnT,EAAE,GAAKA,EAAE,GAAK,IAAGA,EAAE,IAAM,GACzBA,EAAE,GAAKA,EAAE,GAAK,IAAGA,EAAE,IAAM,EAC7B,KAAK,GAAIc,GAAI,EAAGA,EAAId,EAAEgF,OAAQlE,IAC1Bd,EAAEc,GAAKkR,EAAchS,EAAEc,IAO/B,GAAIwS,GAAeH,EACf,oBAAsBnT,EAAE,GAAK,KAAOA,EAAE,GAAK,+BAAiCA,EAAE,GAAK,KAAOA,EAAE,GAAK,iBADtER,CAE/B+S,IAAU,2CACkBxS,EAAI,mBAAqBiS,EAAcoB,EAAS3U,GAAK,KAAOuT,EAAcoB,EAAS1U,GAAK,cAAgBsT,EAAcqB,EAAS5U,GAAK,KAAOuT,EAAcqB,EAAS3U,GAAK,wBAElL4U,EAAc,mBAKvC,GAAIC,IAEAC,KAAK,EACLC,QAAQ,EAeRxB,SAAUA,EACVyB,aAAcrR,MAAM+P,UAAUC,QAAQqB,aAAaC,QAC/C,gBACA,8IAGJC,gBACI,wBACA,yBACA,yBACA,4BACA,sBACA,+BACA,SAEAvR,MAAMwR,YAAYC,OAClBzR,MAAMwR,YAAYE,QAClB1R,MAAMwR,YAAYG,wBAClB3R,MAAMwR,YAAYI,oBAClB5R,MAAMwR,YAAYK,iBAClB7R,MAAMwR,YAAYM,kBAClB9R,MAAMwR,YAAYO,kBAClB/R,MAAMwR,YAAYQ,uBAClBhS,MAAMwR,YAAYS,oBAClBjS,MAAMwR,YAAYU,uBAClBlS,MAAMwR,YAAYW,0BAClBnS,MAAMwR,YAAYY,qBAClBpS,MAAMwR,YAAYa,MAClBrS,MAAMwR,YAAYc,YAClBtS,MAAMwR,YAAYe,kBAClBvS,MAAMwR,YAAYgB,wBAClBxS,MAAMwR,YAAYiB,yBAClBzS,MAAMwR,YAAYkB,0BAClB1S,MAAMwR,YAAYmB,0BAClB3S,MAAMwR,YAAYoB,8BAElB3C,EACA,sBACA,0BACA,yBAEA,gBAEAjQ,MAAMwR,YAAYqB,yBAE7B,wGACA,yCAGW,+EAEA,oDACA,wDAA0DlD,EAAcQ,EAAS/T,GAAK,KAAOuT,EAAcQ,EAAS9T,GAAK,cAAgBsT,EAAcW,EAASlU,GAAK,KAAOuT,EAAcW,EAASjU,GAAK,gBACpM6T,EACJ,4BAGIlQ,MAAMwR,YAAYsB,qBAClB9S,MAAMwR,YAAYuB,aAClB/S,MAAMwR,YAAYwB,eAClBhT,MAAMwR,YAAYyB,kBAClBjT,MAAMwR,YAAY0B,mBAClBlT,MAAMwR,YAAY2B,qBAClBnT,MAAMwR,YAAY4B,qBAGtB,sFAEIpT,MAAMwR,YAAY6B,kBAEtB,kFACA,0BACA,4FACA,YACA,0DACA,aACA,kGAGIrT,MAAMwR,YAAY8B,eACtB,iHACItT,MAAMwR,YAAY+B,YAClBvT,MAAMwR,YAAYgC,gBACtB,2DACIxT,MAAMwR,YAAYiC,qBAClBzT,MAAMwR,YAAYkC,mBAClB1T,MAAMwR,YAAYmC,aAClB3T,MAAMwR,YAAYoC,6BAClB5T,MAAMwR,YAAYqC,mBACtB,KACFC,KAAK,MAEX,OAAO,IAAI9T,OAAM+T,eAAe7C,IAoDpClR,MAAMC,QAAQ+T,cAAgB,SAAS/R,EAAU/B,GAC7C,IAAKA,EAAQ8B,KAET,MADAiB,SAAQgR,MAAM,mFACd,EAEJ,IAAIhS,YAAoBjC,OAAMoD,eAE1B,MADAH,SAAQC,KAAK,6GACb,EAEChD,GAAQ0B,QACT1B,EAAQ0B,MAAQ,GAAI5B,OAAM6B,SAE9B,IAAI1B,IACA4F,OAAQ,KACRmO,aAAc,EACdC,aAAc,GACdC,WAAY5W,KAAKI,OACjByW,SAAU,kBACVC,QAAS5N,EAAAA,EACTyC,EAAG,EACHoL,EAAG,EAEP,KAAK,GAAI/S,KAAOrB,GACRA,EAAesB,eAAeD,KAC9BtB,EAAQsB,OAA+B,KAAjBtB,EAAQsB,GAAuBrB,EAAeqB,GAAOtB,EAAQsB,GAI3F,IAAIgT,GAA2C,gBAAnBtU,GAAQ6F,OAChC0O,EACAL,EACAM,EAAc,EAAIxU,EAAQgU,aAC1BS,EAA4C,EAAvBzU,EAAQiU,aAC7BxW,EAAIsE,EAASS,SACbkS,KACAC,EAAK3U,EAAQ8B,KAAK6S,GAAGC,QAAQC,eAAe,GAAI/U,OAAMgV,QAAQ,EAAG,EAAG,GAAI,GAAIxX,KAAKuE,GACjFyS,KACAC,EAAkBvU,EAAQkU,aAC1BA,EAAwC,gBAApBK,GAA+BjX,KAAKI,OAAS,SAASiJ,GAAK,MAAO4N,GAAgB5N,IAG1G,KAAK,GAAInJ,GAAI,EAAGyL,EAAc,EAAVjJ,EAAQiJ,EAAKzL,EAAIyL,EAAGzL,IACpC,IAAK,GAAIe,GAAI,EAAG8V,EAAIrU,EAAQqU,EAAG9V,EAAI8V,EAAG9V,IAAK,CACvC,GAAIyK,GAAMzK,EAAE0K,EAAIzL,EACZuX,EAAIhT,EAASiT,MAAMhM,GACnBiM,GAAQ,CACZ,IAAIX,EAAgB,CAChB,GAAIY,GAAKhB,EAAWlL,EAChBkM,GAAKlV,EAAQ6F,OACboP,GAAQ,EAEHC,EAAKlV,EAAQ6F,OAAS7F,EAAQgU,eAInCiB,EAAQnV,MAAMC,QAAQiF,WAAWkQ,EAAKlV,EAAQ6F,QAAU2O,GAAexU,EAAQ6F,OAASvI,KAAKI,cAIjGuX,GAAQjV,EAAQ6F,OAAOpI,EAAEsX,EAAEtY,GAAIuM,EAAK+L,EAAGvX,EAAGe,EAE9C,IAAI0W,EAAO,CAEP,GAAIF,EAAEI,OAAOC,QAAQT,GAAM3U,EAAQmU,SAC/B,QAEJ,IAAIrS,GAAO9B,EAAQ8B,KAAK8S,OAIxB,IAFA9S,EAAKuT,SAASC,KAAK7X,EAAEsX,EAAEtY,IAAI2G,IAAI3F,EAAEsX,EAAErY,IAAI0G,IAAI3F,EAAEsX,EAAElM,IAAI0M,aAAa,GAE5DvV,EAAQoU,QAAU,EAAG,CACrB,GAAIe,GAASrT,EAAKuT,SAAST,QAAQxR,IAAI2R,EAAEI,OACzCrT,GAAK0T,OAAOL,EACZ,IAAIM,GAAYV,EAAEI,OAAOC,QAAQT,EACjC,IAAIc,EAAYzV,EAAQoU,QAAS,CAC7B,GAAIsB,GAAQ1V,EAAQoU,QAAUqB,CAC9B3T,GAAKF,SAAS1F,GAAKwZ,EACnB5T,EAAKF,SAASzF,GAAKuZ,EACnB5T,EAAKF,SAASxF,GAAKsZ,GAK3B,GAFA5T,EAAKF,SAAS1F,GAAK,GAAWoB,KAAKuE,GACnCC,EAAK6T,QAAwB,EAAhBrY,KAAKI,SAAeJ,KAAKuE,IAClC7B,EAAQiU,aAAc,CACtB,GAAI2B,GAAWtY,KAAKI,SAAW+W,EAAqBzU,EAAQiU,YAC5DnS,GAAKM,MAAMlG,EAAI4F,EAAKM,MAAMhG,EAAI,EAAIwZ,EAClC9T,EAAKM,MAAMjG,GAAKyZ,EAEpBlB,EAAOpL,KAAKxH,IAMxB,GAAI6E,GAAGpE,CACP,IAAIvC,EAAQ8B,KAAKC,mBAAoBjC,OAAM+V,SAAU,CACjD,GAAIxQ,GAAI,GAAIvF,OAAM+V,QAClB,KAAKlP,EAAI,EAAGpE,EAAImS,EAAOjS,OAAQkE,EAAIpE,EAAGoE,IAAK,CACvC,GAAIoC,GAAI2L,EAAO/N,EACfoC,GAAE+M,eACFzQ,EAAEuK,MAAM7G,EAAEhH,SAAUgH,EAAEgN,QAO1B/V,EAAQ0B,MAAM0B,IAAI,GAAItD,OAAM4C,KAAK2C,EAAGrF,EAAQ8B,KAAKvB,eAIjD,KAAKoG,EAAI,EAAGpE,EAAImS,EAAOjS,OAAQkE,EAAIpE,EAAGoE,IAClC3G,EAAQ0B,MAAM0B,IAAIsR,EAAO/N,GAIjC,OAAO3G,GAAQ0B,OA+BnB5B,MAAMC,QAAQiW,cAAgB,SAASpR,EAAQ5E,EAASiW,EAAMC,GAC1DD,EAAOA,GAAQ,EACfC,EAAYA,GAAa,IACzBlW,EAAQY,UAAYZ,EAAQY,WAAa,GAEzC,IAAI8J,KACJ,KAAK,GAAIpJ,KAAOtB,GACRA,EAAQuB,eAAeD,KACvBoJ,EAAcpJ,GAAOtB,EAAQsB,GAIrCoJ,GAAczJ,WAAa,EAC3ByJ,EAAc5J,SAAU,EACxB4J,EAAclK,UAAY,EAC1BkK,EAAcjK,UAAY,CAG1B,KAAK,GAFDJ,GAAYP,MAAMC,QAAQ4E,eAAeC,EAAQ8F,GAE5ClN,EAAI,EAAG+E,EAAIlC,EAAUoC,OAAQjF,EAAI+E,EAAG/E,KACrCA,EAAIyY,GAAQ3Y,KAAKI,SAAWwY,KAC5B7V,EAAU7C,GAAK,EAGvB,OAAO,YACH,MAAO6C,KAYfP,MAAMC,QAAQ2M,YACVyJ,KAAM,SAASja,GACX,MAAO,MAAOoB,KAAKoH,IAAI,GAAKpH,KAAKgS,KAAMpT,EAAEA,KAE7Cka,KAAM,SAASla,GACX,OAAQ4D,MAAMC,QAAQ2M,WAAWyJ,KAAKja,IAE1CgQ,KAAM,SAAShQ,GAEX,MAAOA,GAAI,GAAKA,EAAE,IAAIA,EAAE,IAAI,EAAE,GAAGA,EAAE,IAAM,EAAEA,EAAEA,GAAG,EAAE,EAAEA,IAExDma,OAAQ,SAASna,GACb,OAAQ4D,MAAMC,QAAQ2M,WAAWR,KAAKhQ,IAE1Coa,KAAM,SAASpa,GAEX,QAASA,EAAE,IAAIA,EAAE,IAGrBqa,KAAM,SAASra,GACX,MAAO,IAEXsa,QAAS,SAASta,GACd,MAAO,IAAO,KAAQoB,KAAKiN,IAAI,EAAIrO,GAAKoB,KAAK8N,IAAI,EAAI9N,KAAKuE,GAAKvE,KAAKiN,IAAIrO,GAAK,OAuDrF4D,MAAMC,QAAQgN,UAAY,SAAS1H,EAAGrF,EAAS+U,EAAG7Y,EAAGC,EAAGsa,EAAGpC,EAAG9X,EAAGqP,GAC7DmJ,EAAIA,GAAKjV,MAAMC,QAAQ2M,WAAWR,KAClChQ,MAAiB,KAANA,EAAoB,GAAMA,EACrCC,MAAiB,KAANA,EAAoB,GAAMA,EACrCsa,MAAiB,KAANA,EAAoB,GAAMA,EACrCpC,MAAiB,KAANA,EAAoB,GAAMA,EACrC9X,MAAiB,KAANA,EAAoBuD,MAAM4W,eAAiBna,EACtDqP,EAAIA,GAAK9L,MAAMC,QAAQ+E,MAgBvB,KAAK,GAdDX,GAAKnE,EAAQiB,UAAY,EACzBmD,EAAKpE,EAAQmB,UAAY,EACzBwV,EAAKxS,EAAKjI,EACV0a,EAAKxS,EAAKjI,EACV0a,EAAK7W,EAAQkB,MAAQlB,EAAQiB,UAC7B6V,EAAK9W,EAAQoB,MAAQpB,EAAQmB,UAC7B4V,EAAKN,EAAII,EACTG,EAAKP,EAAIK,EACTxI,EAAK,EAAImI,EACTQ,EAAK3Z,KAAK4Z,KAAKP,EAAKI,GACpBI,EAAK7Z,KAAKC,MAAMoZ,EAAKI,GACrBK,EAAK9Z,KAAK4Z,KAAKN,EAAKI,GACpBK,EAAK/Z,KAAKC,MAAMqZ,EAAKI,GAEhBxZ,EAAIyZ,EAAIzZ,EAAI2Z,EAAI3Z,IACrB,IAAK,GAAIe,GAAI6Y,EAAI7Y,EAAI8Y,EAAI9Y,IAAK,CAC1B,GAAIoI,GAAIpI,EAAI4F,EAAK3G,EAEb8Z,GAAO9Z,EAAImZ,GAAME,EACjBU,GAAOhZ,EAAIqY,GAAME,EACjBU,EAAKla,KAAKM,KAAK0Z,EAAIA,EAAMC,EAAIA,GAC7BE,EAAMD,EAAKlJ,EACXoJ,EAAOJ,EAAMhJ,EACbqJ,EAAOJ,EAAMjJ,EAGb1H,EAAImO,EAAE0C,EAAKC,EAAMC,GAAQtD,GAAK,EAAIzI,EAAE6L,EAAKC,EAAMC,GAC/CH,GAAKf,OAAoB,KAARpR,EAAEsB,KACdpK,IAAMuD,MAAMkN,iBAAqB3H,EAAEsB,GAAGvK,GAAKwK,EAC3CrK,IAAMuD,MAAM8X,oBAAqBvS,EAAEsB,GAAGvK,GAAKwK,EAC3CrK,IAAMuD,MAAM+X,iBAAqBxS,EAAEsB,GAAGvK,GAAKwK,EAC3CrK,IAAMuD,MAAMgY,WAAqBzS,EAAEsB,GAAGvK,EAAKwK,EAC3CrK,IAAMuD,MAAM4W,eAAqBrR,EAAEsB,GAAGvK,EAAKwP,EAAE6L,EAAKC,EAAMC,GAAQtS,EAAEsB,GAAGvK,EAAIwK,EAC5D,kBAANrK,KAA0B8I,EAAEsB,GAAGvK,EAAKG,EAAE8I,EAAEsB,GAAGvK,EAAGwK,EAAG6Q,EAAKC,EAAMC","file":"THREE.Terrain.min.js"} \ No newline at end of file +{"version":3,"sources":["THREE.Terrain.js"],"names":["global","Grad","x","y","z","this","fade","t","lerp","a","b","module","noise","prototype","dot2","dot3","grad3","p","perm","Array","gradP","seed","Math","floor","i","v","random","F2","sqrt","G2","F3","G3","simplex","xin","yin","n0","n1","n2","s","j","x0","y0","i1","j1","x1","y1","x2","y2","gi0","gi1","gi2","t0","t1","t2","perlin","X","Y","n00","n01","n10","n11","u","THREE","Terrain","options","defaultOptions","after","easing","Linear","heightmap","DiamondSquare","material","maxHeight","minHeight","optimization","NONE","frequency","steps","stretch","turbulent","useBufferGeometry","xSegments","xSize","ySegments","ySize","_mesh","opt","hasOwnProperty","MeshBasicMaterial","color","scene","Object3D","rotation","PI","mesh","geometry","type","parameters","widthSegments","heightSegments","scale","width","height","l","vertices","length","Mesh","PlaneGeometry","HTMLCanvasElement","Image","fromHeightmap","console","warn","Normalize","BufferGeometry","fromGeometry","add","Turbulence","Step","Smooth","Clamp","verticesNeedUpdate","normalsNeedUpdate","computeBoundingSphere","computeFaceNormals","computeVertexNormals","GEOMIPMAP","GEOCLIPMAP","POLYGONREDUCTION","toArray2D","tgt","xl","yl","Float64Array","fromArray2D","src","toArray1D","fromArray1D","min","heightmapArray","method","arr","EaseIn","EaseOut","EaseInOut","InEaseOut","EaseInWeak","pow","EaseInStrong","g","canvas","document","createElement","context","getContext","rows","cols","spread","drawImage","data","getImageData","row","col","idx","toHeightmap","hasMax","hasMin","max","Infinity","max2","min2","k","d","createImageData","round","putImageData","actualRange","optMax","optMin","targetMax","targetMin","range","Edges","direction","distance","edges","numXSegments","numYSegments","peak","multiplier","k1","k2","top","bottom","left","right","RadialEdges","xl2","yl2","xSegmentSize","ySegmentSize","edgeRadius","vertexDistance","weight","sum","c","n","m","key","w","SmoothMedian","neighborValues","neighborKeys","sortByValue","push","sort","halfKey","median","SmoothConservative","kk","halfdiff","middle","levels","inc","heights","buckets","subset","slice","bl","avg","startHeight","abs","MultiPass","passes","clonedOptions","amp","amplitude","move","Curve","curve","scalar","Cosine","frequencyScalar","phase","cos","CosineLayers","segments","nextPowerOfTwo","size","smoothing","half","whole","e","Fault","iterations","displacement","smoothDistance","sin","Hill","feature","shape","numFeatures","heightRange","smallerSideLength","minRadius","maxRadius","Influences","coords","radius","maxX","maxY","Influence","AdditiveBlending","HillIsland","island","theta","deposit","currentKey","neighborKey","Particles","xDeviation","yDeviation","Perlin","divisor","PerlinDiamond","o","PerlinLayers","Simplex","SimplexLayers","WhiteNoise","lastX","lastY","px","py","r1","r2","kg","kd","Value","Weierstrass","dir1","dir2","r11","r12","r13","r14","r21","r22","r23","r24","exp","generateBlendedMaterial","textures","glslifyNumber","uniforms","UniformsUtils","merge","ShaderLib","lambert","declare","assign","t0Repeat","texture","repeat","t0Offset","offset","wrapS","wrapT","RepeatWrapping","needsUpdate","value","glsl","useLevels","tiRepeat","tiOffset","blendAmount","params","fog","lights","vertexShader","replace","fragmentShader","ShaderChunk","common","packing","dithering_pars_fragment","color_pars_fragment","uv_pars_fragment","uv2_pars_fragment","map_pars_fragment","alphamap_pars_fragment","aomap_pars_fragment","lightmap_pars_fragment","emissivemap_pars_fragment","envmap_pars_fragment","bsdfs","lights_pars_begin","lights_pars_maps","fog_pars_fragment","shadowmap_pars_fragment","shadowmask_pars_fragment","specularmap_pars_fragment","logdepthbuf_pars_fragment","clipping_planes_pars_fragment","clipping_planes_fragment","logdepthbuf_fragment","map_fragment","color_fragment","alphamap_fragment","alphatest_fragment","specularmap_fragment","emissivemap_fragment","lightmap_fragment","aomap_fragment","normal_flip","envmap_fragment","tonemapping_fragment","encodings_fragment","fog_fragment","premultiplied_alpha_fragment","dithering_fragment","join","ShaderMaterial","ScatterMeshes","error","smoothSpread","sizeVariance","randomness","maxSlope","maxTilt","h","spreadIsNumber","randomHeightmap","spreadRange","doubleSizeVariance","meshes","up","clone","applyAxisAngle","Vector3","f","faces","place","rv","normal","angleTo","position","copy","divideScalar","lookAt","tiltAngle","ratio","rotateY","variance","Geometry","updateMatrix","matrix","ScatterHelper","skip","threshold","Mesa","Hole","Valley","Dome","Flat","Volcano","r","NormalBlending","vx","vy","xw","yw","rx","ry","xs","ceil","xe","ys","ye","fdx","fdy","fd","fdr","fdxr","fdyr","SubtractiveBlending","MultiplyBlending","NoBlending"],"mappings":";;;;;;;CAgBA,SAAUA,GAGN,QAASC,GAAKC,EAAGC,EAAGC,GAChBC,KAAKH,EAAIA,EACTG,KAAKF,EAAIA,EACTE,KAAKD,EAAIA,EAsIb,QAASE,GAAKC,GACV,MAAOA,GAAEA,EAAEA,GAAGA,GAAK,EAAFA,EAAI,IAAI,IAG7B,QAASC,GAAKC,EAAGC,EAAGH,GAChB,OAAQ,EAAEA,GAAGE,EAAIF,EAAEG,EAhJvB,GAAIC,GAASX,EAAOY,QAQpBX,GAAKY,UAAUC,KAAO,SAASZ,EAAGC,GAC9B,MAAOE,MAAKH,EAAEA,EAAIG,KAAKF,EAAEA,GAG7BF,EAAKY,UAAUE,KAAO,SAASb,EAAGC,EAAGC,GACjC,MAAOC,MAAKH,EAAEA,EAAIG,KAAKF,EAAEA,EAAIE,KAAKD,EAAEA,EAGxC,IAAIY,IACA,GAAIf,GAAK,EAAE,EAAE,GAAG,GAAIA,IAAM,EAAE,EAAE,GAAG,GAAIA,GAAK,GAAG,EAAE,GAAG,GAAIA,IAAM,GAAG,EAAE,GACjE,GAAIA,GAAK,EAAE,EAAE,GAAG,GAAIA,IAAM,EAAE,EAAE,GAAG,GAAIA,GAAK,EAAE,GAAG,GAAG,GAAIA,IAAM,EAAE,GAAG,GACjE,GAAIA,GAAK,EAAE,EAAE,GAAG,GAAIA,GAAK,GAAG,EAAE,GAAG,GAAIA,GAAK,EAAE,GAAG,GAAG,GAAIA,GAAK,GAAG,GAAG,IAGjEgB,GAAK,IAAI,IAAI,IAAI,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,IAAI,EAAE,IAAI,IAAI,GAAG,IACnE,GAAG,GAAG,IAAI,EAAE,GAAG,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,EAAE,IAAI,IAAI,IAAI,IAAI,GAAG,EAAE,GAAG,IAAI,GAAG,GACpE,IAAI,IAAI,IAAI,IAAI,GAAG,GAAG,GAAG,GAAG,IAAI,GAAG,GAAG,IAAI,IAAI,GAAG,GAAG,IAAI,GAAG,IAAI,IAAI,IACnE,IAAI,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,IAAI,GAAG,GAAG,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,IACjE,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,GAAG,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,GAAG,GAAG,GAAG,IAClE,EAAE,IAAI,GAAG,GAAG,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IACjE,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,EAAE,GAAG,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,EAAE,IAAI,GAAG,IAChE,IAAI,IAAI,IAAI,GAAG,GAAG,IAAI,IAAI,IAAI,GAAG,IAAI,GAAG,GAAG,GAAG,GAAG,IAAI,IAAI,GAAG,GAAG,IAAI,IACnE,IAAI,IAAI,IAAI,IAAI,IAAI,EAAE,GAAG,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,GAAG,IAAI,EAAE,IACjE,GAAG,GAAG,IAAI,GAAG,GAAG,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,GAAG,IAClE,IAAI,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,IAAI,GAAG,GAAG,IAAI,IAAI,IAAI,GAAG,IACnE,IAAI,GAAG,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,IAAI,GAAG,GAAG,IAAI,EACnE,IAAI,IAAI,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,GAAG,GAAG,GAAG,GAAG,IAAI,IAAI,IAAI,IAAI,GAAG,GAAG,IACjE,GAAG,IAAI,KAEPC,EAAO,GAAIC,OAAM,KACjBC,EAAQ,GAAID,OAAM,IAItBR,GAAOU,KAAO,SAASA,GACfA,EAAO,GAAKA,EAAO,IAEnBA,GAAQ,OAGZA,EAAOC,KAAKC,MAAMF,GACdA,EAAO,MACPA,GAAQA,GAAQ,EAGpB,KAAK,GAAIG,GAAI,EAAGA,EAAI,IAAKA,IAAK,CAC1B,GAAIC,EAEAA,GADI,EAAJD,EACIP,EAAEO,GAAa,IAAPH,EAGRJ,EAAEO,GAAOH,GAAM,EAAK,IAG5BH,EAAKM,GAAKN,EAAKM,EAAI,KAAOC,EAC1BL,EAAMI,GAAKJ,EAAMI,EAAI,KAAOR,EAAMS,EAAI,MAI9Cd,EAAOU,KAAKC,KAAKI,SAGjB,IAAIC,GAAK,IAAKL,KAAKM,KAAK,GAAG,GACvBC,GAAM,EAAEP,KAAKM,KAAK,IAAI,EACtBE,EAAK,EAAE,EACPC,EAAK,EAAE,CAGXpB,GAAOqB,QAAU,SAASC,EAAKC,GAC3B,GAAIC,GAAIC,EAAIC,EAERC,GAAKL,EAAIC,GAAKP,EACdH,EAAIF,KAAKC,MAAMU,EAAIK,GACnBC,EAAIjB,KAAKC,MAAMW,EAAII,GACnB/B,GAAKiB,EAAEe,GAAGV,EACVW,EAAKP,EAAIT,EAAEjB,EACXkC,EAAKP,EAAIK,EAAEhC,EAGXmC,EAAIC,CACJH,GAAKC,GACLC,EAAK,EAAGC,EAAK,IAGbD,EAAK,EAAGC,EAAK,EAKjB,IAAIC,GAAKJ,EAAKE,EAAKb,EACfgB,EAAKJ,EAAKE,EAAKd,EACfiB,EAAKN,EAAK,EAAI,EAAIX,EAClBkB,EAAKN,EAAK,EAAI,EAAIZ,CAEtBL,IAAK,IACLe,GAAK,GACL,IAAIS,GAAM5B,EAAMI,EAAEN,EAAKqB,IACnBU,EAAM7B,EAAMI,EAAEkB,EAAGxB,EAAKqB,EAAEI,IACxBO,EAAM9B,EAAMI,EAAE,EAAEN,EAAKqB,EAAE,IAEvBY,EAAK,GAAMX,EAAGA,EAAGC,EAAGA,CACpBU,GAAK,EACLhB,EAAK,GAGLgB,GAAMA,EACNhB,EAAKgB,EAAKA,EAAKH,EAAIlC,KAAK0B,EAAIC,GAEhC,IAAIW,GAAK,GAAMR,EAAGA,EAAGC,EAAGA,CACpBO,GAAK,EACLhB,EAAK,GAGLgB,GAAMA,EACNhB,EAAKgB,EAAKA,EAAKH,EAAInC,KAAK8B,EAAIC,GAEhC,IAAIQ,GAAK,GAAMP,EAAGA,EAAGC,EAAGA,CAUxB,OATIM,GAAK,EACLhB,EAAK,GAGLgB,GAAMA,EACNhB,EAAKgB,EAAKA,EAAKH,EAAIpC,KAAKgC,EAAIC,IAIzB,IAAMZ,EAAKC,EAAKC,IAc3B1B,EAAO2C,OAAS,SAASpD,EAAGC,GAExB,GAAIoD,GAAIjC,KAAKC,MAAMrB,GACfsD,EAAIlC,KAAKC,MAAMpB,EAEnBD,IAAQqD,EACRpD,GAAQqD,EAERD,GAAQ,IACRC,GAAQ,GAGR,IAAIC,GAAMrC,EAAMmC,EAAErC,EAAKsC,IAAI1C,KAAKZ,EAAGC,GAC/BuD,EAAMtC,EAAMmC,EAAErC,EAAKsC,EAAE,IAAI1C,KAAKZ,EAAGC,EAAE,GACnCwD,EAAMvC,EAAMmC,EAAE,EAAErC,EAAKsC,IAAI1C,KAAKZ,EAAE,EAAGC,GACnCyD,EAAMxC,EAAMmC,EAAE,EAAErC,EAAKsC,EAAE,IAAI1C,KAAKZ,EAAE,EAAGC,EAAE,GAGvC0D,EAAIvD,EAAKJ,EAGb,OAAOM,GACHA,EAAKiD,EAAKE,EAAKE,GACfrD,EAAKkD,EAAKE,EAAKC,GACfvD,EAAKH,MAGdE,MA8EHyD,MAAMC,QAAU,SAASC,GACrB,GAAIC,IACAC,MAAO,KACPC,OAAQL,MAAMC,QAAQK,OACtBC,UAAWP,MAAMC,QAAQO,cACzBC,SAAU,KACVC,UAAW,IACXC,WAAY,IACZC,aAAcZ,MAAMC,QAAQY,KAC5BC,UAAW,IACXC,MAAO,EACPC,SAAS,EACTC,WAAW,EACXC,mBAAmB,EACnBC,UAAW,GACXC,MAAO,KACPC,UAAW,GACXC,MAAO,KACPC,MAAO,KAEXrB,GAAUA,KACV,KAAK,GAAIsB,KAAOrB,GACRA,EAAesB,eAAeD,KAC9BtB,EAAQsB,OAA+B,KAAjBtB,EAAQsB,GAAuBrB,EAAeqB,GAAOtB,EAAQsB,GAG3FtB,GAAQO,SAAWP,EAAQO,UAAY,GAAIT,OAAM0B,mBAAoBC,MAAO,UAI5E,IAAIC,GAAQ,GAAI5B,OAAM6B,QAEtBD,GAAME,SAAS1F,GAAK,GAAMoB,KAAKuE,EAI/B,IAAIC,GAAO9B,EAAQqB,KACnB,IAAIS,GAA+B,kBAAvBA,EAAKC,SAASC,MACdF,EAAKC,SAASE,WAAWC,gBAAkBlC,EAAQiB,WACnDa,EAAKC,SAASE,WAAWE,iBAAmBnC,EAAQmB,UAAW,CACvEW,EAAKvB,SAAWP,EAAQO,SACxBuB,EAAKM,MAAMlG,EAAI8D,EAAQkB,MAAQY,EAAKC,SAASE,WAAWI,MACxDP,EAAKM,MAAMjG,EAAI6D,EAAQoB,MAAQU,EAAKC,SAASE,WAAWK,MACxD,KAAK,GAAI9E,GAAI,EAAG+E,EAAIT,EAAKC,SAASS,SAASC,OAAQjF,EAAI+E,EAAG/E,IACtDsE,EAAKC,SAASS,SAAShF,GAAGpB,EAAI,MAIlC0F,GAAO,GAAIhC,OAAM4C,KACb,GAAI5C,OAAM6C,cAAc3C,EAAQkB,MAAOlB,EAAQoB,MAAOpB,EAAQiB,UAAWjB,EAAQmB,WACjFnB,EAAQO,SAwBhB,cArBOP,GAAQqB,MAGXrB,EAAQK,oBAAqBuC,oBAAqB5C,EAAQK,oBAAqBwC,OAC/E/C,MAAMC,QAAQ+C,cAAchB,EAAKC,SAASS,SAAUxC,GAElB,kBAAtBA,GAAQK,UACpBL,EAAQK,UAAUyB,EAAKC,SAASS,SAAUxC,GAG1C+C,QAAQC,KAAK,wDAA0DhD,EAAQK,WAEnFP,MAAMC,QAAQkD,UAAUnB,EAAM9B,GAE1BA,EAAQgB,oBACRc,EAAKC,UAAW,GAAKjC,OAAMoD,gBAAkBC,aAAarB,EAAKC,WAKnEL,EAAM0B,IAAItB,GACHJ,GAgBX5B,MAAMC,QAAQkD,UAAY,SAASnB,EAAM9B,GACrC,GAAIvC,GAAIqE,EAAKC,SAASS,QAClBxC,GAAQe,WACRjB,MAAMC,QAAQsD,WAAW5F,EAAGuC,GAE5BA,EAAQa,MAAQ,IAChBf,MAAMC,QAAQuD,KAAK7F,EAAGuC,EAAQa,OAC9Bf,MAAMC,QAAQwD,OAAO9F,EAAGuC,IAG5BF,MAAMC,QAAQyD,MAAM/F,EAAGuC,GAEM,kBAAlBA,GAAQE,OACfF,EAAQE,MAAMzC,EAAGuC,GAGrB8B,EAAKC,SAAS0B,oBAAqB,EACnC3B,EAAKC,SAAS2B,mBAAoB,EAClC5B,EAAKC,SAAS4B,wBACd7B,EAAKC,SAAS6B,qBACd9B,EAAKC,SAAS8B,wBAwDlB/D,MAAMC,QAAQY,KAAO,EACrBb,MAAMC,QAAQ+D,UAAY,EAC1BhE,MAAMC,QAAQgE,WAAa,EAC3BjE,MAAMC,QAAQiE,iBAAmB,EAkBjClE,MAAMC,QAAQkE,UAAY,SAASzB,EAAUxC,GACzC,GAAIkE,GAAM,GAAI/G,OAAM6C,EAAQiB,WACxBkD,EAAKnE,EAAQiB,UAAY,EACzBmD,EAAKpE,EAAQmB,UAAY,EACzB3D,EAAGe,CACP,KAAKf,EAAI,EAAGA,EAAI2G,EAAI3G,IAEhB,IADA0G,EAAI1G,GAAK,GAAI6G,cAAarE,EAAQmB,WAC7B5C,EAAI,EAAGA,EAAI6F,EAAI7F,IAChB2F,EAAI1G,GAAGe,GAAKiE,EAASjE,EAAI4F,EAAK3G,GAAGpB,CAGzC,OAAO8H,IAaXpE,MAAMC,QAAQuE,YAAc,SAAS9B,EAAU+B,GAC3C,IAAK,GAAI/G,GAAI,EAAG2G,EAAKI,EAAI9B,OAAQjF,EAAI2G,EAAI3G,IACrC,IAAK,GAAIe,GAAI,EAAG6F,EAAKG,EAAI/G,GAAGiF,OAAQlE,EAAI6F,EAAI7F,IACxCiE,EAASjE,EAAI4F,EAAK3G,GAAGpB,EAAImI,EAAI/G,GAAGe,IAqB5CuB,MAAMC,QAAQyE,UAAY,SAAShC,GAE/B,IAAK,GADD0B,GAAM,GAAIG,cAAa7B,EAASC,QAC3BjF,EAAI,EAAG+E,EAAI2B,EAAIzB,OAAQjF,EAAI+E,EAAG/E,IACnC0G,EAAI1G,GAAKgF,EAAShF,GAAGpB,CAEzB,OAAO8H,IAaXpE,MAAMC,QAAQ0E,YAAc,SAASjC,EAAU+B,GAC3C,IAAK,GAAI/G,GAAI,EAAG+E,EAAIjF,KAAKoH,IAAIlC,EAASC,OAAQ8B,EAAI9B,QAASjF,EAAI+E,EAAG/E,IAC9DgF,EAAShF,GAAGpB,EAAImI,EAAI/G,IAkB5BsC,MAAMC,QAAQ4E,eAAiB,SAASC,EAAQ5E,GAC5C,GAAI6E,GAAM,GAAI1H,QAAO6C,EAAQiB,UAAU,IAAMjB,EAAQmB,UAAU,IAC3DoB,EAAIsC,EAAIpC,OACRjF,CAMJ,KAAKA,EAAI,EAAGA,EAAI+E,EAAG/E,IACfqH,EAAIrH,IAAMpB,EAAG,EAOjB,KALA4D,EAAQS,UAAYT,EAAQS,WAAa,EACzCT,EAAQQ,cAAyC,KAAtBR,EAAQQ,UAA4B,EAAIR,EAAQQ,UAC3ER,EAAQc,QAAUd,EAAQc,UAAW,EACrC8D,EAAOC,EAAK7E,GACZF,MAAMC,QAAQyD,MAAMqB,EAAK7E,GACpBxC,EAAI,EAAGA,EAAI+E,EAAG/E,IACfqH,EAAIrH,GAAKqH,EAAIrH,GAAGpB,CAEpB,OAAOyI,IAMX/E,MAAMC,QAAQK,OAAS,SAASlE,GAC5B,MAAOA,IAIX4D,MAAMC,QAAQ+E,OAAS,SAAS5I,GAC5B,MAAOA,GAAEA,GAIb4D,MAAMC,QAAQgF,QAAU,SAAS7I,GAC7B,OAAQA,GAAKA,EAAI,IAMrB4D,MAAMC,QAAQiF,UAAY,SAAS9I,GAC/B,MAAOA,GAAEA,GAAG,EAAE,EAAEA,IAIpB4D,MAAMC,QAAQkF,UAAY,SAAS/I,GAC/B,GAAIC,GAAI,EAAED,EAAE,CACZ,OAAO,GAAMC,EAAEA,EAAEA,EAAI,IAIzB2D,MAAMC,QAAQmF,WAAa,SAAShJ,GAChC,MAAOoB,MAAK6H,IAAIjJ,EAAG,OAIvB4D,MAAMC,QAAQqF,aAAe,SAASlJ,GAClC,MAAOA,GAAEA,EAAEA,EAAEA,EAAEA,EAAEA,EAAEA,GAcvB4D,MAAMC,QAAQ+C,cAAgB,SAASuC,EAAGrF,GACtC,GAAIsF,GAASC,SAASC,cAAc,UAChCC,EAAUH,EAAOI,WAAW,MAC5BC,EAAO3F,EAAQmB,UAAY,EAC3ByE,EAAO5F,EAAQiB,UAAY,EAC3B4E,EAAS7F,EAAQQ,UAAYR,EAAQS,SACzC6E,GAAOjD,MAAQuD,EACfN,EAAOhD,OAASqD,EAChBF,EAAQK,UAAU9F,EAAQK,UAAW,EAAG,EAAGiF,EAAOjD,MAAOiD,EAAOhD,OAEhE,KAAK,GADDyD,GAAON,EAAQO,aAAa,EAAG,EAAGV,EAAOjD,MAAOiD,EAAOhD,QAAQyD,KAC1DE,EAAM,EAAGA,EAAMN,EAAMM,IAC1B,IAAK,GAAIC,GAAM,EAAGA,EAAMN,EAAMM,IAAO,CACjC,GAAI1I,GAAIyI,EAAML,EAAOM,EACjBC,EAAU,EAAJ3I,CACV6H,GAAE7H,GAAGpB,GAAK2J,EAAKI,GAAOJ,EAAKI,EAAI,GAAKJ,EAAKI,EAAI,IAAM,IAAMN,EAAS7F,EAAQS,YAoBtFX,MAAMC,QAAQqG,YAAc,SAASf,EAAGrF,GACpC,GAAIqG,OAAsC,KAAtBrG,EAAQQ,UACxB8F,MAAsC,KAAtBtG,EAAQS,UACxB8F,EAAMF,EAASrG,EAAQQ,WAAagG,EAAAA,EACpC9B,EAAM4B,EAAStG,EAAQS,UAAa+F,EAAAA,CACxC,KAAKH,IAAWC,EAAQ,CAGpB,IAAK,GAFDG,GAAOF,EACPG,EAAOhC,EACFiC,EAAI,EAAGpE,EAAI8C,EAAE5C,OAAQkE,EAAIpE,EAAGoE,IAC7BtB,EAAEsB,GAAGvK,EAAIqK,IAAMA,EAAOpB,EAAEsB,GAAGvK,GAC3BiJ,EAAEsB,GAAGvK,EAAIsK,IAAMA,EAAOrB,EAAEsB,GAAGvK,EAE9BiK,KAAQE,EAAME,GACdH,IAAQ5B,EAAMgC,GAEvB,GAAIpB,GAAStF,EAAQK,oBAAqBuC,mBAAoB5C,EAAQK,UAAYkF,SAASC,cAAc,UACrGC,EAAUH,EAAOI,WAAW,MAC5BC,EAAO3F,EAAQmB,UAAY,EAC3ByE,EAAO5F,EAAQiB,UAAY,EAC3B4E,EAAS7F,EAAQQ,UAAYR,EAAQS,SACzC6E,GAAOjD,MAAQuD,EACfN,EAAOhD,OAASqD,CAGhB,KAAK,GAFDiB,GAAInB,EAAQoB,gBAAgBvB,EAAOjD,MAAOiD,EAAOhD,QACjDyD,EAAOa,EAAEb,KACJE,EAAM,EAAGA,EAAMN,EAAMM,IAC1B,IAAK,GAAIC,GAAM,EAAGA,EAAMN,EAAMM,IAAO,CACjC,GAAI1I,GAAIyI,EAAML,EAAOM,EACrBC,EAAU,EAAJ3I,CACNuI,GAAKI,GAAOJ,EAAKI,EAAI,GAAKJ,EAAKI,EAAI,GAAK7I,KAAKwJ,OAAQzB,EAAE7H,GAAGpB,EAAI4D,EAAQS,WAAaoF,EAAU,KAC7FE,EAAKI,EAAI,GAAK,IAItB,MADAV,GAAQsB,aAAaH,EAAG,EAAG,GACpBtB,GAeXxF,MAAMC,QAAQyD,MAAQ,SAAS6B,EAAGrF,GAC9B,GAAI0E,GAAM8B,EAAAA,EACND,GAAOC,EAAAA,EACPjE,EAAI8C,EAAE5C,OACNjF,CAEJ,KADAwC,EAAQG,OAASH,EAAQG,QAAUL,MAAMC,QAAQK,OAC5C5C,EAAI,EAAGA,EAAI+E,EAAG/E,IACX6H,EAAE7H,GAAGpB,EAAIsI,IAAKA,EAAMW,EAAE7H,GAAGpB,GACzBiJ,EAAE7H,GAAGpB,EAAImK,IAAKA,EAAMlB,EAAE7H,GAAGpB,EAEjC,IAAI4K,GAAcT,EAAM7B,EACpBuC,EAAsC,gBAAtBjH,GAAQQ,UAAyB+F,EAAMvG,EAAQQ,UAC/D0G,EAAsC,gBAAtBlH,GAAQS,UAAyBiE,EAAM1E,EAAQS,UAC/D0G,EAAYnH,EAAQc,QAAUmG,EAAUV,EAAMU,EAASV,EAAMU,EAC7DG,EAAYpH,EAAQc,QAAUoG,EAAUxC,EAAMwC,EAASxC,EAAMwC,EAC7DG,EAAQF,EAAYC,CAKxB,KAJID,EAAYC,IACZD,EAAYF,EACZI,EAAQF,EAAYC,GAEnB5J,EAAI,EAAGA,EAAI+E,EAAG/E,IACf6H,EAAE7H,GAAGpB,EAAI4D,EAAQG,QAAQkF,EAAE7H,GAAGpB,EAAIsI,GAAOsC,GAAeK,EAAQH,GAmCxEpH,MAAMC,QAAQuH,MAAQ,SAASjC,EAAGrF,EAASuH,EAAWC,EAAUrH,EAAQsH,GACpE,GAAIC,GAAepK,KAAKC,MAAMiK,GAAYxH,EAAQkB,MAAQlB,EAAQiB,aAAe,EAC7E0G,EAAerK,KAAKC,MAAMiK,GAAYxH,EAAQoB,MAAQpB,EAAQmB,aAAe,EAC7EyG,EAAOL,EAAYvH,EAAQQ,UAAYR,EAAQS,UAC/C8F,EAAMgB,EAAYjK,KAAKiJ,IAAMjJ,KAAKoH,IAClCP,EAAKnE,EAAQiB,UAAY,EACzBmD,EAAKpE,EAAQmB,UAAY,EACzB3D,EAAGe,EAAGsJ,EAAYC,EAAIC,CAK1B,KAJA5H,EAASA,GAAUL,MAAMC,QAAQiF,UACZ,gBAAVyC,KACPA,GAASO,KAAK,EAAMC,QAAQ,EAAMC,MAAM,EAAMC,OAAO,IAEpD3K,EAAI,EAAGA,EAAI2G,EAAI3G,IAChB,IAAKe,EAAI,EAAGA,EAAIoJ,EAAcpJ,IAC1BsJ,EAAa1H,EAAO,EAAI5B,EAAIoJ,GAC5BG,EAAKvJ,EAAE4F,EAAK3G,EACZuK,GAAM/H,EAAQmB,UAAU5C,GAAG4F,EAAK3G,EAC5BiK,EAAMO,MACN3C,EAAEyC,GAAI1L,EAAImK,EAAIlB,EAAEyC,GAAI1L,GAAIwL,EAAOvC,EAAEyC,GAAI1L,GAAKyL,EAAaxC,EAAEyC,GAAI1L,IAE7DqL,EAAMQ,SACN5C,EAAE0C,GAAI3L,EAAImK,EAAIlB,EAAE0C,GAAI3L,GAAIwL,EAAOvC,EAAE0C,GAAI3L,GAAKyL,EAAaxC,EAAE0C,GAAI3L,GAIzE,KAAKoB,EAAI,EAAGA,EAAI4G,EAAI5G,IAChB,IAAKe,EAAI,EAAGA,EAAImJ,EAAcnJ,IAC1BsJ,EAAa1H,EAAO,EAAI5B,EAAImJ,GAC5BI,EAAKtK,EAAE2G,EAAG5F,EACVwJ,GAAM/H,EAAQmB,UAAU3D,GAAG2G,GAAMnE,EAAQiB,UAAU1C,GAC/CkJ,EAAMS,OACN7C,EAAEyC,GAAI1L,EAAImK,EAAIlB,EAAEyC,GAAI1L,GAAIwL,EAAOvC,EAAEyC,GAAI1L,GAAKyL,EAAaxC,EAAEyC,GAAI1L,IAE7DqL,EAAMU,QACN9C,EAAE0C,GAAI3L,EAAImK,EAAIlB,EAAE0C,GAAI3L,GAAIwL,EAAOvC,EAAE0C,GAAI3L,GAAKyL,EAAaxC,EAAE0C,GAAI3L,GAIzE0D,OAAMC,QAAQyD,MAAM6B,GAChB7E,UAAWR,EAAQQ,UACnBC,UAAWT,EAAQS,UACnBK,SAAS,KA+BjBhB,MAAMC,QAAQqI,YAAc,SAAS/C,EAAGrF,EAASuH,EAAWC,EAAUrH,GAClE,GAAIyH,GAAOL,EAAYvH,EAAQQ,UAAYR,EAAQS,UAC/C8F,EAAMgB,EAAYjK,KAAKiJ,IAAMjJ,KAAKoH,IAClCP,EAAMnE,EAAQiB,UAAY,EAC1BmD,EAAMpE,EAAQmB,UAAY,EAC1BkH,EAAW,GAALlE,EACNmE,EAAW,GAALlE,EACNmE,EAAevI,EAAQkB,MAAQlB,EAAQiB,UACvCuH,EAAexI,EAAQoB,MAAQpB,EAAQmB,UACvCsH,EAAsD,GAAzCnL,KAAKoH,IAAI1E,EAAQkB,MAAOlB,EAAQoB,OAAeoG,EAC5DhK,EAAGe,EAAGsJ,EAAYlB,EAAG+B,CACzB,KAAKlL,EAAI,EAAGA,EAAI2G,EAAI3G,IAChB,IAAKe,EAAI,EAAGA,EAAI+J,EAAK/J,IACjBoI,EAAIpI,EAAE4F,EAAK3G,EACXkL,EAAiBpL,KAAKoH,IAAI+D,EAAYnL,KAAKM,MAAMyK,EAAI7K,GAAG+K,GAAcF,EAAI7K,GAAG+K,GAAgBD,EAAI/J,GAAGiK,GAAcF,EAAI/J,GAAGiK,GAAgBhB,GACrIkB,EAAiB,IACrBb,EAAa1H,EAAOuI,EAAiBD,GACrCpD,EAAEsB,GAAGvK,EAAImK,EAAIlB,EAAEsB,GAAGvK,GAAIwL,EAAOvC,EAAEsB,GAAGvK,GAAKyL,EAAaxC,EAAEsB,GAAGvK,GAEzDuK,GAAK3G,EAAQmB,UAAU5C,GAAG4F,EAAK3G,EAC/B6H,EAAEsB,GAAGvK,EAAImK,EAAIlB,EAAEsB,GAAGvK,GAAIwL,EAAOvC,EAAEsB,GAAGvK,GAAKyL,EAAaxC,EAAEsB,GAAGvK,KAmBrE0D,MAAMC,QAAQwD,OAAS,SAAS8B,EAAGrF,EAAS2I,GAExC,IAAK,GADDtI,GAAY,GAAIgE,cAAagB,EAAE5C,QAC1BjF,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGmD,EAAKpE,EAAQmB,UAAY,EAAG3D,EAAI2G,EAAI3G,IAC5E,IAAK,GAAIe,GAAI,EAAGA,EAAI6F,EAAI7F,IAAK,CAGzB,IAAK,GAFDqK,GAAM,EACNC,EAAI,EACCC,GAAK,EAAGA,GAAK,EAAGA,IACrB,IAAK,GAAIC,IAAK,EAAGA,GAAK,EAAGA,IAAK,CAC1B,GAAIC,IAAOzK,EAAEuK,GAAG3E,EAAK3G,EAAIuL,MACH,KAAX1D,EAAE2D,IAAwBxL,EAAEuL,GAAK,GAAKxK,EAAEuK,GAAK,GAAKtL,EAAEuL,EAAI5E,GAAM5F,EAAEuK,EAAI1E,IAC3EwE,GAAOvD,EAAE2D,GAAK5M,EACdyM,KAIZxI,EAAU9B,EAAE4F,EAAK3G,GAAKoL,EAAMC,EAGpCF,EAASA,GAAU,CAEnB,KAAK,GADDM,GAAI,GAAK,EAAIN,GACRhC,EAAI,EAAGpE,EAAI8C,EAAE5C,OAAQkE,EAAIpE,EAAGoE,IACjCtB,EAAEsB,GAAGvK,GAAKiE,EAAUsG,GAAKtB,EAAEsB,GAAGvK,EAAIuM,GAAUM,GASpDnJ,MAAMC,QAAQmJ,aAAe,SAAS7D,EAAGrF,GAOrC,IAAK,GANDK,GAAY,GAAIgE,cAAagB,EAAE5C,QAC/B0G,KACAC,KACAC,EAAc,SAAS5M,EAAGC,GACtB,MAAOyM,GAAe1M,GAAK0M,EAAezM,IAEzCc,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGmD,EAAKpE,EAAQmB,UAAY,EAAG3D,EAAI2G,EAAI3G,IAC5E,IAAK,GAAIe,GAAI,EAAGA,EAAI6F,EAAI7F,IAAK,CACzB4K,EAAe1G,OAAS,EACxB2G,EAAa3G,OAAS,CACtB,KAAK,GAAIqG,IAAK,EAAGA,GAAK,EAAGA,IACrB,IAAK,GAAIC,IAAK,EAAGA,GAAK,EAAGA,IAAK,CAC1B,GAAIC,IAAOzK,EAAEuK,GAAG3E,EAAK3G,EAAIuL,MACH,KAAX1D,EAAE2D,IAAwBxL,EAAEuL,GAAK,GAAKxK,EAAEuK,GAAK,GAAKtL,EAAEuL,EAAI5E,GAAM5F,EAAEuK,EAAI1E,IAC3E+E,EAAeG,KAAKjE,EAAE2D,GAAK5M,GAC3BgN,EAAaE,KAAKN,IAI9BI,EAAaG,KAAKF,EAClB,IAAIG,GAAUlM,KAAKC,MAA0B,GAApB6L,EAAa3G,QAClCgH,CAEAA,GADAL,EAAa3G,OAAS,GAAM,EACnB4C,EAAE+D,EAAaI,IAAUpN,EAGqC,IAA7DiJ,EAAE+D,EAAaI,EAAQ,IAAIpN,EAAIiJ,EAAE+D,EAAaI,IAAUpN,GAEtEiE,EAAU9B,EAAE4F,EAAK3G,GAAKiM,EAG9B,IAAK,GAAI9C,GAAI,EAAGpE,EAAI8C,EAAE5C,OAAQkE,EAAIpE,EAAGoE,IACjCtB,EAAEsB,GAAGvK,EAAIiE,EAAUsG,IAoB3B7G,MAAMC,QAAQ2J,mBAAqB,SAASrE,EAAGrF,EAAS6H,GAEpD,IAAK,GADDxH,GAAY,GAAIgE,cAAagB,EAAE5C,QAC1BjF,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGmD,EAAKpE,EAAQmB,UAAY,EAAG3D,EAAI2G,EAAI3G,IAC5E,IAAK,GAAIe,GAAI,EAAGA,EAAI6F,EAAI7F,IAAK,CAGzB,IAAK,GAFDgI,IAAOC,EAAAA,EACP9B,EAAM8B,EAAAA,EACDsC,GAAK,EAAGA,GAAK,EAAGA,IACrB,IAAK,GAAIC,IAAK,EAAGA,GAAK,EAAGA,IAAK,CAC1B,GAAIC,IAAOzK,EAAEuK,GAAG3E,EAAK3G,EAAIuL,MACH,KAAX1D,EAAE2D,IAAwBF,GAAKC,GAAKvL,EAAEuL,GAAK,GAAKxK,EAAEuK,GAAK,GAAKtL,EAAEuL,EAAI5E,GAAM5F,EAAEuK,EAAI1E,IACjFiB,EAAE2D,GAAK5M,EAAIsI,IAAKA,EAAMW,EAAE2D,GAAK5M,GAC7BiJ,EAAE2D,GAAK5M,EAAImK,IAAKA,EAAMlB,EAAE2D,GAAK5M,IAI7C,GAAIuN,GAAKpL,EAAE4F,EAAK3G,CAChB,IAA0B,gBAAfqK,GAAyB,CAChC,GAAI+B,GAAyB,IAAbrD,EAAM7B,GAClBmF,EAASnF,EAAMkF,CACnBrD,GAAMsD,EAASD,EAAW/B,EAC1BnD,EAAMmF,EAASD,EAAW/B,EAE9BxH,EAAUsJ,GAAMtE,EAAEsE,GAAIvN,EAAImK,EAAMA,EAAOlB,EAAEsE,GAAIvN,EAAIsI,EAAMA,EAAMW,EAAEsE,GAAIvN,EAG3E,IAAK,GAAIuK,GAAI,EAAGpE,EAAI8C,EAAE5C,OAAQkE,EAAIpE,EAAGoE,IACjCtB,EAAEsB,GAAGvK,EAAIiE,EAAUsG,IAc3B7G,MAAMC,QAAQuD,KAAO,SAAS+B,EAAGyE,GAE7B,GAAItM,GAAI,EACJe,EAAI,EACJgE,EAAI8C,EAAE5C,OACNsH,EAAMzM,KAAKC,MAAMgF,EAAIuH,GACrBE,EAAU,GAAI7M,OAAMoF,GACpB0H,EAAU,GAAI9M,OAAM2M,EAIxB,SAHsB,KAAXA,IACPA,EAASxM,KAAKC,MAAMD,KAAK6H,IAAM,GAAF5C,EAAO,OAEnC/E,EAAI,EAAGA,EAAI+E,EAAG/E,IACfwM,EAAQxM,GAAK6H,EAAE7H,GAAGpB,CAGtB,KADA4N,EAAQT,KAAK,SAAS9M,EAAGC,GAAK,MAAOD,GAAIC,IACpCc,EAAI,EAAGA,EAAIsM,EAAQtM,IAAK,CAEzB,GAAI0M,GAASF,EAAQG,MAAM3M,EAAEuM,GAAMvM,EAAE,GAAGuM,GACpCnB,EAAM,EACNwB,EAAKF,EAAOzH,MAChB,KAAKlE,EAAI,EAAGA,EAAI6L,EAAI7L,IAChBqK,GAAOsB,EAAO3L,EAElB0L,GAAQzM,IACJkH,IAAKwF,EAAO,GACZ3D,IAAK2D,EAAOA,EAAOzH,OAAO,GAC1B4H,IAAKzB,EAAMwB,GAKnB,IAAK5M,EAAI,EAAGA,EAAI+E,EAAG/E,IAAK,CACpB,GAAI8M,GAAcjF,EAAE7H,GAAGpB,CACvB,KAAKmC,EAAI,EAAGA,EAAIuL,EAAQvL,IACpB,GAAI+L,GAAeL,EAAQ1L,GAAGmG,KAAO4F,GAAeL,EAAQ1L,GAAGgI,IAAK,CAChElB,EAAE7H,GAAGpB,EAAI6N,EAAQ1L,GAAG8L,GACpB,UAWhBvK,MAAMC,QAAQsD,WAAa,SAASgC,EAAGrF,GAEnC,IAAK,GADDqH,GAAQrH,EAAQQ,UAAYR,EAAQS,UAC/BjD,EAAI,EAAG+E,EAAI8C,EAAE5C,OAAQjF,EAAI+E,EAAG/E,IACjC6H,EAAE7H,GAAGpB,EAAI4D,EAAQS,UAAYnD,KAAKiN,IAAmC,GAA9BlF,EAAE7H,GAAGpB,EAAI4D,EAAQS,WAAiB4G,IA2BjFvH,MAAMC,QAAQyK,UAAY,SAASnF,EAAGrF,EAASyK,GAC3C,GAAIC,KACJ,KAAK,GAAIpJ,KAAOtB,GACRA,EAAQuB,eAAeD,KACvBoJ,EAAcpJ,GAAOtB,EAAQsB,GAIrC,KAAK,GADD+F,GAAQrH,EAAQQ,UAAYR,EAAQS,UAC/BjD,EAAI,EAAG+E,EAAIkI,EAAOhI,OAAQjF,EAAI+E,EAAG/E,IAAK,CAC3C,GAAImN,OAAqC,KAAxBF,EAAOjN,GAAGoN,UAA4B,EAAIH,EAAOjN,GAAGoN,UACjEC,EAAO,IAAOxD,EAAQA,EAAQsD,EAClCD,GAAclK,UAAYR,EAAQQ,UAAYqK,EAC9CH,EAAcjK,UAAYT,EAAQS,UAAYoK,EAC9CH,EAAc9J,cAA2C,KAAxB6J,EAAOjN,GAAGoD,UAA4BZ,EAAQY,UAAY6J,EAAOjN,GAAGoD,UACrG6J,EAAOjN,GAAGoH,OAAOS,EAAGqF,KAsB5B5K,MAAMC,QAAQ+K,MAAQ,SAASzF,EAAGrF,EAAS+K,GAGvC,IAAK,GAFD1D,GAAkD,IAAzCrH,EAAQQ,UAAYR,EAAQS,WACrCuK,EAAShL,EAAQY,WAAatD,KAAKoH,IAAI1E,EAAQiB,UAAWjB,EAAQmB,WAAa,GAC1E3D,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGmD,EAAKpE,EAAQmB,UAAY,EAAG3D,EAAI2G,EAAI3G,IAC5E,IAAK,GAAIe,GAAI,EAAGA,EAAI6F,EAAI7F,IACpB8G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAK2O,EAAMvN,EAAIwN,EAAQzM,EAAIyM,GAAU3D,GAU/DvH,MAAMC,QAAQkL,OAAS,SAAS5F,EAAGrF,GAI/B,IAAK,GAHD4K,GAAsD,IAAzC5K,EAAQQ,UAAYR,EAAQS,WACzCyK,EAAkBlL,EAAQY,UAAYtD,KAAKuE,IAAMvE,KAAKoH,IAAI1E,EAAQiB,UAAWjB,EAAQmB,WAAa,GAClGgK,EAAQ7N,KAAKI,SAAWJ,KAAKuE,GAAK,EAC7BrE,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGzD,EAAI2G,EAAI3G,IAChD,IAAK,GAAIe,GAAI,EAAG6F,EAAKpE,EAAQmB,UAAY,EAAG5C,EAAI6F,EAAI7F,IAChD8G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAKwO,GAAatN,KAAK8N,IAAI5N,EAAI0N,EAAkBC,GAAS7N,KAAK8N,IAAI7M,EAAI2M,EAAkBC,KAUnHrL,MAAMC,QAAQsL,aAAe,SAAShG,EAAGrF,GACrCF,MAAMC,QAAQyK,UAAUnF,EAAGrF,IACrB4E,OAAQ9E,MAAMC,QAAQkL,OAA0BrK,UAAY,MAC5DgE,OAAQ9E,MAAMC,QAAQkL,OAAQL,UAAW,GAAOhK,UAAY,KAC5DgE,OAAQ9E,MAAMC,QAAQkL,OAAQL,UAAW,IAAOhK,UAAY,KAC5DgE,OAAQ9E,MAAMC,QAAQkL,OAAQL,UAAW,KAAOhK,UAAY,OAiBtEd,MAAMC,QAAQO,cAAgB,SAAS+E,EAAGrF,GAGtC,GAAIsL,GAAWxL,MAAMxC,KAAKiO,eAAejO,KAAKiJ,IAAIvG,EAAQiB,UAAWjB,EAAQmB,WAAa,GAGtFqK,EAAOF,EAAW,EAClBjL,KACAoL,EAAazL,EAAQQ,UAAYR,EAAQS,UACzCjD,EACAe,EACA4F,EAAKnE,EAAQiB,UAAY,EACzBmD,EAAKpE,EAAQmB,UAAY,CAC7B,KAAK3D,EAAI,EAAGA,GAAK8N,EAAU9N,IACvB6C,EAAU7C,GAAK,GAAI6G,cAAaiH,EAAS,EAI7C,KAAK,GAAI/I,GAAI+I,EAAU/I,GAAK,EAAGA,GAAK,EAAG,CACnC,GAAImJ,GAAOpO,KAAKwJ,MAAQ,GAAFvE,GAClBoJ,EAAQrO,KAAKwJ,MAAMvE,GACnBrG,EACAC,EACAkO,EACAzD,EACAgF,CAGJ,KAFAH,GAAa,EAERvP,EAAI,EAAGA,EAAIoP,EAAUpP,GAAKyP,EAC3B,IAAKxP,EAAI,EAAGA,EAAImP,EAAUnP,GAAKwP,EAC3B/E,EAAItJ,KAAKI,SAAW+N,EAAY,EAAIA,EACpCpB,EAAMhK,EAAUnE,GAAGC,GACbkE,EAAUnE,EAAEyP,GAAOxP,GACnBkE,EAAUnE,GAAGC,EAAEwP,GACftL,EAAUnE,EAAEyP,GAAOxP,EAAEwP,GAC3BtB,GAAO,IACPhK,EAAUnE,EAAEwP,GAAMvP,EAAEuP,GAAQrB,EAAMzD,CAI1C,KAAK1K,EAAI,EAAGA,EAAIoP,EAAUpP,GAAKwP,EAC3B,IAAKvP,GAAKD,EAAEwP,GAAQnJ,EAAGpG,EAAImP,EAAUnP,GAAKoG,EACtCqE,EAAItJ,KAAKI,SAAW+N,EAAY,EAAIA,EACpCpB,EAAMhK,GAAWnE,EAAEwP,EAAKF,GAAMA,GAAMrP,GAC9BkE,GAAWnE,EAAEwP,GAAMF,GAAMrP,GACzBkE,EAAUnE,IAAIC,EAAEuP,GAAMF,GACtBnL,EAAUnE,IAAIC,EAAEuP,EAAKF,GAAMA,GACjCnB,GAAO,IACPA,GAAOzD,EACPvG,EAAUnE,GAAGC,GAAKkO,EAER,IAANnO,IAASmE,EAAUiL,GAAUnP,GAAKkO,GAC5B,IAANlO,IAASkE,EAAUnE,GAAGoP,GAAYjB,GAMlD,IAAK7M,EAAI,EAAGA,EAAI2G,EAAI3G,IAChB,IAAKe,EAAI,EAAGA,EAAI6F,EAAI7F,IAChB8G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAKiE,EAAU7C,GAAGe,IAgB5CuB,MAAMC,QAAQ8L,MAAQ,SAASxG,EAAGrF,GAM9B,IAAK,GALD4G,GAAItJ,KAAKM,KAAKoC,EAAQiB,UAAUjB,EAAQiB,UAAYjB,EAAQmB,UAAUnB,EAAQmB,WAC9E2K,EAAalF,EAAI5G,EAAQY,UACzByG,EAAkD,IAAzCrH,EAAQQ,UAAYR,EAAQS,WACrCsL,EAAe1E,EAAQyE,EACvBE,EAAiB1O,KAAKoH,IAAI1E,EAAQkB,MAAQlB,EAAQiB,UAAWjB,EAAQoB,MAAQpB,EAAQmB,WAAanB,EAAQY,UACrG+F,EAAI,EAAGA,EAAImF,EAAYnF,IAK5B,IAAK,GAJDlJ,GAAIH,KAAKI,SACTjB,EAAIa,KAAK2O,IAAIxO,EAAIH,KAAKuE,GAAK,GAC3BnF,EAAIY,KAAK8N,IAAI3N,EAAIH,KAAKuE,GAAK,GAC3BgH,EAAIvL,KAAKI,SAAWkJ,EAAM,GAAFA,EACnBpJ,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGzD,EAAI2G,EAAI3G,IAChD,IAAK,GAAIe,GAAI,EAAG6F,EAAKpE,EAAQmB,UAAY,EAAG5C,EAAI6F,EAAI7F,IAAK,CACrD,GAAIiJ,GAAW/K,EAAEe,EAAId,EAAE6B,EAAIsK,CACvBrB,GAAWwE,EACX3G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAK2P,EAEdvE,GAAYwE,EACjB3G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAK2P,EAGnB1G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAKkB,KAAK8N,IAAI5D,EAAWwE,EAAiB1O,KAAKuE,GAAK,GAAKkK,IAuC3FjM,MAAMC,QAAQmM,KAAO,SAAS7G,EAAGrF,EAASmM,EAASC,GAC/C,GAAIxL,GAAgC,EAApBZ,EAAQY,UACpByL,EAAczL,EAAYA,EAAY,GACtC0L,EAActM,EAAQQ,UAAYR,EAAQS,UAC1CA,EAAY6L,GAAe1L,EAAYA,GACvCJ,EAAY8L,EAAc1L,EAC1B2L,EAAoBjP,KAAKoH,IAAI1E,EAAQkB,MAAOlB,EAAQoB,OACpDoL,EAAYD,GAAqB3L,EAAYA,GAC7C6L,EAAYF,EAAoB3L,CACpCuL,GAAUA,GAAWrM,MAAMC,QAAQ2M,WAAWR,IAG9C,KAAK,GADDS,IAAWzQ,EAAG,EAAGC,EAAG,GACfqB,EAAI,EAAGA,EAAI6O,EAAa7O,IAAK,CAClC,GAAIoP,GAAStP,KAAKI,UAAY+O,EAAYD,GAAaA,EACnDlK,EAAShF,KAAKI,UAAY8C,EAAYC,GAAaA,EACnDiE,EAAM,EAAIkI,EACVC,EAAO7M,EAAQkB,MAAQ0L,EACvBE,EAAO9M,EAAQoB,MAAQwL,CAC3BD,GAAOzQ,EAAIoB,KAAKI,SAChBiP,EAAOxQ,EAAImB,KAAKI,SACK,kBAAV0O,IAAsBA,EAAMO,GACvC7M,MAAMC,QAAQgN,UACV1H,EAAGrF,EACHmM,EACAQ,EAAOzQ,EAAGyQ,EAAOxQ,EACjByQ,EAAQtK,EACRxC,MAAMkN,iBACNlN,MAAMC,QAAQqF,gBA6B1BtF,MAAMC,QAAQkN,WAAa,WACvB,GAAIC,GAAS,SAASP,GAClB,GAAIQ,GAAQ7P,KAAKI,SAAWJ,KAAKuE,GAAK,CACtC8K,GAAOzQ,EAAI,GAAMoB,KAAK8N,IAAI+B,GAASR,EAAOzQ,EAAI,GAC9CyQ,EAAOxQ,EAAI,GAAMmB,KAAK2O,IAAIkB,GAASR,EAAOxQ,EAAI,GAElD,OAAO,UAASkJ,EAAGrF,EAASmM,GACxBrM,MAAMC,QAAQmM,KAAK7G,EAAGrF,EAASmM,EAASe,OAIhD,WAII,QAASE,GAAQ/H,EAAG7H,EAAGe,EAAG4F,EAAI4H,GAG1B,IAAK,GAFDsB,GAAa9O,EAAI4F,EAAK3G,EAEjBmJ,EAAI,EAAGA,EAAI,EAAGA,IAAK,CAExB,OADQrJ,KAAKC,MAAsB,EAAhBD,KAAKI,WAEpB,IAAK,GAAGF,GAAK,MACb,KAAK,GAAGA,GAAK,MACb,KAAK,GAAGe,GAAK,MACb,KAAK,GAAGA,GAAK,MACb,KAAK,GAAGf,IAAKe,GAAK,MAClB,KAAK,GAAGf,IAAKe,GAAK,MAClB,KAAK,GAAGf,IAAKe,GAAK,MAClB,KAAK,GAAGf,IAAKe,GAAK,OAEtB,GAAI+O,GAAc/O,EAAI4F,EAAK3G,CAE3B,QAA8B,KAAnB6H,EAAEiI,IACT,GAAIjI,EAAEiI,GAAalR,EAAIiJ,EAAEgI,GAAYjR,EAEjC,MADAgR,GAAQ/H,EAAG7H,EAAGe,EAAG4F,EAAI4H,OACrB,OAIH,IAAIzO,KAAKI,SAAW,GAErB,MADA2H,GAAEgI,GAAYjR,GAAK2P,MACnB,GAGR1G,EAAEgI,GAAYjR,GAAK2P,EAkBvBjM,MAAMC,QAAQwN,UAAY,SAASlI,EAAGrF,GAQlC,IAAK,GAPD8L,GAAaxO,KAAKM,KAAKoC,EAAQiB,UAAUjB,EAAQiB,UAAYjB,EAAQmB,UAAUnB,EAAQmB,WAAanB,EAAQY,UAAY,IACxHuD,EAAKnE,EAAQiB,UAAY,EACzB8K,GAAgB/L,EAAQQ,UAAYR,EAAQS,WAAaqL,EAAa,IACtEtO,EAAIF,KAAKC,MAAMD,KAAKI,SAAWsC,EAAQiB,WACvC1C,EAAIjB,KAAKC,MAAMD,KAAKI,SAAWsC,EAAQmB,WACvCqM,EAA6B,GAAhBlQ,KAAKI,SAAiB,GACnC+P,EAA6B,GAAhBnQ,KAAKI,SAAiB,GAC9BiJ,EAAI,EAAGA,EAAImF,EAAYnF,IAAK,CACjCyG,EAAQ/H,EAAG7H,EAAGe,EAAG4F,EAAI4H,EACrB,IAAInF,GAAItJ,KAAKI,SAAWJ,KAAKuE,GAAK,CAC9B8E,GAAI,KAAS,IACb6G,EAA6B,GAAhBlQ,KAAKI,SAAiB,GACnC+P,EAA6B,GAAhBnQ,KAAKI,SAAiB,IAEnCiJ,EAAI,KAAQ,IACZnJ,EAAIF,KAAKC,MAAMyC,EAAQiB,WAAW,GAAIuM,GAAclQ,KAAK8N,IAAIxE,GAAKtJ,KAAKI,SAAWsC,EAAQiB,WAAW,GAAI3D,KAAKiN,IAAIiD,KAClHjP,EAAIjB,KAAKC,MAAMyC,EAAQmB,WAAW,GAAIsM,GAAcnQ,KAAK2O,IAAIrF,GAAKtJ,KAAKI,SAAWsC,EAAQmB,WAAW,GAAI7D,KAAKiN,IAAIkD,WAYlI3N,MAAMC,QAAQ2N,OAAS,SAASrI,EAAGrF,GAC/BpD,MAAMS,KAAKC,KAAKI,SAGhB,KAAK,GAFD2J,GAAkD,IAAzCrH,EAAQQ,UAAYR,EAAQS,WACrCkN,GAAWrQ,KAAKoH,IAAI1E,EAAQiB,UAAWjB,EAAQmB,WAAa,GAAKnB,EAAQY,UACpEpD,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGzD,EAAI2G,EAAI3G,IAChD,IAAK,GAAIe,GAAI,EAAG6F,EAAKpE,EAAQmB,UAAY,EAAG5C,EAAI6F,EAAI7F,IAChD8G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAKQ,MAAM0C,OAAO9B,EAAImQ,EAASpP,EAAIoP,GAAWtG,GAUxEvH,MAAMC,QAAQ6N,cAAgB,SAASvI,EAAGrF,GACtCF,MAAMC,QAAQyK,UAAUnF,EAAGrF,IACrB4E,OAAQ9E,MAAMC,QAAQ2N,SACtB9I,OAAQ9E,MAAMC,QAAQO,cAAesK,UAAW,MAChDhG,OAAQ,SAASS,EAAGwI,GAAK,MAAO/N,OAAMC,QAAQmJ,aAAa7D,EAAGwI,QASxE/N,MAAMC,QAAQ+N,aAAe,SAASzI,EAAGrF,GACrCF,MAAMC,QAAQyK,UAAUnF,EAAGrF,IACrB4E,OAAQ9E,MAAMC,QAAQ2N,OAAyB9M,UAAY,OAC3DgE,OAAQ9E,MAAMC,QAAQ2N,OAAQ9C,UAAW,IAAMhK,UAAY,MAC3DgE,OAAQ9E,MAAMC,QAAQ2N,OAAQ9C,UAAW,IAAMhK,UAAY,IAC3DgE,OAAQ9E,MAAMC,QAAQ2N,OAAQ9C,UAAW,IAAMhK,UAAW,OAYpEd,MAAMC,QAAQgO,QAAU,SAAS1I,EAAGrF,GAChCpD,MAAMS,KAAKC,KAAKI,SAGhB,KAAK,GAFD2J,GAAkD,IAAzCrH,EAAQQ,UAAYR,EAAQS,WACrCkN,EAAiE,GAAtDrQ,KAAKoH,IAAI1E,EAAQiB,UAAWjB,EAAQmB,WAAa,GAASnB,EAAQY,UACxEpD,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGzD,EAAI2G,EAAI3G,IAChD,IAAK,GAAIe,GAAI,EAAG6F,EAAKpE,EAAQmB,UAAY,EAAG5C,EAAI6F,EAAI7F,IAChD8G,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAKQ,MAAMoB,QAAQR,EAAImQ,EAASpP,EAAIoP,GAAWtG,GAUzEvH,MAAMC,QAAQiO,cAAgB,SAAS3I,EAAGrF,GACtCF,MAAMC,QAAQyK,UAAUnF,EAAGrF,IACrB4E,OAAQ9E,MAAMC,QAAQgO,QAA4BnN,UAAY,OAC9DgE,OAAQ9E,MAAMC,QAAQgO,QAASnD,UAAW,GAAQhK,UAAY,MAC9DgE,OAAQ9E,MAAMC,QAAQgO,QAASnD,UAAW,IAAQhK,UAAY,IAC9DgE,OAAQ9E,MAAMC,QAAQgO,QAASnD,UAAW,KAAQhK,UAAW,KAC7DgE,OAAQ9E,MAAMC,QAAQgO,QAASnD,UAAW,MAAQhK,UAAW,OAIvE,WAWI,QAASqN,GAAW5I,EAAGrF,EAASoC,EAAOkJ,EAAUjE,EAAOtB,GACpD,KAAI3D,EAAQkJ,GAAZ,CACA,GAAI9N,GAAI,EACJe,EAAI,EACJ4F,EAAKmH,EACLlH,EAAKkH,EACLvB,EAAMzM,KAAKC,MAAM+N,EAAWlJ,GAC5B8L,GAASnE,EACToE,GAASpE,CAGb,KAAKvM,EAAI,EAAGA,GAAK2G,EAAI3G,GAAKuM,EAAK,CAC3B,IAAKxL,EAAI,EAAGA,GAAK6F,EAAI7F,GAAKwL,EAAK,CAC3B,GAAIpD,GAAIpI,EAAI4F,EAAK3G,CAEjB,IADAuI,EAAKY,GAAKrJ,KAAKI,SAAW2J,IACtB6G,EAAQ,GAAKC,EAAQ,GAAzB,CAWA,IAAK,GAPD5R,GAAIwJ,EAAKY,GACTpE,EAAIwD,EAAMxH,EAAS4F,GAAM3G,EAAEuM,KAASxN,EACpCG,EAAIqJ,GAAMxH,EAAEwL,GAAO5F,EAAM3G,IAAWjB,EACpCsM,EAAI9C,GAAMxH,EAAEwL,GAAO5F,GAAM3G,EAAEuM,KAASxN,EAI/BL,EAAIgS,EAAOhS,EAAIsB,EAAGtB,IACvB,IAAK,GAAIC,GAAIgS,EAAOhS,EAAIoC,EAAGpC,IACvB,GAAID,IAAMgS,GAAS/R,IAAMgS,EAAzB,CACA,GAAI/R,GAAID,EAAIgI,EAAKjI,CACjB,MAAIE,EAAI,GAAR,CACA,GAAIgS,IAAOlS,EAAEgS,GAASnE,EAClBsE,GAAOlS,EAAEgS,GAASpE,EAClBuE,EAAKF,EAAK1R,GAAK,EAAE0R,GAAMvF,EACvB0F,EAAKH,EAAK7R,GAAK,EAAE6R,GAAM7L,CAC3BwD,GAAK3J,GAAKiS,EAAKE,GAAM,EAAEF,GAAMC,GAGrCH,EAAQ5P,GAEZ2P,EAAQ1Q,EACR2Q,GAASpE,EAGb,IAAKvM,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGzD,EAAI2G,EAAI3G,IAC5C,IAAKe,EAAI,EAAG6F,EAAKpE,EAAQmB,UAAY,EAAG5C,EAAI6F,EAAI7F,IAAK,CAEjD,GAAIiQ,GAAKjQ,EAAI4F,EAAK3G,EACdiR,EAAKlQ,EAAI+M,EAAW9N,CACxB6H,GAAEmJ,GAAIpS,GAAK2J,EAAK0I,KAc5B3O,MAAMC,QAAQ2O,MAAQ,SAASrJ,EAAGrF,GAY9B,IAAK,GATDsL,GAAWxL,MAAMxC,KAAKiO,eAAejO,KAAKiJ,IAAIvG,EAAQiB,UAAWjB,EAAQmB,WAAa,GAKtF4E,EAAO,GAAI1B,eAAciH,EAAS,IAAIA,EAAS,IAG/CjE,EAAQrH,EAAQQ,UAAYR,EAAQS,UAC/BjD,EAAI,EAAGA,EAAI,EAAGA,IACnByQ,EAAW5I,EAAGrF,EAAS1C,KAAK6H,IAAI,EAAG3H,GAAI8N,EAAUjE,EAAQ/J,KAAK6H,IAAI,EAAG,IAAM,IAAF3H,GAAQuI,EAKrFjG,OAAMC,QAAQyD,MAAM6B,GAChB7E,UAAWR,EAAQQ,UACnBC,UAAWT,EAAQS,UACnBK,SAAS,QAcrBhB,MAAMC,QAAQ4O,YAAc,SAAStJ,EAAGrF,GAYpC,IAAK,GAXDqH,GAAkD,IAAzCrH,EAAQQ,UAAYR,EAAQS,WACrCmO,EAAOtR,KAAKI,SAAW,GAAM,GAAK,EAClCmR,EAAOvR,KAAKI,SAAW,GAAM,GAAK,EAClCoR,EAAQ,GAAwB,EAAhBxR,KAAKI,SACrBqR,EAAQ,GAAwB,EAAhBzR,KAAKI,SACrBsR,EAAQ,KAAwB,GAAhB1R,KAAKI,SACrBuR,EAAgC,EAAhB3R,KAAKI,SAAb,EACRwR,EAAQ,GAAwB,EAAhB5R,KAAKI,SACrByR,EAAQ,GAAwB,EAAhB7R,KAAKI,SACrB0R,EAAQ,KAAwB,GAAhB9R,KAAKI,SACrB2R,EAAgC,EAAhB/R,KAAKI,SAAb,EACHF,EAAI,EAAG2G,EAAKnE,EAAQiB,UAAY,EAAGzD,EAAI2G,EAAI3G,IAChD,IAAK,GAAIe,GAAI,EAAG6F,EAAKpE,EAAQmB,UAAY,EAAG5C,EAAI6F,EAAI7F,IAAK,CAErD,IAAK,GADDqK,GAAM,EACDjC,EAAI,EAAGA,EAAI,GAAIA,IAAK,CACzB,GAAIzK,GAAIoB,KAAK6H,IAAI,EAAE2J,GAAMnI,GAAKrJ,KAAK2O,IAAI3O,KAAK6H,IAAI,EAAE4J,EAAKpI,IAAMnJ,EAAI,IAAKF,KAAK8N,IAAI7M,GAAK0Q,EAAI1Q,GAAKyQ,GACzF7S,EAAImB,KAAK6H,IAAI,EAAE+J,GAAMvI,GAAKrJ,KAAK2O,IAAI3O,KAAK6H,IAAI,EAAEgK,EAAKxI,IAAMpI,EAAI,IAAKjB,KAAK8N,IAAI5N,GAAK6R,EAAI7R,GAAK4R,EAC7FxG,IAAOtL,KAAKgS,IAAIV,EAAK1S,EAAEA,EAAI2S,EAAK1S,EAAEA,GAEtCkJ,EAAE9G,EAAI4F,EAAK3G,GAAGpB,GAAKwM,EAAMvB,EAGjCvH,MAAMC,QAAQyD,MAAM6B,EAAGrF,IAwC3BF,MAAMC,QAAQwP,wBAA0B,SAASC,GAE7C,QAASC,GAAc3G,GACnB,MAAOA,MAAS,EAAFA,GAAOA,EAAE,KAAOA,EAAE,GAQpC,IAAK,GALD4G,GAAW5P,MAAM6P,cAAcC,OAAO9P,MAAM+P,UAAUC,QAAQJ,WAC9DK,EAAU,GACVC,EAAS,GACTC,EAAWT,EAAS,GAAGU,QAAQC,OAC/BC,EAAWZ,EAAS,GAAGU,QAAQG,OAC1B7S,EAAI,EAAG+E,EAAIiN,EAAS/M,OAAQjF,EAAI+E,EAAG/E,IAYxC,GAVAgS,EAAShS,GAAG0S,QAAQI,MAAQd,EAAShS,GAAG+S,MAAQzQ,MAAM0Q,eACtDhB,EAAShS,GAAG0S,QAAQO,aAAc,EAClCf,EAAS,WAAalS,IAClBwE,KAAM,IACN0O,MAAOlB,EAAShS,GAAG0S,SAKvBH,GAAW,6BAA+BvS,EAAI,MACpC,IAANA,EAAS,CACT,GAAIC,GAAI+R,EAAShS,GAAGsM,OAChB7M,EAAIuS,EAAShS,GAAGmT,KAChBC,MAAyB,KAANnT,EACnBoT,EAAWrB,EAAShS,GAAG0S,QAAQC,OAC/BW,EAAWtB,EAAShS,GAAG0S,QAAQG,MACnC,IAAIO,EAAW,CAGPnT,EAAE,GAAKA,EAAE,GAAK,IAAGA,EAAE,IAAM,GACzBA,EAAE,GAAKA,EAAE,GAAK,IAAGA,EAAE,IAAM,EAC7B,KAAK,GAAIc,GAAI,EAAGA,EAAId,EAAEgF,OAAQlE,IAC1Bd,EAAEc,GAAKkR,EAAchS,EAAEc,IAO/B,GAAIwS,GAAeH,EACf,oBAAsBnT,EAAE,GAAK,KAAOA,EAAE,GAAK,+BAAiCA,EAAE,GAAK,KAAOA,EAAE,GAAK,iBADtER,CAE/B+S,IAAU,2CACkBxS,EAAI,mBAAqBiS,EAAcoB,EAAS3U,GAAK,KAAOuT,EAAcoB,EAAS1U,GAAK,cAAgBsT,EAAcqB,EAAS5U,GAAK,KAAOuT,EAAcqB,EAAS3U,GAAK,wBAElL4U,EAAc,mBAKvC,GAAIC,IAEAC,KAAK,EACLC,QAAQ,EAeRxB,SAAUA,EACVyB,aAAcrR,MAAM+P,UAAUC,QAAQqB,aAAaC,QAC/C,gBACA,8IAGJC,gBACI,wBACA,yBACA,yBACA,4BACA,sBACA,+BACA,SAEAvR,MAAMwR,YAAYC,OAClBzR,MAAMwR,YAAYE,QAClB1R,MAAMwR,YAAYG,wBAClB3R,MAAMwR,YAAYI,oBAClB5R,MAAMwR,YAAYK,iBAClB7R,MAAMwR,YAAYM,kBAClB9R,MAAMwR,YAAYO,kBAClB/R,MAAMwR,YAAYQ,uBAClBhS,MAAMwR,YAAYS,oBAClBjS,MAAMwR,YAAYU,uBAClBlS,MAAMwR,YAAYW,0BAClBnS,MAAMwR,YAAYY,qBAClBpS,MAAMwR,YAAYa,MAClBrS,MAAMwR,YAAYc,kBAClBtS,MAAMwR,YAAYe,iBAClBvS,MAAMwR,YAAYgB,kBAClBxS,MAAMwR,YAAYiB,wBAClBzS,MAAMwR,YAAYkB,yBAClB1S,MAAMwR,YAAYmB,0BAClB3S,MAAMwR,YAAYoB,0BAClB5S,MAAMwR,YAAYqB,8BAElB5C,EACA,sBACA,0BACA,yBAEA,gBAEAjQ,MAAMwR,YAAYsB,yBAE7B,wGACA,yCAGW,+EAEA,oDACA,wDAA0DnD,EAAcQ,EAAS/T,GAAK,KAAOuT,EAAcQ,EAAS9T,GAAK,cAAgBsT,EAAcW,EAASlU,GAAK,KAAOuT,EAAcW,EAASjU,GAAK,gBACpM6T,EACJ,4BAGIlQ,MAAMwR,YAAYuB,qBAClB/S,MAAMwR,YAAYwB,aAClBhT,MAAMwR,YAAYyB,eAClBjT,MAAMwR,YAAY0B,kBAClBlT,MAAMwR,YAAY2B,mBAClBnT,MAAMwR,YAAY4B,qBAClBpT,MAAMwR,YAAY6B,qBAGtB,sFAEIrT,MAAMwR,YAAY8B,kBAEtB,kFACA,0BACA,4FACA,YACA,0DACA,aACA,kGAGItT,MAAMwR,YAAY+B,eACtB,iHACIvT,MAAMwR,YAAYgC,YAClBxT,MAAMwR,YAAYiC,gBACtB,2DACIzT,MAAMwR,YAAYkC,qBAClB1T,MAAMwR,YAAYmC,mBAClB3T,MAAMwR,YAAYoC,aAClB5T,MAAMwR,YAAYqC,6BAClB7T,MAAMwR,YAAYsC,mBACtB,KACFC,KAAK,MAEX,OAAO,IAAI/T,OAAMgU,eAAe9C,IAoDpClR,MAAMC,QAAQgU,cAAgB,SAAShS,EAAU/B,GAC7C,IAAKA,EAAQ8B,KAET,MADAiB,SAAQiR,MAAM,mFACd,EAEJ,IAAIjS,YAAoBjC,OAAMoD,eAE1B,MADAH,SAAQC,KAAK,6GACb,EAEChD,GAAQ0B,QACT1B,EAAQ0B,MAAQ,GAAI5B,OAAM6B,SAE9B,IAAI1B,IACA4F,OAAQ,KACRoO,aAAc,EACdC,aAAc,GACdC,WAAY7W,KAAKI,OACjB0W,SAAU,kBACVC,QAAS7N,EAAAA,EACTyC,EAAG,EACHqL,EAAG,EAEP,KAAK,GAAIhT,KAAOrB,GACRA,EAAesB,eAAeD,KAC9BtB,EAAQsB,OAA+B,KAAjBtB,EAAQsB,GAAuBrB,EAAeqB,GAAOtB,EAAQsB,GAI3F,IAAIiT,GAA2C,gBAAnBvU,GAAQ6F,OAChC2O,EACAL,EACAM,EAAc,EAAIzU,EAAQiU,aAC1BS,EAA4C,EAAvB1U,EAAQkU,aAC7BzW,EAAIsE,EAASS,SACbmS,KACAC,EAAK5U,EAAQ8B,KAAK8S,GAAGC,QAAQC,eAAe,GAAIhV,OAAMiV,QAAQ,EAAG,EAAG,GAAI,GAAIzX,KAAKuE,GACjF0S,KACAC,EAAkBxU,EAAQmU,aAC1BA,EAAwC,gBAApBK,GAA+BlX,KAAKI,OAAS,SAASiJ,GAAK,MAAO6N,GAAgB7N,IAG1G,KAAK,GAAInJ,GAAI,EAAGyL,EAAc,EAAVjJ,EAAQiJ,EAAKzL,EAAIyL,EAAGzL,IACpC,IAAK,GAAIe,GAAI,EAAG+V,EAAItU,EAAQsU,EAAG/V,EAAI+V,EAAG/V,IAAK,CACvC,GAAIyK,GAAMzK,EAAE0K,EAAIzL,EACZwX,EAAIjT,EAASkT,MAAMjM,GACnBkM,GAAQ,CACZ,IAAIX,EAAgB,CAChB,GAAIY,GAAKhB,EAAWnL,EAChBmM,GAAKnV,EAAQ6F,OACbqP,GAAQ,EAEHC,EAAKnV,EAAQ6F,OAAS7F,EAAQiU,eAInCiB,EAAQpV,MAAMC,QAAQiF,WAAWmQ,EAAKnV,EAAQ6F,QAAU4O,GAAezU,EAAQ6F,OAASvI,KAAKI,cAIjGwX,GAAQlV,EAAQ6F,OAAOpI,EAAEuX,EAAEvY,GAAIuM,EAAKgM,EAAGxX,EAAGe,EAE9C,IAAI2W,EAAO,CAEP,GAAIF,EAAEI,OAAOC,QAAQT,GAAM5U,EAAQoU,SAC/B,QAEJ,IAAItS,GAAO9B,EAAQ8B,KAAK+S,OAIxB,IAFA/S,EAAKwT,SAASC,KAAK9X,EAAEuX,EAAEvY,IAAI2G,IAAI3F,EAAEuX,EAAEtY,IAAI0G,IAAI3F,EAAEuX,EAAEnM,IAAI2M,aAAa,GAE5DxV,EAAQqU,QAAU,EAAG,CACrB,GAAIe,GAAStT,EAAKwT,SAAST,QAAQzR,IAAI4R,EAAEI,OACzCtT,GAAK2T,OAAOL,EACZ,IAAIM,GAAYV,EAAEI,OAAOC,QAAQT,EACjC,IAAIc,EAAY1V,EAAQqU,QAAS,CAC7B,GAAIsB,GAAQ3V,EAAQqU,QAAUqB,CAC9B5T,GAAKF,SAAS1F,GAAKyZ,EACnB7T,EAAKF,SAASzF,GAAKwZ,EACnB7T,EAAKF,SAASxF,GAAKuZ,GAK3B,GAFA7T,EAAKF,SAAS1F,GAAK,GAAWoB,KAAKuE,GACnCC,EAAK8T,QAAwB,EAAhBtY,KAAKI,SAAeJ,KAAKuE,IAClC7B,EAAQkU,aAAc,CACtB,GAAI2B,GAAWvY,KAAKI,SAAWgX,EAAqB1U,EAAQkU,YAC5DpS,GAAKM,MAAMlG,EAAI4F,EAAKM,MAAMhG,EAAI,EAAIyZ,EAClC/T,EAAKM,MAAMjG,GAAK0Z,EAEpBlB,EAAOrL,KAAKxH,IAMxB,GAAI6E,GAAGpE,CACP,IAAIvC,EAAQ8B,KAAKC,mBAAoBjC,OAAMgW,SAAU,CACjD,GAAIzQ,GAAI,GAAIvF,OAAMgW,QAClB,KAAKnP,EAAI,EAAGpE,EAAIoS,EAAOlS,OAAQkE,EAAIpE,EAAGoE,IAAK,CACvC,GAAIoC,GAAI4L,EAAOhO,EACfoC,GAAEgN,eACF1Q,EAAEuK,MAAM7G,EAAEhH,SAAUgH,EAAEiN,QAO1BhW,EAAQ0B,MAAM0B,IAAI,GAAItD,OAAM4C,KAAK2C,EAAGrF,EAAQ8B,KAAKvB,eAIjD,KAAKoG,EAAI,EAAGpE,EAAIoS,EAAOlS,OAAQkE,EAAIpE,EAAGoE,IAClC3G,EAAQ0B,MAAM0B,IAAIuR,EAAOhO,GAIjC,OAAO3G,GAAQ0B,OA+BnB5B,MAAMC,QAAQkW,cAAgB,SAASrR,EAAQ5E,EAASkW,EAAMC,GAC1DD,EAAOA,GAAQ,EACfC,EAAYA,GAAa,IACzBnW,EAAQY,UAAYZ,EAAQY,WAAa,GAEzC,IAAI8J,KACJ,KAAK,GAAIpJ,KAAOtB,GACRA,EAAQuB,eAAeD,KACvBoJ,EAAcpJ,GAAOtB,EAAQsB,GAIrCoJ,GAAczJ,WAAa,EAC3ByJ,EAAc5J,SAAU,EACxB4J,EAAclK,UAAY,EAC1BkK,EAAcjK,UAAY,CAG1B,KAAK,GAFDJ,GAAYP,MAAMC,QAAQ4E,eAAeC,EAAQ8F,GAE5ClN,EAAI,EAAG+E,EAAIlC,EAAUoC,OAAQjF,EAAI+E,EAAG/E,KACrCA,EAAI0Y,GAAQ5Y,KAAKI,SAAWyY,KAC5B9V,EAAU7C,GAAK,EAGvB,OAAO,YACH,MAAO6C,KAYfP,MAAMC,QAAQ2M,YACV0J,KAAM,SAASla,GACX,MAAO,MAAOoB,KAAKoH,IAAI,GAAKpH,KAAKgS,KAAMpT,EAAEA,KAE7Cma,KAAM,SAASna,GACX,OAAQ4D,MAAMC,QAAQ2M,WAAW0J,KAAKla,IAE1CgQ,KAAM,SAAShQ,GAEX,MAAOA,GAAI,GAAKA,EAAE,IAAIA,EAAE,IAAI,EAAE,GAAGA,EAAE,IAAM,EAAEA,EAAEA,GAAG,EAAE,EAAEA,IAExDoa,OAAQ,SAASpa,GACb,OAAQ4D,MAAMC,QAAQ2M,WAAWR,KAAKhQ,IAE1Cqa,KAAM,SAASra,GAEX,QAASA,EAAE,IAAIA,EAAE,IAGrBsa,KAAM,SAASta,GACX,MAAO,IAEXua,QAAS,SAASva,GACd,MAAO,IAAO,KAAQoB,KAAKiN,IAAI,EAAIrO,GAAKoB,KAAK8N,IAAI,EAAI9N,KAAKuE,GAAKvE,KAAKiN,IAAIrO,GAAK,OAuDrF4D,MAAMC,QAAQgN,UAAY,SAAS1H,EAAGrF,EAASgV,EAAG9Y,EAAGC,EAAGua,EAAGpC,EAAG/X,EAAGqP,GAC7DoJ,EAAIA,GAAKlV,MAAMC,QAAQ2M,WAAWR,KAClChQ,MAAiB,KAANA,EAAoB,GAAMA,EACrCC,MAAiB,KAANA,EAAoB,GAAMA,EACrCua,MAAiB,KAANA,EAAoB,GAAMA,EACrCpC,MAAiB,KAANA,EAAoB,GAAMA,EACrC/X,MAAiB,KAANA,EAAoBuD,MAAM6W,eAAiBpa,EACtDqP,EAAIA,GAAK9L,MAAMC,QAAQ+E,MAgBvB,KAAK,GAdDX,GAAKnE,EAAQiB,UAAY,EACzBmD,EAAKpE,EAAQmB,UAAY,EACzByV,EAAKzS,EAAKjI,EACV2a,EAAKzS,EAAKjI,EACV2a,EAAK9W,EAAQkB,MAAQlB,EAAQiB,UAC7B8V,EAAK/W,EAAQoB,MAAQpB,EAAQmB,UAC7B6V,EAAKN,EAAII,EACTG,EAAKP,EAAIK,EACTzI,EAAK,EAAIoI,EACTQ,EAAK5Z,KAAK6Z,KAAKP,EAAKI,GACpBI,EAAK9Z,KAAKC,MAAMqZ,EAAKI,GACrBK,EAAK/Z,KAAK6Z,KAAKN,EAAKI,GACpBK,EAAKha,KAAKC,MAAMsZ,EAAKI,GAEhBzZ,EAAI0Z,EAAI1Z,EAAI4Z,EAAI5Z,IACrB,IAAK,GAAIe,GAAI8Y,EAAI9Y,EAAI+Y,EAAI/Y,IAAK,CAC1B,GAAIoI,GAAIpI,EAAI4F,EAAK3G,EAEb+Z,GAAO/Z,EAAIoZ,GAAME,EACjBU,GAAOjZ,EAAIsY,GAAME,EACjBU,EAAKna,KAAKM,KAAK2Z,EAAIA,EAAMC,EAAIA,GAC7BE,EAAMD,EAAKnJ,EACXqJ,EAAOJ,EAAMjJ,EACbsJ,EAAOJ,EAAMlJ,EAGb1H,EAAIoO,EAAE0C,EAAKC,EAAMC,GAAQtD,GAAK,EAAI1I,EAAE8L,EAAKC,EAAMC,GAC/CH,GAAKf,OAAoB,KAARrR,EAAEsB,KACdpK,IAAMuD,MAAMkN,iBAAqB3H,EAAEsB,GAAGvK,GAAKwK,EAC3CrK,IAAMuD,MAAM+X,oBAAqBxS,EAAEsB,GAAGvK,GAAKwK,EAC3CrK,IAAMuD,MAAMgY,iBAAqBzS,EAAEsB,GAAGvK,GAAKwK,EAC3CrK,IAAMuD,MAAMiY,WAAqB1S,EAAEsB,GAAGvK,EAAKwK,EAC3CrK,IAAMuD,MAAM6W,eAAqBtR,EAAEsB,GAAGvK,EAAKwP,EAAE8L,EAAKC,EAAMC,GAAQvS,EAAEsB,GAAGvK,EAAIwK,EAC5D,kBAANrK,KAA0B8I,EAAEsB,GAAGvK,EAAKG,EAAE8I,EAAEsB,GAAGvK,EAAGwK,EAAG8Q,EAAKC,EAAMC","file":"THREE.Terrain.min.js"} \ No newline at end of file diff --git a/demo/index.js b/demo/index.js index 0320e87..0ef2d63 100644 --- a/demo/index.js +++ b/demo/index.js @@ -145,11 +145,8 @@ function setupDatGui() { sand.rotation.x = -0.5 * Math.PI; scene.add(sand); loader.load('demo/img/grass1.jpg', function(t2) { - t2.wrapS = t2.wrapT = THREE.RepeatWrapping; loader.load('demo/img/stone1.jpg', function(t3) { - t3.wrapS = t3.wrapT = THREE.RepeatWrapping; loader.load('demo/img/snow1.jpg', function(t4) { - t4.wrapS = t4.wrapT = THREE.RepeatWrapping; // t2.repeat.x = t2.repeat.y = 2; blend = THREE.Terrain.generateBlendedMaterial([ {texture: t1}, diff --git a/demo/libs/three.js b/demo/libs/three.js index 1ce6ff7..23755c9 100644 --- a/demo/libs/three.js +++ b/demo/libs/three.js @@ -1,7 +1,7 @@ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.THREE = global.THREE || {}))); + (factory((global.THREE = {}))); }(this, (function (exports) { 'use strict'; // Polyfills @@ -39,7 +39,7 @@ } - if ( Function.prototype.name === undefined ) { + if ( 'name' in Function.prototype === false ) { // Missing in IE // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name @@ -65,8 +65,6 @@ Object.assign = function ( target ) { - 'use strict'; - if ( target === undefined || target === null ) { throw new TypeError( 'Cannot convert undefined or null to object' ); @@ -187,7 +185,7 @@ } ); - var REVISION = '86'; + var REVISION = '91'; var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 }; var CullFaceNone = 0; var CullFaceBack = 1; @@ -281,15 +279,29 @@ var RGBEFormat = RGBAFormat; var DepthFormat = 1026; var DepthStencilFormat = 1027; - var RGB_S3TC_DXT1_Format = 2001; - var RGBA_S3TC_DXT1_Format = 2002; - var RGBA_S3TC_DXT3_Format = 2003; - var RGBA_S3TC_DXT5_Format = 2004; - var RGB_PVRTC_4BPPV1_Format = 2100; - var RGB_PVRTC_2BPPV1_Format = 2101; - var RGBA_PVRTC_4BPPV1_Format = 2102; - var RGBA_PVRTC_2BPPV1_Format = 2103; - var RGB_ETC1_Format = 2151; + var RGB_S3TC_DXT1_Format = 33776; + var RGBA_S3TC_DXT1_Format = 33777; + var RGBA_S3TC_DXT3_Format = 33778; + var RGBA_S3TC_DXT5_Format = 33779; + var RGB_PVRTC_4BPPV1_Format = 35840; + var RGB_PVRTC_2BPPV1_Format = 35841; + var RGBA_PVRTC_4BPPV1_Format = 35842; + var RGBA_PVRTC_2BPPV1_Format = 35843; + var RGB_ETC1_Format = 36196; + var RGBA_ASTC_4x4_Format = 37808; + var RGBA_ASTC_5x4_Format = 37809; + var RGBA_ASTC_5x5_Format = 37810; + var RGBA_ASTC_6x5_Format = 37811; + var RGBA_ASTC_6x6_Format = 37812; + var RGBA_ASTC_8x5_Format = 37813; + var RGBA_ASTC_8x6_Format = 37814; + var RGBA_ASTC_8x8_Format = 37815; + var RGBA_ASTC_10x5_Format = 37816; + var RGBA_ASTC_10x6_Format = 37817; + var RGBA_ASTC_10x8_Format = 37818; + var RGBA_ASTC_10x10_Format = 37819; + var RGBA_ASTC_12x10_Format = 37820; + var RGBA_ASTC_12x12_Format = 37821; var LoopOnce = 2200; var LoopRepeat = 2201; var LoopPingPong = 2202; @@ -323,42 +335,32 @@ DEG2RAD: Math.PI / 180, RAD2DEG: 180 / Math.PI, - generateUUID: function () { - - // http://www.broofa.com/Tools/Math.uuid.htm - - var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' ); - var uuid = new Array( 36 ); - var rnd = 0, r; - - return function generateUUID() { - - for ( var i = 0; i < 36; i ++ ) { - - if ( i === 8 || i === 13 || i === 18 || i === 23 ) { - - uuid[ i ] = '-'; + generateUUID: ( function () { - } else if ( i === 14 ) { + // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 - uuid[ i ] = '4'; + var lut = []; - } else { + for ( var i = 0; i < 256; i ++ ) { - if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0; - r = rnd & 0xf; - rnd = rnd >> 4; - uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ]; + lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 ).toUpperCase(); - } + } - } + return function generateUUID() { - return uuid.join( '' ); + var d0 = Math.random() * 0xffffffff | 0; + var d1 = Math.random() * 0xffffffff | 0; + var d2 = Math.random() * 0xffffffff | 0; + var d3 = Math.random() * 0xffffffff | 0; + return lut[ d0 & 0xff ] + lut[ d0 >> 8 & 0xff ] + lut[ d0 >> 16 & 0xff ] + lut[ d0 >> 24 & 0xff ] + '-' + + lut[ d1 & 0xff ] + lut[ d1 >> 8 & 0xff ] + '-' + lut[ d1 >> 16 & 0x0f | 0x40 ] + lut[ d1 >> 24 & 0xff ] + '-' + + lut[ d2 & 0x3f | 0x80 ] + lut[ d2 >> 8 & 0xff ] + '-' + lut[ d2 >> 16 & 0xff ] + lut[ d2 >> 24 & 0xff ] + + lut[ d3 & 0xff ] + lut[ d3 >> 8 & 0xff ] + lut[ d3 >> 16 & 0xff ] + lut[ d3 >> 24 & 0xff ]; }; - }(), + } )(), clamp: function ( value, min, max ) { @@ -457,23 +459,15 @@ }, - nearestPowerOfTwo: function ( value ) { + ceilPowerOfTwo: function ( value ) { - return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) ); + return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); }, - nextPowerOfTwo: function ( value ) { - - value --; - value |= value >> 1; - value |= value >> 2; - value |= value >> 4; - value |= value >> 8; - value |= value >> 16; - value ++; + floorPowerOfTwo: function ( value ) { - return value; + return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); } @@ -495,7 +489,7 @@ Object.defineProperties( Vector2.prototype, { - "width" : { + "width": { get: function () { @@ -511,7 +505,7 @@ }, - "height" : { + "height": { get: function () { @@ -718,6 +712,18 @@ }, + applyMatrix3: function ( m ) { + + var x = this.x, y = this.y; + var e = m.elements; + + this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ]; + this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ]; + + return this; + + }, + min: function ( v ) { this.x = Math.min( this.x, v.x ); @@ -834,7 +840,7 @@ }, - lengthManhattan: function() { + manhattanLength: function () { return Math.abs( this.x ) + Math.abs( this.y ); @@ -871,7 +877,7 @@ }, - distanceToManhattan: function ( v ) { + manhattanDistanceTo: function ( v ) { return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); @@ -960,1021 +966,926 @@ /** * @author mrdoob / http://mrdoob.com/ + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author philogb / http://blog.thejit.org/ + * @author jordi_ros / http://plattsoft.com + * @author D1plo1d / http://github.com/D1plo1d * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ + * @author mikael emtinger / http://gomo.se/ + * @author timknip / http://www.floorplanner.com/ + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley */ - var textureId = 0; + function Matrix4() { - function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + this.elements = [ - Object.defineProperty( this, 'id', { value: textureId ++ } ); + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - this.uuid = _Math.generateUUID(); + ]; - this.name = ''; + if ( arguments.length > 0 ) { - this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE; - this.mipmaps = []; + console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); - this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING; + } - this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping; - this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping; + } - this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; - this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter; + Object.assign( Matrix4.prototype, { - this.anisotropy = anisotropy !== undefined ? anisotropy : 1; + isMatrix4: true, - this.format = format !== undefined ? format : RGBAFormat; - this.type = type !== undefined ? type : UnsignedByteType; + set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { - this.offset = new Vector2( 0, 0 ); - this.repeat = new Vector2( 1, 1 ); + var te = this.elements; - this.generateMipmaps = true; - this.premultiplyAlpha = false; - this.flipY = true; - this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) + te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; + te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; + te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; + te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; - // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap. - // - // Also changing the encoding after already used by a Material will not automatically make the Material - // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. - this.encoding = encoding !== undefined ? encoding : LinearEncoding; + return this; - this.version = 0; - this.onUpdate = null; + }, - } + identity: function () { - Texture.DEFAULT_IMAGE = undefined; - Texture.DEFAULT_MAPPING = UVMapping; + this.set( - Object.defineProperty( Texture.prototype, "needsUpdate", { + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - set: function ( value ) { + ); - if ( value === true ) this.version ++; + return this; - } + }, - } ); + clone: function () { - Object.assign( Texture.prototype, EventDispatcher.prototype, { + return new Matrix4().fromArray( this.elements ); - constructor: Texture, + }, - isTexture: true, + copy: function ( m ) { - clone: function () { + var te = this.elements; + var me = m.elements; - return new this.constructor().copy( this ); + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; + te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; + te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; + te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; + + return this; }, - copy: function ( source ) { + copyPosition: function ( m ) { - this.name = source.name; + var te = this.elements, me = m.elements; - this.image = source.image; - this.mipmaps = source.mipmaps.slice( 0 ); + te[ 12 ] = me[ 12 ]; + te[ 13 ] = me[ 13 ]; + te[ 14 ] = me[ 14 ]; - this.mapping = source.mapping; + return this; - this.wrapS = source.wrapS; - this.wrapT = source.wrapT; + }, - this.magFilter = source.magFilter; - this.minFilter = source.minFilter; + extractBasis: function ( xAxis, yAxis, zAxis ) { - this.anisotropy = source.anisotropy; + xAxis.setFromMatrixColumn( this, 0 ); + yAxis.setFromMatrixColumn( this, 1 ); + zAxis.setFromMatrixColumn( this, 2 ); - this.format = source.format; - this.type = source.type; + return this; - this.offset.copy( source.offset ); - this.repeat.copy( source.repeat ); + }, - this.generateMipmaps = source.generateMipmaps; - this.premultiplyAlpha = source.premultiplyAlpha; - this.flipY = source.flipY; - this.unpackAlignment = source.unpackAlignment; - this.encoding = source.encoding; + makeBasis: function ( xAxis, yAxis, zAxis ) { + + this.set( + xAxis.x, yAxis.x, zAxis.x, 0, + xAxis.y, yAxis.y, zAxis.y, 0, + xAxis.z, yAxis.z, zAxis.z, 0, + 0, 0, 0, 1 + ); return this; }, - toJSON: function ( meta ) { + extractRotation: function () { - if ( meta.textures[ this.uuid ] !== undefined ) { + var v1 = new Vector3(); - return meta.textures[ this.uuid ]; + return function extractRotation( m ) { - } + var te = this.elements; + var me = m.elements; - function getDataURL( image ) { + var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length(); + var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length(); + var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length(); - var canvas; + te[ 0 ] = me[ 0 ] * scaleX; + te[ 1 ] = me[ 1 ] * scaleX; + te[ 2 ] = me[ 2 ] * scaleX; - if ( image.toDataURL !== undefined ) { + te[ 4 ] = me[ 4 ] * scaleY; + te[ 5 ] = me[ 5 ] * scaleY; + te[ 6 ] = me[ 6 ] * scaleY; - canvas = image; + te[ 8 ] = me[ 8 ] * scaleZ; + te[ 9 ] = me[ 9 ] * scaleZ; + te[ 10 ] = me[ 10 ] * scaleZ; - } else { + return this; - canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = image.width; - canvas.height = image.height; + }; - canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height ); + }(), - } + makeRotationFromEuler: function ( euler ) { - if ( canvas.width > 2048 || canvas.height > 2048 ) { + if ( ! ( euler && euler.isEuler ) ) { - return canvas.toDataURL( 'image/jpeg', 0.6 ); + console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); - } else { + } - return canvas.toDataURL( 'image/png' ); + var te = this.elements; - } + var x = euler.x, y = euler.y, z = euler.z; + var a = Math.cos( x ), b = Math.sin( x ); + var c = Math.cos( y ), d = Math.sin( y ); + var e = Math.cos( z ), f = Math.sin( z ); - } + if ( euler.order === 'XYZ' ) { - var output = { - metadata: { - version: 4.5, - type: 'Texture', - generator: 'Texture.toJSON' - }, + var ae = a * e, af = a * f, be = b * e, bf = b * f; - uuid: this.uuid, - name: this.name, + te[ 0 ] = c * e; + te[ 4 ] = - c * f; + te[ 8 ] = d; - mapping: this.mapping, + te[ 1 ] = af + be * d; + te[ 5 ] = ae - bf * d; + te[ 9 ] = - b * c; - repeat: [ this.repeat.x, this.repeat.y ], - offset: [ this.offset.x, this.offset.y ], - wrap: [ this.wrapS, this.wrapT ], + te[ 2 ] = bf - ae * d; + te[ 6 ] = be + af * d; + te[ 10 ] = a * c; - minFilter: this.minFilter, - magFilter: this.magFilter, - anisotropy: this.anisotropy, + } else if ( euler.order === 'YXZ' ) { - flipY: this.flipY - }; + var ce = c * e, cf = c * f, de = d * e, df = d * f; - if ( this.image !== undefined ) { + te[ 0 ] = ce + df * b; + te[ 4 ] = de * b - cf; + te[ 8 ] = a * d; - // TODO: Move to THREE.Image + te[ 1 ] = a * f; + te[ 5 ] = a * e; + te[ 9 ] = - b; - var image = this.image; + te[ 2 ] = cf * b - de; + te[ 6 ] = df + ce * b; + te[ 10 ] = a * c; - if ( image.uuid === undefined ) { + } else if ( euler.order === 'ZXY' ) { - image.uuid = _Math.generateUUID(); // UGH + var ce = c * e, cf = c * f, de = d * e, df = d * f; - } + te[ 0 ] = ce - df * b; + te[ 4 ] = - a * f; + te[ 8 ] = de + cf * b; - if ( meta.images[ image.uuid ] === undefined ) { + te[ 1 ] = cf + de * b; + te[ 5 ] = a * e; + te[ 9 ] = df - ce * b; - meta.images[ image.uuid ] = { - uuid: image.uuid, - url: getDataURL( image ) - }; + te[ 2 ] = - a * d; + te[ 6 ] = b; + te[ 10 ] = a * c; - } + } else if ( euler.order === 'ZYX' ) { - output.image = image.uuid; + var ae = a * e, af = a * f, be = b * e, bf = b * f; - } + te[ 0 ] = c * e; + te[ 4 ] = be * d - af; + te[ 8 ] = ae * d + bf; - meta.textures[ this.uuid ] = output; + te[ 1 ] = c * f; + te[ 5 ] = bf * d + ae; + te[ 9 ] = af * d - be; - return output; + te[ 2 ] = - d; + te[ 6 ] = b * c; + te[ 10 ] = a * c; - }, + } else if ( euler.order === 'YZX' ) { - dispose: function () { + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - this.dispatchEvent( { type: 'dispose' } ); + te[ 0 ] = c * e; + te[ 4 ] = bd - ac * f; + te[ 8 ] = bc * f + ad; - }, + te[ 1 ] = f; + te[ 5 ] = a * e; + te[ 9 ] = - b * e; - transformUv: function ( uv ) { + te[ 2 ] = - d * e; + te[ 6 ] = ad * f + bc; + te[ 10 ] = ac - bd * f; - if ( this.mapping !== UVMapping ) return; + } else if ( euler.order === 'XZY' ) { - uv.multiply( this.repeat ); - uv.add( this.offset ); + var ac = a * c, ad = a * d, bc = b * c, bd = b * d; - if ( uv.x < 0 || uv.x > 1 ) { + te[ 0 ] = c * e; + te[ 4 ] = - f; + te[ 8 ] = d * e; - switch ( this.wrapS ) { + te[ 1 ] = ac * f + bd; + te[ 5 ] = a * e; + te[ 9 ] = ad * f - bc; - case RepeatWrapping: + te[ 2 ] = bc * f - ad; + te[ 6 ] = b * e; + te[ 10 ] = bd * f + ac; - uv.x = uv.x - Math.floor( uv.x ); - break; + } - case ClampToEdgeWrapping: + // last column + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - uv.x = uv.x < 0 ? 0 : 1; - break; + // bottom row + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - case MirroredRepeatWrapping: + return this; - if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { + }, - uv.x = Math.ceil( uv.x ) - uv.x; + makeRotationFromQuaternion: function ( q ) { - } else { + var te = this.elements; - uv.x = uv.x - Math.floor( uv.x ); + var x = q._x, y = q._y, z = q._z, w = q._w; + var x2 = x + x, y2 = y + y, z2 = z + z; + var xx = x * x2, xy = x * y2, xz = x * z2; + var yy = y * y2, yz = y * z2, zz = z * z2; + var wx = w * x2, wy = w * y2, wz = w * z2; - } - break; + te[ 0 ] = 1 - ( yy + zz ); + te[ 4 ] = xy - wz; + te[ 8 ] = xz + wy; - } + te[ 1 ] = xy + wz; + te[ 5 ] = 1 - ( xx + zz ); + te[ 9 ] = yz - wx; - } + te[ 2 ] = xz - wy; + te[ 6 ] = yz + wx; + te[ 10 ] = 1 - ( xx + yy ); - if ( uv.y < 0 || uv.y > 1 ) { + // last column + te[ 3 ] = 0; + te[ 7 ] = 0; + te[ 11 ] = 0; - switch ( this.wrapT ) { + // bottom row + te[ 12 ] = 0; + te[ 13 ] = 0; + te[ 14 ] = 0; + te[ 15 ] = 1; - case RepeatWrapping: + return this; - uv.y = uv.y - Math.floor( uv.y ); - break; + }, - case ClampToEdgeWrapping: + lookAt: function () { - uv.y = uv.y < 0 ? 0 : 1; - break; + var x = new Vector3(); + var y = new Vector3(); + var z = new Vector3(); - case MirroredRepeatWrapping: + return function lookAt( eye, target, up ) { - if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { + var te = this.elements; - uv.y = Math.ceil( uv.y ) - uv.y; + z.subVectors( eye, target ); - } else { + if ( z.lengthSq() === 0 ) { - uv.y = uv.y - Math.floor( uv.y ); + // eye and target are in the same position - } - break; + z.z = 1; } - } + z.normalize(); + x.crossVectors( up, z ); - if ( this.flipY ) { + if ( x.lengthSq() === 0 ) { - uv.y = 1 - uv.y; + // up and z are parallel - } + if ( Math.abs( up.z ) === 1 ) { - } + z.x += 0.0001; - } ); + } else { - /** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author philogb / http://blog.thejit.org/ - * @author mikael emtinger / http://gomo.se/ - * @author egraether / http://egraether.com/ - * @author WestLangley / http://github.com/WestLangley - */ + z.z += 0.0001; - function Vector4( x, y, z, w ) { + } - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - this.w = ( w !== undefined ) ? w : 1; + z.normalize(); + x.crossVectors( up, z ); - } + } - Object.assign( Vector4.prototype, { + x.normalize(); + y.crossVectors( z, x ); - isVector4: true, + te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x; + te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y; + te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z; - set: function ( x, y, z, w ) { + return this; - this.x = x; - this.y = y; - this.z = z; - this.w = w; + }; - return this; + }(), - }, + multiply: function ( m, n ) { - setScalar: function ( scalar ) { + if ( n !== undefined ) { - this.x = scalar; - this.y = scalar; - this.z = scalar; - this.w = scalar; + console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); + return this.multiplyMatrices( m, n ); - return this; + } - }, + return this.multiplyMatrices( this, m ); - setX: function ( x ) { + }, - this.x = x; + premultiply: function ( m ) { - return this; + return this.multiplyMatrices( m, this ); }, - setY: function ( y ) { - - this.y = y; - - return this; + multiplyMatrices: function ( a, b ) { - }, + var ae = a.elements; + var be = b.elements; + var te = this.elements; - setZ: function ( z ) { + var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; + var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; + var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; + var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; - this.z = z; + var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; + var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; + var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; + var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; - return this; + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; - }, + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; - setW: function ( w ) { + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; - this.w = w; + te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; return this; }, - setComponent: function ( index, value ) { - - switch ( index ) { + multiplyScalar: function ( s ) { - case 0: this.x = value; break; - case 1: this.y = value; break; - case 2: this.z = value; break; - case 3: this.w = value; break; - default: throw new Error( 'index is out of range: ' + index ); + var te = this.elements; - } + te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; + te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; + te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; + te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; return this; }, - getComponent: function ( index ) { + applyToBufferAttribute: function () { - switch ( index ) { - - case 0: return this.x; - case 1: return this.y; - case 2: return this.z; - case 3: return this.w; - default: throw new Error( 'index is out of range: ' + index ); + var v1 = new Vector3(); - } + return function applyToBufferAttribute( attribute ) { - }, + for ( var i = 0, l = attribute.count; i < l; i ++ ) { - clone: function () { + v1.x = attribute.getX( i ); + v1.y = attribute.getY( i ); + v1.z = attribute.getZ( i ); - return new this.constructor( this.x, this.y, this.z, this.w ); + v1.applyMatrix4( this ); - }, + attribute.setXYZ( i, v1.x, v1.y, v1.z ); - copy: function ( v ) { + } - this.x = v.x; - this.y = v.y; - this.z = v.z; - this.w = ( v.w !== undefined ) ? v.w : 1; + return attribute; - return this; + }; - }, + }(), - add: function ( v, w ) { + determinant: function () { - if ( w !== undefined ) { + var te = this.elements; - console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); - return this.addVectors( v, w ); + var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; + var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; + var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; + var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; - } + //TODO: make this more efficient + //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) - this.x += v.x; - this.y += v.y; - this.z += v.z; - this.w += v.w; + return ( + n41 * ( + + n14 * n23 * n32 + - n13 * n24 * n32 + - n14 * n22 * n33 + + n12 * n24 * n33 + + n13 * n22 * n34 + - n12 * n23 * n34 + ) + + n42 * ( + + n11 * n23 * n34 + - n11 * n24 * n33 + + n14 * n21 * n33 + - n13 * n21 * n34 + + n13 * n24 * n31 + - n14 * n23 * n31 + ) + + n43 * ( + + n11 * n24 * n32 + - n11 * n22 * n34 + - n14 * n21 * n32 + + n12 * n21 * n34 + + n14 * n22 * n31 + - n12 * n24 * n31 + ) + + n44 * ( + - n13 * n22 * n31 + - n11 * n23 * n32 + + n11 * n22 * n33 + + n13 * n21 * n32 + - n12 * n21 * n33 + + n12 * n23 * n31 + ) - return this; + ); }, - addScalar: function ( s ) { + transpose: function () { - this.x += s; - this.y += s; - this.z += s; - this.w += s; + var te = this.elements; + var tmp; + + tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; + tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; + tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; + + tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; + tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; + tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; return this; }, - addVectors: function ( a, b ) { + setPosition: function ( v ) { - this.x = a.x + b.x; - this.y = a.y + b.y; - this.z = a.z + b.z; - this.w = a.w + b.w; + var te = this.elements; + + te[ 12 ] = v.x; + te[ 13 ] = v.y; + te[ 14 ] = v.z; return this; }, - addScaledVector: function ( v, s ) { + getInverse: function ( m, throwOnDegenerate ) { - this.x += v.x * s; - this.y += v.y * s; - this.z += v.z * s; - this.w += v.w * s; + // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + var te = this.elements, + me = m.elements, - return this; + n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ], + n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ], + n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ], + n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ], - }, + t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, + t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, + t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, + t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; - sub: function ( v, w ) { + var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; - if ( w !== undefined ) { + if ( det === 0 ) { - console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); - return this.subVectors( v, w ); + var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0"; + + if ( throwOnDegenerate === true ) { + + throw new Error( msg ); + + } else { + + console.warn( msg ); + + } + + return this.identity(); } - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - this.w -= v.w; + var detInv = 1 / det; - return this; + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; + te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; + te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; - }, + te[ 4 ] = t12 * detInv; + te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; + te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; + te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; - subScalar: function ( s ) { + te[ 8 ] = t13 * detInv; + te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; + te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; + te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; - this.x -= s; - this.y -= s; - this.z -= s; - this.w -= s; + te[ 12 ] = t14 * detInv; + te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; + te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; + te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; return this; }, - subVectors: function ( a, b ) { + scale: function ( v ) { - this.x = a.x - b.x; - this.y = a.y - b.y; - this.z = a.z - b.z; - this.w = a.w - b.w; + var te = this.elements; + var x = v.x, y = v.y, z = v.z; + + te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; + te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; + te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; + te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; return this; }, - multiplyScalar: function ( scalar ) { + getMaxScaleOnAxis: function () { - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; + var te = this.elements; - return this; + var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; + var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; + var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + + return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); }, - applyMatrix4: function ( m ) { + makeTranslation: function ( x, y, z ) { - var x = this.x, y = this.y, z = this.z, w = this.w; - var e = m.elements; + this.set( - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; - this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; - this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1 + + ); return this; }, - divideScalar: function ( scalar ) { - - return this.multiplyScalar( 1 / scalar ); + makeRotationX: function ( theta ) { - }, + var c = Math.cos( theta ), s = Math.sin( theta ); - setAxisAngleFromQuaternion: function ( q ) { + this.set( - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + 1, 0, 0, 0, + 0, c, - s, 0, + 0, s, c, 0, + 0, 0, 0, 1 - // q is assumed to be normalized + ); - this.w = 2 * Math.acos( q.w ); + return this; - var s = Math.sqrt( 1 - q.w * q.w ); + }, - if ( s < 0.0001 ) { + makeRotationY: function ( theta ) { - this.x = 1; - this.y = 0; - this.z = 0; + var c = Math.cos( theta ), s = Math.sin( theta ); - } else { + this.set( - this.x = q.x / s; - this.y = q.y / s; - this.z = q.z / s; + c, 0, s, 0, + 0, 1, 0, 0, + - s, 0, c, 0, + 0, 0, 0, 1 - } + ); return this; }, - setAxisAngleFromRotationMatrix: function ( m ) { + makeRotationZ: function ( theta ) { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm + var c = Math.cos( theta ), s = Math.sin( theta ); - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + this.set( - var angle, x, y, z, // variables for result - epsilon = 0.01, // margin to allow for rounding errors - epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees + c, - s, 0, 0, + s, c, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 - te = m.elements, + ); - m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], - m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], - m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + return this; - if ( ( Math.abs( m12 - m21 ) < epsilon ) && - ( Math.abs( m13 - m31 ) < epsilon ) && - ( Math.abs( m23 - m32 ) < epsilon ) ) { + }, - // singularity found - // first check for identity matrix which must have +1 for all terms - // in leading diagonal and zero in other terms + makeRotationAxis: function ( axis, angle ) { - if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && - ( Math.abs( m13 + m31 ) < epsilon2 ) && - ( Math.abs( m23 + m32 ) < epsilon2 ) && - ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { + // Based on http://www.gamedev.net/reference/articles/article1199.asp - // this singularity is identity matrix so angle = 0 + var c = Math.cos( angle ); + var s = Math.sin( angle ); + var t = 1 - c; + var x = axis.x, y = axis.y, z = axis.z; + var tx = t * x, ty = t * y; - this.set( 1, 0, 0, 0 ); + this.set( - return this; // zero angle, arbitrary axis + tx * x + c, tx * y - s * z, tx * z + s * y, 0, + tx * y + s * z, ty * y + c, ty * z - s * x, 0, + tx * z - s * y, ty * z + s * x, t * z * z + c, 0, + 0, 0, 0, 1 - } + ); - // otherwise this singularity is angle = 180 + return this; - angle = Math.PI; + }, - var xx = ( m11 + 1 ) / 2; - var yy = ( m22 + 1 ) / 2; - var zz = ( m33 + 1 ) / 2; - var xy = ( m12 + m21 ) / 4; - var xz = ( m13 + m31 ) / 4; - var yz = ( m23 + m32 ) / 4; + makeScale: function ( x, y, z ) { - if ( ( xx > yy ) && ( xx > zz ) ) { + this.set( - // m11 is the largest diagonal term + x, 0, 0, 0, + 0, y, 0, 0, + 0, 0, z, 0, + 0, 0, 0, 1 - if ( xx < epsilon ) { + ); - x = 0; - y = 0.707106781; - z = 0.707106781; + return this; - } else { + }, - x = Math.sqrt( xx ); - y = xy / x; - z = xz / x; + makeShear: function ( x, y, z ) { - } + this.set( - } else if ( yy > zz ) { + 1, y, z, 0, + x, 1, z, 0, + x, y, 1, 0, + 0, 0, 0, 1 - // m22 is the largest diagonal term + ); - if ( yy < epsilon ) { + return this; - x = 0.707106781; - y = 0; - z = 0.707106781; + }, - } else { + compose: function ( position, quaternion, scale ) { - y = Math.sqrt( yy ); - x = xy / y; - z = yz / y; + this.makeRotationFromQuaternion( quaternion ); + this.scale( scale ); + this.setPosition( position ); - } + return this; - } else { + }, - // m33 is the largest diagonal term so base result on this + decompose: function () { - if ( zz < epsilon ) { + var vector = new Vector3(); + var matrix = new Matrix4(); - x = 0.707106781; - y = 0.707106781; - z = 0; + return function decompose( position, quaternion, scale ) { - } else { + var te = this.elements; - z = Math.sqrt( zz ); - x = xz / z; - y = yz / z; + var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); + var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); + var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); - } + // if determine is negative, we need to invert one scale + var det = this.determinant(); + if ( det < 0 ) sx = - sx; - } + position.x = te[ 12 ]; + position.y = te[ 13 ]; + position.z = te[ 14 ]; - this.set( x, y, z, angle ); + // scale the rotation part + matrix.copy( this ); - return this; // return 180 deg rotation + var invSX = 1 / sx; + var invSY = 1 / sy; + var invSZ = 1 / sz; - } + matrix.elements[ 0 ] *= invSX; + matrix.elements[ 1 ] *= invSX; + matrix.elements[ 2 ] *= invSX; - // as we have reached here there are no singularities so we can handle normally + matrix.elements[ 4 ] *= invSY; + matrix.elements[ 5 ] *= invSY; + matrix.elements[ 6 ] *= invSY; - var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + - ( m13 - m31 ) * ( m13 - m31 ) + - ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize + matrix.elements[ 8 ] *= invSZ; + matrix.elements[ 9 ] *= invSZ; + matrix.elements[ 10 ] *= invSZ; - if ( Math.abs( s ) < 0.001 ) s = 1; + quaternion.setFromRotationMatrix( matrix ); - // prevent divide by zero, should not happen if matrix is orthogonal and should be - // caught by singularity test above, but I've left it in just in case + scale.x = sx; + scale.y = sy; + scale.z = sz; - this.x = ( m32 - m23 ) / s; - this.y = ( m13 - m31 ) / s; - this.z = ( m21 - m12 ) / s; - this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); + return this; - return this; + }; - }, + }(), - min: function ( v ) { + makePerspective: function ( left, right, top, bottom, near, far ) { - this.x = Math.min( this.x, v.x ); - this.y = Math.min( this.y, v.y ); - this.z = Math.min( this.z, v.z ); - this.w = Math.min( this.w, v.w ); + if ( far === undefined ) { - return this; + console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' ); - }, + } - max: function ( v ) { + var te = this.elements; + var x = 2 * near / ( right - left ); + var y = 2 * near / ( top - bottom ); - this.x = Math.max( this.x, v.x ); - this.y = Math.max( this.y, v.y ); - this.z = Math.max( this.z, v.z ); - this.w = Math.max( this.w, v.w ); + var a = ( right + left ) / ( right - left ); + var b = ( top + bottom ) / ( top - bottom ); + var c = - ( far + near ) / ( far - near ); + var d = - 2 * far * near / ( far - near ); + + te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; + te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; return this; }, - clamp: function ( min, max ) { + makeOrthographic: function ( left, right, top, bottom, near, far ) { - // assumes min < max, componentwise + var te = this.elements; + var w = 1.0 / ( right - left ); + var h = 1.0 / ( top - bottom ); + var p = 1.0 / ( far - near ); - this.x = Math.max( min.x, Math.min( max.x, this.x ) ); - this.y = Math.max( min.y, Math.min( max.y, this.y ) ); - this.z = Math.max( min.z, Math.min( max.z, this.z ) ); - this.w = Math.max( min.w, Math.min( max.w, this.w ) ); + var x = ( right + left ) * w; + var y = ( top + bottom ) * h; + var z = ( far + near ) * p; + + te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; + te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y; + te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z; + te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; return this; }, - clampScalar: function () { - - var min, max; - - return function clampScalar( minVal, maxVal ) { - - if ( min === undefined ) { - - min = new Vector4(); - max = new Vector4(); + equals: function ( matrix ) { - } + var te = this.elements; + var me = matrix.elements; - min.set( minVal, minVal, minVal, minVal ); - max.set( maxVal, maxVal, maxVal, maxVal ); + for ( var i = 0; i < 16; i ++ ) { - return this.clamp( min, max ); + if ( te[ i ] !== me[ i ] ) return false; - }; + } - }(), + return true; - clampLength: function ( min, max ) { + }, - var length = this.length(); + fromArray: function ( array, offset ) { - return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); + if ( offset === undefined ) offset = 0; - }, + for ( var i = 0; i < 16; i ++ ) { - floor: function () { + this.elements[ i ] = array[ i + offset ]; - this.x = Math.floor( this.x ); - this.y = Math.floor( this.y ); - this.z = Math.floor( this.z ); - this.w = Math.floor( this.w ); + } return this; }, - ceil: function () { - - this.x = Math.ceil( this.x ); - this.y = Math.ceil( this.y ); - this.z = Math.ceil( this.z ); - this.w = Math.ceil( this.w ); + toArray: function ( array, offset ) { - return this; + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - }, + var te = this.elements; - round: function () { + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; + array[ offset + 3 ] = te[ 3 ]; - this.x = Math.round( this.x ); - this.y = Math.round( this.y ); - this.z = Math.round( this.z ); - this.w = Math.round( this.w ); - - return this; - - }, - - roundToZero: function () { - - this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); - this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); - this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); - this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); - - return this; - - }, - - negate: function () { - - this.x = - this.x; - this.y = - this.y; - this.z = - this.z; - this.w = - this.w; - - return this; - - }, - - dot: function ( v ) { - - return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - - }, - - lengthSq: function () { - - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; - - }, - - length: function () { - - return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); - - }, - - lengthManhattan: function () { - - return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); - - }, - - normalize: function () { - - return this.divideScalar( this.length() || 1 ); - - }, - - setLength: function ( length ) { - - return this.normalize().multiplyScalar( length ); - - }, - - lerp: function ( v, alpha ) { - - this.x += ( v.x - this.x ) * alpha; - this.y += ( v.y - this.y ) * alpha; - this.z += ( v.z - this.z ) * alpha; - this.w += ( v.w - this.w ) * alpha; - - return this; - - }, - - lerpVectors: function ( v1, v2, alpha ) { - - return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - - }, - - equals: function ( v ) { - - return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); - - }, - - fromArray: function ( array, offset ) { - - if ( offset === undefined ) offset = 0; - - this.x = array[ offset ]; - this.y = array[ offset + 1 ]; - this.z = array[ offset + 2 ]; - this.w = array[ offset + 3 ]; - - return this; - - }, - - toArray: function ( array, offset ) { + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + array[ offset + 8 ] = te[ 8 ]; + array[ offset + 9 ] = te[ 9 ]; + array[ offset + 10 ] = te[ 10 ]; + array[ offset + 11 ] = te[ 11 ]; - array[ offset ] = this.x; - array[ offset + 1 ] = this.y; - array[ offset + 2 ] = this.z; - array[ offset + 3 ] = this.w; + array[ offset + 12 ] = te[ 12 ]; + array[ offset + 13 ] = te[ 13 ]; + array[ offset + 14 ] = te[ 14 ]; + array[ offset + 15 ] = te[ 15 ]; return array; - }, - - fromBufferAttribute: function ( attribute, index, offset ) { - - if ( offset !== undefined ) { - - console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' ); - - } - - this.x = attribute.getX( index ); - this.y = attribute.getY( index ); - this.z = attribute.getZ( index ); - this.w = attribute.getW( index ); - - return this; - - } - - } ); - - /** - * @author szimek / https://github.com/szimek/ - * @author alteredq / http://alteredqualia.com/ - * @author Marius Kintel / https://github.com/kintel - */ - - /* - In options, we can specify: - * Texture parameters for an auto-generated target texture - * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers - */ - function WebGLRenderTarget( width, height, options ) { - - this.uuid = _Math.generateUUID(); - - this.width = width; - this.height = height; - - this.scissor = new Vector4( 0, 0, width, height ); - this.scissorTest = false; - - this.viewport = new Vector4( 0, 0, width, height ); - - options = options || {}; - - if ( options.minFilter === undefined ) options.minFilter = LinearFilter; - - this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); - - this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; - this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; - this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; - - } - - Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, { - - isWebGLRenderTarget: true, - - setSize: function ( width, height ) { - - if ( this.width !== width || this.height !== height ) { - - this.width = width; - this.height = height; - - this.dispose(); - - } - - this.viewport.set( 0, 0, width, height ); - this.scissor.set( 0, 0, width, height ); - - }, - - clone: function () { - - return new this.constructor().copy( this ); - - }, - - copy: function ( source ) { - - this.width = source.width; - this.height = source.height; - - this.viewport.copy( source.viewport ); - - this.texture = source.texture.clone(); - - this.depthBuffer = source.depthBuffer; - this.stencilBuffer = source.stencilBuffer; - this.depthTexture = source.depthTexture; - - return this; - - }, - - dispose: function () { - - this.dispatchEvent( { type: 'dispose' } ); - } } ); - /** - * @author alteredq / http://alteredqualia.com - */ - - function WebGLRenderTargetCube( width, height, options ) { - - WebGLRenderTarget.call( this, width, height, options ); - - this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 - this.activeMipMapLevel = 0; - - } - - WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype ); - WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube; - - WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true; - /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ @@ -2370,7 +2281,9 @@ inverse: function () { - return this.conjugate().normalize(); + // quaternion is assumed to have unit length + + return this.conjugate(); }, @@ -2861,8 +2774,8 @@ var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); - this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w; - this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w; + this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w; + this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w; this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w; return this; @@ -2876,9 +2789,9 @@ // calculate quat * vector - var ix = qw * x + qy * z - qz * y; - var iy = qw * y + qz * x - qx * z; - var iz = qw * z + qx * y - qy * x; + var ix = qw * x + qy * z - qz * y; + var iy = qw * y + qz * x - qx * z; + var iz = qw * z + qx * y - qy * x; var iw = - qx * x - qy * y - qz * z; // calculate result * inverse quat @@ -2925,8 +2838,8 @@ var x = this.x, y = this.y, z = this.z; var e = m.elements; - this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; - this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; return this.normalize(); @@ -3075,7 +2988,7 @@ }, - lengthManhattan: function () { + manhattanLength: function () { return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); @@ -3118,13 +3031,7 @@ } - var x = this.x, y = this.y, z = this.z; - - this.x = y * v.z - z * v.y; - this.y = z * v.x - x * v.z; - this.z = x * v.y - y * v.x; - - return this; + return this.crossVectors( this, v ); }, @@ -3202,7 +3109,7 @@ }, - distanceToManhattan: function ( v ) { + manhattanDistanceTo: function ( v ) { return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); @@ -3312,49 +3219,41 @@ } ); /** - * @author mrdoob / http://mrdoob.com/ - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author philogb / http://blog.thejit.org/ - * @author jordi_ros / http://plattsoft.com - * @author D1plo1d / http://github.com/D1plo1d * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author timknip / http://www.floorplanner.com/ - * @author bhouston / http://clara.io * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + * @author tschw */ - function Matrix4() { + function Matrix3() { this.elements = [ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 ]; if ( arguments.length > 0 ) { - console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); + console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); } } - Object.assign( Matrix4.prototype, { + Object.assign( Matrix3.prototype, { - isMatrix4: true, + isMatrix3: true, - set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { + set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { var te = this.elements; - te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; - te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; - te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; - te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; + te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; + te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; + te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; return this; @@ -3364,10 +3263,9 @@ this.set( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 ); @@ -3377,7 +3275,7 @@ clone: function () { - return new Matrix4().fromArray( this.elements ); + return new this.constructor().fromArray( this.elements ); }, @@ -3386,813 +3284,725 @@ var te = this.elements; var me = m.elements; - te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; - te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; - te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; - te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; - - return this; - - }, - - copyPosition: function ( m ) { - - var te = this.elements, me = m.elements; - - te[ 12 ] = me[ 12 ]; - te[ 13 ] = me[ 13 ]; - te[ 14 ] = me[ 14 ]; + te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; + te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; + te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; return this; }, - extractBasis: function ( xAxis, yAxis, zAxis ) { - - xAxis.setFromMatrixColumn( this, 0 ); - yAxis.setFromMatrixColumn( this, 1 ); - zAxis.setFromMatrixColumn( this, 2 ); + setFromMatrix4: function ( m ) { - return this; + var me = m.elements; - }, + this.set( - makeBasis: function ( xAxis, yAxis, zAxis ) { + me[ 0 ], me[ 4 ], me[ 8 ], + me[ 1 ], me[ 5 ], me[ 9 ], + me[ 2 ], me[ 6 ], me[ 10 ] - this.set( - xAxis.x, yAxis.x, zAxis.x, 0, - xAxis.y, yAxis.y, zAxis.y, 0, - xAxis.z, yAxis.z, zAxis.z, 0, - 0, 0, 0, 1 ); return this; }, - extractRotation: function () { + applyToBufferAttribute: function () { var v1 = new Vector3(); - return function extractRotation( m ) { + return function applyToBufferAttribute( attribute ) { - var te = this.elements; - var me = m.elements; + for ( var i = 0, l = attribute.count; i < l; i ++ ) { - var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length(); - var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length(); - var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length(); + v1.x = attribute.getX( i ); + v1.y = attribute.getY( i ); + v1.z = attribute.getZ( i ); - te[ 0 ] = me[ 0 ] * scaleX; - te[ 1 ] = me[ 1 ] * scaleX; - te[ 2 ] = me[ 2 ] * scaleX; + v1.applyMatrix3( this ); - te[ 4 ] = me[ 4 ] * scaleY; - te[ 5 ] = me[ 5 ] * scaleY; - te[ 6 ] = me[ 6 ] * scaleY; + attribute.setXYZ( i, v1.x, v1.y, v1.z ); - te[ 8 ] = me[ 8 ] * scaleZ; - te[ 9 ] = me[ 9 ] * scaleZ; - te[ 10 ] = me[ 10 ] * scaleZ; + } - return this; + return attribute; }; }(), - makeRotationFromEuler: function ( euler ) { + multiply: function ( m ) { - if ( ! ( euler && euler.isEuler ) ) { + return this.multiplyMatrices( this, m ); - console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); + }, - } + premultiply: function ( m ) { + + return this.multiplyMatrices( m, this ); + + }, + + multiplyMatrices: function ( a, b ) { + var ae = a.elements; + var be = b.elements; var te = this.elements; - var x = euler.x, y = euler.y, z = euler.z; - var a = Math.cos( x ), b = Math.sin( x ); - var c = Math.cos( y ), d = Math.sin( y ); - var e = Math.cos( z ), f = Math.sin( z ); + var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ]; + var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ]; + var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ]; - if ( euler.order === 'XYZ' ) { + var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ]; + var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ]; + var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ]; - var ae = a * e, af = a * f, be = b * e, bf = b * f; + te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31; + te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32; + te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33; - te[ 0 ] = c * e; - te[ 4 ] = - c * f; - te[ 8 ] = d; + te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31; + te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32; + te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33; - te[ 1 ] = af + be * d; - te[ 5 ] = ae - bf * d; - te[ 9 ] = - b * c; + te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31; + te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32; + te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33; - te[ 2 ] = bf - ae * d; - te[ 6 ] = be + af * d; - te[ 10 ] = a * c; + return this; - } else if ( euler.order === 'YXZ' ) { + }, - var ce = c * e, cf = c * f, de = d * e, df = d * f; + multiplyScalar: function ( s ) { - te[ 0 ] = ce + df * b; - te[ 4 ] = de * b - cf; - te[ 8 ] = a * d; + var te = this.elements; - te[ 1 ] = a * f; - te[ 5 ] = a * e; - te[ 9 ] = - b; + te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; + te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; + te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; - te[ 2 ] = cf * b - de; - te[ 6 ] = df + ce * b; - te[ 10 ] = a * c; + return this; - } else if ( euler.order === 'ZXY' ) { + }, - var ce = c * e, cf = c * f, de = d * e, df = d * f; + determinant: function () { - te[ 0 ] = ce - df * b; - te[ 4 ] = - a * f; - te[ 8 ] = de + cf * b; + var te = this.elements; - te[ 1 ] = cf + de * b; - te[ 5 ] = a * e; - te[ 9 ] = df - ce * b; + var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], + d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], + g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; - te[ 2 ] = - a * d; - te[ 6 ] = b; - te[ 10 ] = a * c; + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; - } else if ( euler.order === 'ZYX' ) { + }, - var ae = a * e, af = a * f, be = b * e, bf = b * f; + getInverse: function ( matrix, throwOnDegenerate ) { - te[ 0 ] = c * e; - te[ 4 ] = be * d - af; - te[ 8 ] = ae * d + bf; + if ( matrix && matrix.isMatrix4 ) { - te[ 1 ] = c * f; - te[ 5 ] = bf * d + ae; - te[ 9 ] = af * d - be; + console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." ); - te[ 2 ] = - d; - te[ 6 ] = b * c; - te[ 10 ] = a * c; + } - } else if ( euler.order === 'YZX' ) { + var me = matrix.elements, + te = this.elements, - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], + n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ], + n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ], - te[ 0 ] = c * e; - te[ 4 ] = bd - ac * f; - te[ 8 ] = bc * f + ad; + t11 = n33 * n22 - n32 * n23, + t12 = n32 * n13 - n33 * n12, + t13 = n23 * n12 - n22 * n13, - te[ 1 ] = f; - te[ 5 ] = a * e; - te[ 9 ] = - b * e; + det = n11 * t11 + n21 * t12 + n31 * t13; - te[ 2 ] = - d * e; - te[ 6 ] = ad * f + bc; - te[ 10 ] = ac - bd * f; + if ( det === 0 ) { - } else if ( euler.order === 'XZY' ) { + var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0"; - var ac = a * c, ad = a * d, bc = b * c, bd = b * d; + if ( throwOnDegenerate === true ) { - te[ 0 ] = c * e; - te[ 4 ] = - f; - te[ 8 ] = d * e; + throw new Error( msg ); - te[ 1 ] = ac * f + bd; - te[ 5 ] = a * e; - te[ 9 ] = ad * f - bc; + } else { - te[ 2 ] = bc * f - ad; - te[ 6 ] = b * e; - te[ 10 ] = bd * f + ac; + console.warn( msg ); + + } + + return this.identity(); } - // last column - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; + var detInv = 1 / det; - // bottom row - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + te[ 0 ] = t11 * detInv; + te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; + te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; + + te[ 3 ] = t12 * detInv; + te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; + te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; + + te[ 6 ] = t13 * detInv; + te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; + te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; return this; }, - makeRotationFromQuaternion: function ( q ) { + transpose: function () { - var te = this.elements; + var tmp, m = this.elements; - var x = q._x, y = q._y, z = q._z, w = q._w; - var x2 = x + x, y2 = y + y, z2 = z + z; - var xx = x * x2, xy = x * y2, xz = x * z2; - var yy = y * y2, yz = y * z2, zz = z * z2; - var wx = w * x2, wy = w * y2, wz = w * z2; + tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; + tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; + tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; - te[ 0 ] = 1 - ( yy + zz ); - te[ 4 ] = xy - wz; - te[ 8 ] = xz + wy; + return this; - te[ 1 ] = xy + wz; - te[ 5 ] = 1 - ( xx + zz ); - te[ 9 ] = yz - wx; + }, - te[ 2 ] = xz - wy; - te[ 6 ] = yz + wx; - te[ 10 ] = 1 - ( xx + yy ); + getNormalMatrix: function ( matrix4 ) { - // last column - te[ 3 ] = 0; - te[ 7 ] = 0; - te[ 11 ] = 0; + return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose(); - // bottom row - te[ 12 ] = 0; - te[ 13 ] = 0; - te[ 14 ] = 0; - te[ 15 ] = 1; + }, + + transposeIntoArray: function ( r ) { + + var m = this.elements; + + r[ 0 ] = m[ 0 ]; + r[ 1 ] = m[ 3 ]; + r[ 2 ] = m[ 6 ]; + r[ 3 ] = m[ 1 ]; + r[ 4 ] = m[ 4 ]; + r[ 5 ] = m[ 7 ]; + r[ 6 ] = m[ 2 ]; + r[ 7 ] = m[ 5 ]; + r[ 8 ] = m[ 8 ]; return this; }, - lookAt: function () { - - var x = new Vector3(); - var y = new Vector3(); - var z = new Vector3(); + setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) { - return function lookAt( eye, target, up ) { + var c = Math.cos( rotation ); + var s = Math.sin( rotation ); - var te = this.elements; + this.set( + sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx, + - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty, + 0, 0, 1 + ); - z.subVectors( eye, target ); + }, - if ( z.lengthSq() === 0 ) { + scale: function ( sx, sy ) { - // eye and target are in the same position + var te = this.elements; - z.z = 1; + te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx; + te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy; - } + return this; - z.normalize(); - x.crossVectors( up, z ); + }, - if ( x.lengthSq() === 0 ) { + rotate: function ( theta ) { - // up and z are parallel + var c = Math.cos( theta ); + var s = Math.sin( theta ); - if ( Math.abs( up.z ) === 1 ) { + var te = this.elements; - z.x += 0.0001; + var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ]; + var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ]; - } else { + te[ 0 ] = c * a11 + s * a21; + te[ 3 ] = c * a12 + s * a22; + te[ 6 ] = c * a13 + s * a23; - z.z += 0.0001; + te[ 1 ] = - s * a11 + c * a21; + te[ 4 ] = - s * a12 + c * a22; + te[ 7 ] = - s * a13 + c * a23; - } + return this; - z.normalize(); - x.crossVectors( up, z ); + }, - } + translate: function ( tx, ty ) { - x.normalize(); - y.crossVectors( z, x ); + var te = this.elements; - te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x; - te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y; - te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z; + te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ]; + te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ]; - return this; + return this; - }; + }, - }(), + equals: function ( matrix ) { - multiply: function ( m, n ) { + var te = this.elements; + var me = matrix.elements; - if ( n !== undefined ) { + for ( var i = 0; i < 9; i ++ ) { - console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); - return this.multiplyMatrices( m, n ); + if ( te[ i ] !== me[ i ] ) return false; } - return this.multiplyMatrices( this, m ); + return true; }, - premultiply: function ( m ) { + fromArray: function ( array, offset ) { - return this.multiplyMatrices( m, this ); + if ( offset === undefined ) offset = 0; + + for ( var i = 0; i < 9; i ++ ) { + + this.elements[ i ] = array[ i + offset ]; + + } + + return this; }, - multiplyMatrices: function ( a, b ) { + toArray: function ( array, offset ) { + + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - var ae = a.elements; - var be = b.elements; var te = this.elements; - var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; - var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; - var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; - var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; + array[ offset ] = te[ 0 ]; + array[ offset + 1 ] = te[ 1 ]; + array[ offset + 2 ] = te[ 2 ]; - var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; - var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; - var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; - var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; + array[ offset + 3 ] = te[ 3 ]; + array[ offset + 4 ] = te[ 4 ]; + array[ offset + 5 ] = te[ 5 ]; - te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; - te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; - te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; - te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + array[ offset + 6 ] = te[ 6 ]; + array[ offset + 7 ] = te[ 7 ]; + array[ offset + 8 ] = te[ 8 ]; - te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; - te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; - te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; - te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + return array; - te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; - te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; - te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; - te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + } - te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; - te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; - te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; - te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + } ); - return this; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + */ - }, + var textureId = 0; - multiplyScalar: function ( s ) { + function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { - var te = this.elements; + Object.defineProperty( this, 'id', { value: textureId ++ } ); - te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; - te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; - te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; - te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; + this.uuid = _Math.generateUUID(); - return this; + this.name = ''; - }, + this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE; + this.mipmaps = []; - applyToBufferAttribute: function () { + this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING; - var v1 = new Vector3(); + this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping; + this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping; - return function applyToBufferAttribute( attribute ) { + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter; - for ( var i = 0, l = attribute.count; i < l; i ++ ) { + this.anisotropy = anisotropy !== undefined ? anisotropy : 1; - v1.x = attribute.getX( i ); - v1.y = attribute.getY( i ); - v1.z = attribute.getZ( i ); + this.format = format !== undefined ? format : RGBAFormat; + this.type = type !== undefined ? type : UnsignedByteType; - v1.applyMatrix4( this ); + this.offset = new Vector2( 0, 0 ); + this.repeat = new Vector2( 1, 1 ); + this.center = new Vector2( 0, 0 ); + this.rotation = 0; - attribute.setXYZ( i, v1.x, v1.y, v1.z ); + this.matrixAutoUpdate = true; + this.matrix = new Matrix3(); - } + this.generateMipmaps = true; + this.premultiplyAlpha = false; + this.flipY = true; + this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) - return attribute; + // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap. + // + // Also changing the encoding after already used by a Material will not automatically make the Material + // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. + this.encoding = encoding !== undefined ? encoding : LinearEncoding; - }; + this.version = 0; + this.onUpdate = null; - }(), + } - determinant: function () { + Texture.DEFAULT_IMAGE = undefined; + Texture.DEFAULT_MAPPING = UVMapping; - var te = this.elements; + Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { - var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; - var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; - var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; - var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; + constructor: Texture, - //TODO: make this more efficient - //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) + isTexture: true, - return ( - n41 * ( - + n14 * n23 * n32 - - n13 * n24 * n32 - - n14 * n22 * n33 - + n12 * n24 * n33 - + n13 * n22 * n34 - - n12 * n23 * n34 - ) + - n42 * ( - + n11 * n23 * n34 - - n11 * n24 * n33 - + n14 * n21 * n33 - - n13 * n21 * n34 - + n13 * n24 * n31 - - n14 * n23 * n31 - ) + - n43 * ( - + n11 * n24 * n32 - - n11 * n22 * n34 - - n14 * n21 * n32 - + n12 * n21 * n34 - + n14 * n22 * n31 - - n12 * n24 * n31 - ) + - n44 * ( - - n13 * n22 * n31 - - n11 * n23 * n32 - + n11 * n22 * n33 - + n13 * n21 * n32 - - n12 * n21 * n33 - + n12 * n23 * n31 - ) + clone: function () { - ); + return new this.constructor().copy( this ); }, - transpose: function () { + copy: function ( source ) { - var te = this.elements; - var tmp; + this.name = source.name; - tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; - tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; - tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; + this.image = source.image; + this.mipmaps = source.mipmaps.slice( 0 ); - tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; - tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; - tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; + this.mapping = source.mapping; - return this; + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; - }, + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; - setPosition: function ( v ) { + this.anisotropy = source.anisotropy; - var te = this.elements; + this.format = source.format; + this.type = source.type; - te[ 12 ] = v.x; - te[ 13 ] = v.y; - te[ 14 ] = v.z; + this.offset.copy( source.offset ); + this.repeat.copy( source.repeat ); + this.center.copy( source.center ); + this.rotation = source.rotation; + + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy( source.matrix ); + + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.encoding = source.encoding; return this; }, - getInverse: function ( m, throwOnDegenerate ) { + toJSON: function ( meta ) { - // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - var te = this.elements, - me = m.elements, + var isRootObject = ( meta === undefined || typeof meta === 'string' ); - n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ], - n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ], - n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ], - n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ], + if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) { - t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, - t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, - t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, - t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + return meta.textures[ this.uuid ]; - var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + } - if ( det === 0 ) { + function getDataURL( image ) { - var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0"; + var canvas; - if ( throwOnDegenerate === true ) { + if ( image instanceof HTMLCanvasElement ) { - throw new Error( msg ); + canvas = image; } else { - console.warn( msg ); + canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = image.width; + canvas.height = image.height; - } + var context = canvas.getContext( '2d' ); - return this.identity(); + if ( image instanceof ImageData ) { - } + context.putImageData( image, 0, 0 ); - var detInv = 1 / det; + } else { - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; - te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; - te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; + context.drawImage( image, 0, 0, image.width, image.height ); - te[ 4 ] = t12 * detInv; - te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; - te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; - te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; + } - te[ 8 ] = t13 * detInv; - te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; - te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; - te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; + } - te[ 12 ] = t14 * detInv; - te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; - te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; - te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; + if ( canvas.width > 2048 || canvas.height > 2048 ) { - return this; + return canvas.toDataURL( 'image/jpeg', 0.6 ); - }, + } else { - scale: function ( v ) { + return canvas.toDataURL( 'image/png' ); - var te = this.elements; - var x = v.x, y = v.y, z = v.z; + } - te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; - te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; - te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; - te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; + } - return this; + var output = { - }, + metadata: { + version: 4.5, + type: 'Texture', + generator: 'Texture.toJSON' + }, - getMaxScaleOnAxis: function () { + uuid: this.uuid, + name: this.name, - var te = this.elements; + mapping: this.mapping, - var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; - var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; - var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; + repeat: [ this.repeat.x, this.repeat.y ], + offset: [ this.offset.x, this.offset.y ], + center: [ this.center.x, this.center.y ], + rotation: this.rotation, - return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); + wrap: [ this.wrapS, this.wrapT ], - }, + format: this.format, + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, - makeTranslation: function ( x, y, z ) { + flipY: this.flipY - this.set( + }; - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1 + if ( this.image !== undefined ) { - ); + // TODO: Move to THREE.Image - return this; + var image = this.image; - }, + if ( image.uuid === undefined ) { - makeRotationX: function ( theta ) { + image.uuid = _Math.generateUUID(); // UGH - var c = Math.cos( theta ), s = Math.sin( theta ); + } - this.set( + if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) { - 1, 0, 0, 0, - 0, c, - s, 0, - 0, s, c, 0, - 0, 0, 0, 1 + meta.images[ image.uuid ] = { + uuid: image.uuid, + url: getDataURL( image ) + }; - ); + } - return this; + output.image = image.uuid; - }, + } - makeRotationY: function ( theta ) { + if ( ! isRootObject ) { - var c = Math.cos( theta ), s = Math.sin( theta ); + meta.textures[ this.uuid ] = output; - this.set( + } - c, 0, s, 0, - 0, 1, 0, 0, - - s, 0, c, 0, - 0, 0, 0, 1 + return output; - ); + }, - return this; + dispose: function () { + + this.dispatchEvent( { type: 'dispose' } ); }, - makeRotationZ: function ( theta ) { + transformUv: function ( uv ) { - var c = Math.cos( theta ), s = Math.sin( theta ); + if ( this.mapping !== UVMapping ) return; - this.set( + uv.applyMatrix3( this.matrix ); - c, - s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 + if ( uv.x < 0 || uv.x > 1 ) { - ); + switch ( this.wrapS ) { - return this; + case RepeatWrapping: - }, + uv.x = uv.x - Math.floor( uv.x ); + break; - makeRotationAxis: function ( axis, angle ) { + case ClampToEdgeWrapping: - // Based on http://www.gamedev.net/reference/articles/article1199.asp + uv.x = uv.x < 0 ? 0 : 1; + break; - var c = Math.cos( angle ); - var s = Math.sin( angle ); - var t = 1 - c; - var x = axis.x, y = axis.y, z = axis.z; - var tx = t * x, ty = t * y; + case MirroredRepeatWrapping: - this.set( + if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { - tx * x + c, tx * y - s * z, tx * z + s * y, 0, - tx * y + s * z, ty * y + c, ty * z - s * x, 0, - tx * z - s * y, ty * z + s * x, t * z * z + c, 0, - 0, 0, 0, 1 + uv.x = Math.ceil( uv.x ) - uv.x; - ); + } else { - return this; + uv.x = uv.x - Math.floor( uv.x ); - }, + } + break; - makeScale: function ( x, y, z ) { + } - this.set( + } - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1 + if ( uv.y < 0 || uv.y > 1 ) { - ); + switch ( this.wrapT ) { - return this; + case RepeatWrapping: - }, + uv.y = uv.y - Math.floor( uv.y ); + break; - makeShear: function ( x, y, z ) { + case ClampToEdgeWrapping: - this.set( + uv.y = uv.y < 0 ? 0 : 1; + break; - 1, y, z, 0, - x, 1, z, 0, - x, y, 1, 0, - 0, 0, 0, 1 + case MirroredRepeatWrapping: - ); + if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { - return this; + uv.y = Math.ceil( uv.y ) - uv.y; - }, + } else { - compose: function ( position, quaternion, scale ) { + uv.y = uv.y - Math.floor( uv.y ); - this.makeRotationFromQuaternion( quaternion ); - this.scale( scale ); - this.setPosition( position ); - - return this; - - }, + } + break; - decompose: function () { + } - var vector = new Vector3(); - var matrix = new Matrix4(); + } - return function decompose( position, quaternion, scale ) { + if ( this.flipY ) { - var te = this.elements; + uv.y = 1 - uv.y; - var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); - var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); - var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); + } - // if determine is negative, we need to invert one scale - var det = this.determinant(); - if ( det < 0 ) sx = - sx; + } - position.x = te[ 12 ]; - position.y = te[ 13 ]; - position.z = te[ 14 ]; + } ); - // scale the rotation part - matrix.copy( this ); + Object.defineProperty( Texture.prototype, "needsUpdate", { - var invSX = 1 / sx; - var invSY = 1 / sy; - var invSZ = 1 / sz; + set: function ( value ) { - matrix.elements[ 0 ] *= invSX; - matrix.elements[ 1 ] *= invSX; - matrix.elements[ 2 ] *= invSX; + if ( value === true ) this.version ++; - matrix.elements[ 4 ] *= invSY; - matrix.elements[ 5 ] *= invSY; - matrix.elements[ 6 ] *= invSY; + } - matrix.elements[ 8 ] *= invSZ; - matrix.elements[ 9 ] *= invSZ; - matrix.elements[ 10 ] *= invSZ; + } ); - quaternion.setFromRotationMatrix( matrix ); + /** + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author philogb / http://blog.thejit.org/ + * @author mikael emtinger / http://gomo.se/ + * @author egraether / http://egraether.com/ + * @author WestLangley / http://github.com/WestLangley + */ - scale.x = sx; - scale.y = sy; - scale.z = sz; + function Vector4( x, y, z, w ) { - return this; + this.x = x || 0; + this.y = y || 0; + this.z = z || 0; + this.w = ( w !== undefined ) ? w : 1; - }; + } - }(), + Object.assign( Vector4.prototype, { - makePerspective: function ( left, right, top, bottom, near, far ) { + isVector4: true, - if ( far === undefined ) { + set: function ( x, y, z, w ) { - console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' ); + this.x = x; + this.y = y; + this.z = z; + this.w = w; - } + return this; - var te = this.elements; - var x = 2 * near / ( right - left ); - var y = 2 * near / ( top - bottom ); + }, - var a = ( right + left ) / ( right - left ); - var b = ( top + bottom ) / ( top - bottom ); - var c = - ( far + near ) / ( far - near ); - var d = - 2 * far * near / ( far - near ); + setScalar: function ( scalar ) { - te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; - te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; return this; }, - makeOrthographic: function ( left, right, top, bottom, near, far ) { + setX: function ( x ) { - var te = this.elements; - var w = 1.0 / ( right - left ); - var h = 1.0 / ( top - bottom ); - var p = 1.0 / ( far - near ); + this.x = x; - var x = ( right + left ) * w; - var y = ( top + bottom ) * h; - var z = ( far + near ) * p; + return this; - te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; - te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y; - te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z; - te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; + }, + + setY: function ( y ) { + + this.y = y; return this; }, - equals: function ( matrix ) { + setZ: function ( z ) { - var te = this.elements; - var me = matrix.elements; + this.z = z; - for ( var i = 0; i < 16; i ++ ) { + return this; - if ( te[ i ] !== me[ i ] ) return false; + }, - } + setW: function ( w ) { - return true; + this.w = w; - }, + return this; - fromArray: function ( array, offset ) { + }, - if ( offset === undefined ) offset = 0; + setComponent: function ( index, value ) { - for ( var i = 0; i < 16; i ++ ) { + switch ( index ) { - this.elements[ i ] = array[ i + offset ]; + case 0: this.x = value; break; + case 1: this.y = value; break; + case 2: this.z = value; break; + case 3: this.w = value; break; + default: throw new Error( 'index is out of range: ' + index ); } @@ -4200,786 +4010,785 @@ }, - toArray: function ( array, offset ) { + getComponent: function ( index ) { - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + switch ( index ) { - var te = this.elements; + case 0: return this.x; + case 1: return this.y; + case 2: return this.z; + case 3: return this.w; + default: throw new Error( 'index is out of range: ' + index ); - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; - array[ offset + 3 ] = te[ 3 ]; + } - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; + }, - array[ offset + 8 ] = te[ 8 ]; - array[ offset + 9 ] = te[ 9 ]; - array[ offset + 10 ] = te[ 10 ]; - array[ offset + 11 ] = te[ 11 ]; + clone: function () { - array[ offset + 12 ] = te[ 12 ]; - array[ offset + 13 ] = te[ 13 ]; - array[ offset + 14 ] = te[ 14 ]; - array[ offset + 15 ] = te[ 15 ]; + return new this.constructor( this.x, this.y, this.z, this.w ); - return array; + }, - } + copy: function ( v ) { - } ); + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = ( v.w !== undefined ) ? v.w : 1; - /** - * @author alteredq / http://alteredqualia.com/ - */ + return this; - function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { + }, - Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + add: function ( v, w ) { - this.image = { data: data, width: width, height: height }; + if ( w !== undefined ) { - this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); + return this.addVectors( v, w ); - this.generateMipmaps = false; - this.flipY = false; - this.unpackAlignment = 1; + } - } + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; - DataTexture.prototype = Object.create( Texture.prototype ); - DataTexture.prototype.constructor = DataTexture; + return this; - DataTexture.prototype.isDataTexture = true; + }, - /** - * @author mrdoob / http://mrdoob.com/ - */ + addScalar: function ( s ) { - function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { + this.x += s; + this.y += s; + this.z += s; + this.w += s; - images = images !== undefined ? images : []; - mapping = mapping !== undefined ? mapping : CubeReflectionMapping; + return this; - Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); + }, - this.flipY = false; + addVectors: function ( a, b ) { - } + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + this.w = a.w + b.w; - CubeTexture.prototype = Object.create( Texture.prototype ); - CubeTexture.prototype.constructor = CubeTexture; + return this; - CubeTexture.prototype.isCubeTexture = true; + }, - Object.defineProperty( CubeTexture.prototype, 'images', { + addScaledVector: function ( v, s ) { - get: function () { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; - return this.image; + return this; }, - set: function ( value ) { + sub: function ( v, w ) { - this.image = value; + if ( w !== undefined ) { - } + console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); + return this.subVectors( v, w ); - } ); + } - /** - * @author tschw - * - * Uniforms of a program. - * Those form a tree structure with a special top-level container for the root, - * which you get by calling 'new WebGLUniforms( gl, program, renderer )'. - * - * - * Properties of inner nodes including the top-level container: - * - * .seq - array of nested uniforms - * .map - nested uniforms by name - * - * - * Methods of all nodes except the top-level container: - * - * .setValue( gl, value, [renderer] ) - * - * uploads a uniform value(s) - * the 'renderer' parameter is needed for sampler uniforms - * - * - * Static methods of the top-level container (renderer factorizations): - * - * .upload( gl, seq, values, renderer ) - * - * sets uniforms in 'seq' to 'values[id].value' - * - * .seqWithValue( seq, values ) : filteredSeq - * - * filters 'seq' entries with corresponding entry in values - * - * - * Methods of the top-level container (renderer factorizations): - * - * .setValue( gl, name, value ) - * - * sets uniform with name 'name' to 'value' - * - * .set( gl, obj, prop ) - * - * sets uniform from object and property with same name than uniform - * - * .setOptional( gl, obj, prop ) - * - * like .set for an optional property of the object - * - */ + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; - var emptyTexture = new Texture(); - var emptyCubeTexture = new CubeTexture(); + return this; - // --- Base for inner nodes (including the root) --- + }, - function UniformContainer() { + subScalar: function ( s ) { - this.seq = []; - this.map = {}; + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; - } + return this; - // --- Utilities --- + }, - // Array Caches (provide typed arrays for temporary by size) + subVectors: function ( a, b ) { - var arrayCacheF32 = []; - var arrayCacheI32 = []; + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + this.w = a.w - b.w; - // Float32Array caches used for uploading Matrix uniforms + return this; - var mat4array = new Float32Array( 16 ); - var mat3array = new Float32Array( 9 ); + }, - // Flattening for arrays of vectors and matrices + multiplyScalar: function ( scalar ) { - function flatten( array, nBlocks, blockSize ) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; - var firstElem = array[ 0 ]; + return this; - if ( firstElem <= 0 || firstElem > 0 ) return array; - // unoptimized: ! isNaN( firstElem ) - // see http://jacksondunstan.com/articles/983 + }, - var n = nBlocks * blockSize, - r = arrayCacheF32[ n ]; + applyMatrix4: function ( m ) { - if ( r === undefined ) { + var x = this.x, y = this.y, z = this.z, w = this.w; + var e = m.elements; - r = new Float32Array( n ); - arrayCacheF32[ n ] = r; + this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; + this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; + this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; + this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; - } + return this; - if ( nBlocks !== 0 ) { + }, - firstElem.toArray( r, 0 ); + divideScalar: function ( scalar ) { - for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) { + return this.multiplyScalar( 1 / scalar ); - offset += blockSize; - array[ i ].toArray( r, offset ); + }, - } + setAxisAngleFromQuaternion: function ( q ) { - } + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - return r; + // q is assumed to be normalized - } + this.w = 2 * Math.acos( q.w ); - // Texture unit allocation + var s = Math.sqrt( 1 - q.w * q.w ); - function allocTexUnits( renderer, n ) { + if ( s < 0.0001 ) { - var r = arrayCacheI32[ n ]; + this.x = 1; + this.y = 0; + this.z = 0; - if ( r === undefined ) { + } else { - r = new Int32Array( n ); - arrayCacheI32[ n ] = r; + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; - } + } - for ( var i = 0; i !== n; ++ i ) - r[ i ] = renderer.allocTextureUnit(); + return this; - return r; + }, - } + setAxisAngleFromRotationMatrix: function ( m ) { - // --- Setters --- + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - // Note: Defining these methods externally, because they come in a bunch - // and this way their names minify. + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - // Single scalar + var angle, x, y, z, // variables for result + epsilon = 0.01, // margin to allow for rounding errors + epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees - function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); } - function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); } + te = m.elements, - // Single float vector (from flat array or THREE.VectorN) + m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], + m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], + m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - function setValue2fv( gl, v ) { + if ( ( Math.abs( m12 - m21 ) < epsilon ) && + ( Math.abs( m13 - m31 ) < epsilon ) && + ( Math.abs( m23 - m32 ) < epsilon ) ) { - if ( v.x === undefined ) gl.uniform2fv( this.addr, v ); - else gl.uniform2f( this.addr, v.x, v.y ); + // singularity found + // first check for identity matrix which must have +1 for all terms + // in leading diagonal and zero in other terms - } + if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && + ( Math.abs( m13 + m31 ) < epsilon2 ) && + ( Math.abs( m23 + m32 ) < epsilon2 ) && + ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { - function setValue3fv( gl, v ) { + // this singularity is identity matrix so angle = 0 - if ( v.x !== undefined ) - gl.uniform3f( this.addr, v.x, v.y, v.z ); - else if ( v.r !== undefined ) - gl.uniform3f( this.addr, v.r, v.g, v.b ); - else - gl.uniform3fv( this.addr, v ); + this.set( 1, 0, 0, 0 ); - } + return this; // zero angle, arbitrary axis - function setValue4fv( gl, v ) { + } - if ( v.x === undefined ) gl.uniform4fv( this.addr, v ); - else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); + // otherwise this singularity is angle = 180 - } + angle = Math.PI; - // Single matrix (from flat array or MatrixN) + var xx = ( m11 + 1 ) / 2; + var yy = ( m22 + 1 ) / 2; + var zz = ( m33 + 1 ) / 2; + var xy = ( m12 + m21 ) / 4; + var xz = ( m13 + m31 ) / 4; + var yz = ( m23 + m32 ) / 4; - function setValue2fm( gl, v ) { + if ( ( xx > yy ) && ( xx > zz ) ) { - gl.uniformMatrix2fv( this.addr, false, v.elements || v ); + // m11 is the largest diagonal term - } + if ( xx < epsilon ) { - function setValue3fm( gl, v ) { + x = 0; + y = 0.707106781; + z = 0.707106781; - if ( v.elements === undefined ) { + } else { - gl.uniformMatrix3fv( this.addr, false, v ); + x = Math.sqrt( xx ); + y = xy / x; + z = xz / x; - } else { + } - mat3array.set( v.elements ); - gl.uniformMatrix3fv( this.addr, false, mat3array ); + } else if ( yy > zz ) { - } + // m22 is the largest diagonal term - } + if ( yy < epsilon ) { - function setValue4fm( gl, v ) { + x = 0.707106781; + y = 0; + z = 0.707106781; - if ( v.elements === undefined ) { + } else { - gl.uniformMatrix4fv( this.addr, false, v ); + y = Math.sqrt( yy ); + x = xy / y; + z = yz / y; - } else { + } - mat4array.set( v.elements ); - gl.uniformMatrix4fv( this.addr, false, mat4array ); + } else { - } + // m33 is the largest diagonal term so base result on this - } + if ( zz < epsilon ) { - // Single texture (2D / Cube) + x = 0.707106781; + y = 0.707106781; + z = 0; - function setValueT1( gl, v, renderer ) { + } else { - var unit = renderer.allocTextureUnit(); - gl.uniform1i( this.addr, unit ); - renderer.setTexture2D( v || emptyTexture, unit ); + z = Math.sqrt( zz ); + x = xz / z; + y = yz / z; - } + } - function setValueT6( gl, v, renderer ) { + } - var unit = renderer.allocTextureUnit(); - gl.uniform1i( this.addr, unit ); - renderer.setTextureCube( v || emptyCubeTexture, unit ); + this.set( x, y, z, angle ); - } - - // Integer / Boolean vectors or arrays thereof (always flat arrays) - - function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); } - function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); } - function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); } - - // Helper to pick the right setter for the singular case - - function getSingularSetter( type ) { + return this; // return 180 deg rotation - switch ( type ) { + } - case 0x1406: return setValue1f; // FLOAT - case 0x8b50: return setValue2fv; // _VEC2 - case 0x8b51: return setValue3fv; // _VEC3 - case 0x8b52: return setValue4fv; // _VEC4 + // as we have reached here there are no singularities so we can handle normally - case 0x8b5a: return setValue2fm; // _MAT2 - case 0x8b5b: return setValue3fm; // _MAT3 - case 0x8b5c: return setValue4fm; // _MAT4 + var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + + ( m13 - m31 ) * ( m13 - m31 ) + + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize - case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES - case 0x8b60: return setValueT6; // SAMPLER_CUBE + if ( Math.abs( s ) < 0.001 ) s = 1; - case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL - case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 - case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 - case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 + // prevent divide by zero, should not happen if matrix is orthogonal and should be + // caught by singularity test above, but I've left it in just in case - } + this.x = ( m32 - m23 ) / s; + this.y = ( m13 - m31 ) / s; + this.z = ( m21 - m12 ) / s; + this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); - } + return this; - // Array of scalars + }, - function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); } - function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); } + min: function ( v ) { - // Array of vectors (flat or from THREE classes) + this.x = Math.min( this.x, v.x ); + this.y = Math.min( this.y, v.y ); + this.z = Math.min( this.z, v.z ); + this.w = Math.min( this.w, v.w ); - function setValueV2a( gl, v ) { + return this; - gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) ); + }, - } + max: function ( v ) { - function setValueV3a( gl, v ) { + this.x = Math.max( this.x, v.x ); + this.y = Math.max( this.y, v.y ); + this.z = Math.max( this.z, v.z ); + this.w = Math.max( this.w, v.w ); - gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) ); + return this; - } + }, - function setValueV4a( gl, v ) { + clamp: function ( min, max ) { - gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) ); + // assumes min < max, componentwise - } + this.x = Math.max( min.x, Math.min( max.x, this.x ) ); + this.y = Math.max( min.y, Math.min( max.y, this.y ) ); + this.z = Math.max( min.z, Math.min( max.z, this.z ) ); + this.w = Math.max( min.w, Math.min( max.w, this.w ) ); - // Array of matrices (flat or from THREE clases) + return this; - function setValueM2a( gl, v ) { + }, - gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) ); + clampScalar: function () { - } + var min, max; - function setValueM3a( gl, v ) { + return function clampScalar( minVal, maxVal ) { - gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) ); + if ( min === undefined ) { - } + min = new Vector4(); + max = new Vector4(); - function setValueM4a( gl, v ) { + } - gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) ); + min.set( minVal, minVal, minVal, minVal ); + max.set( maxVal, maxVal, maxVal, maxVal ); - } + return this.clamp( min, max ); - // Array of textures (2D / Cube) + }; - function setValueT1a( gl, v, renderer ) { + }(), - var n = v.length, - units = allocTexUnits( renderer, n ); + clampLength: function ( min, max ) { - gl.uniform1iv( this.addr, units ); + var length = this.length(); - for ( var i = 0; i !== n; ++ i ) { + return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); - renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); + }, - } + floor: function () { - } + this.x = Math.floor( this.x ); + this.y = Math.floor( this.y ); + this.z = Math.floor( this.z ); + this.w = Math.floor( this.w ); - function setValueT6a( gl, v, renderer ) { + return this; - var n = v.length, - units = allocTexUnits( renderer, n ); + }, - gl.uniform1iv( this.addr, units ); + ceil: function () { - for ( var i = 0; i !== n; ++ i ) { + this.x = Math.ceil( this.x ); + this.y = Math.ceil( this.y ); + this.z = Math.ceil( this.z ); + this.w = Math.ceil( this.w ); - renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); + return this; - } + }, - } + round: function () { - // Helper to pick the right setter for a pure (bottom-level) array + this.x = Math.round( this.x ); + this.y = Math.round( this.y ); + this.z = Math.round( this.z ); + this.w = Math.round( this.w ); - function getPureArraySetter( type ) { + return this; - switch ( type ) { + }, - case 0x1406: return setValue1fv; // FLOAT - case 0x8b50: return setValueV2a; // _VEC2 - case 0x8b51: return setValueV3a; // _VEC3 - case 0x8b52: return setValueV4a; // _VEC4 + roundToZero: function () { - case 0x8b5a: return setValueM2a; // _MAT2 - case 0x8b5b: return setValueM3a; // _MAT3 - case 0x8b5c: return setValueM4a; // _MAT4 + this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); + this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); + this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); + this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); - case 0x8b5e: return setValueT1a; // SAMPLER_2D - case 0x8b60: return setValueT6a; // SAMPLER_CUBE + return this; - case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL - case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 - case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 - case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 + }, - } + negate: function () { - } + this.x = - this.x; + this.y = - this.y; + this.z = - this.z; + this.w = - this.w; - // --- Uniform Classes --- + return this; - function SingleUniform( id, activeInfo, addr ) { + }, - this.id = id; - this.addr = addr; - this.setValue = getSingularSetter( activeInfo.type ); + dot: function ( v ) { - // this.path = activeInfo.name; // DEBUG + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; - } + }, - function PureArrayUniform( id, activeInfo, addr ) { + lengthSq: function () { - this.id = id; - this.addr = addr; - this.size = activeInfo.size; - this.setValue = getPureArraySetter( activeInfo.type ); + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; - // this.path = activeInfo.name; // DEBUG + }, - } + length: function () { - function StructuredUniform( id ) { + return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); - this.id = id; + }, - UniformContainer.call( this ); // mix-in + manhattanLength: function () { - } + return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); - StructuredUniform.prototype.setValue = function ( gl, value ) { + }, - // Note: Don't need an extra 'renderer' parameter, since samplers - // are not allowed in structured uniforms. + normalize: function () { - var seq = this.seq; + return this.divideScalar( this.length() || 1 ); - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + }, - var u = seq[ i ]; - u.setValue( gl, value[ u.id ] ); + setLength: function ( length ) { - } + return this.normalize().multiplyScalar( length ); - }; + }, - // --- Top-level --- + lerp: function ( v, alpha ) { - // Parser - builds up the property tree from the path strings + this.x += ( v.x - this.x ) * alpha; + this.y += ( v.y - this.y ) * alpha; + this.z += ( v.z - this.z ) * alpha; + this.w += ( v.w - this.w ) * alpha; - var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; + return this; - // extracts - // - the identifier (member name or array index) - // - followed by an optional right bracket (found when array index) - // - followed by an optional left bracket or dot (type of subscript) - // - // Note: These portions can be read in a non-overlapping fashion and - // allow straightforward parsing of the hierarchy that WebGL encodes - // in the uniform names. + }, - function addUniform( container, uniformObject ) { + lerpVectors: function ( v1, v2, alpha ) { - container.seq.push( uniformObject ); - container.map[ uniformObject.id ] = uniformObject; + return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); - } + }, - function parseUniform( activeInfo, addr, container ) { + equals: function ( v ) { - var path = activeInfo.name, - pathLength = path.length; + return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); - // reset RegExp object, because of the early exit of a previous run - RePathPart.lastIndex = 0; + }, - for ( ; ; ) { + fromArray: function ( array, offset ) { - var match = RePathPart.exec( path ), - matchEnd = RePathPart.lastIndex, + if ( offset === undefined ) offset = 0; - id = match[ 1 ], - idIsIndex = match[ 2 ] === ']', - subscript = match[ 3 ]; + this.x = array[ offset ]; + this.y = array[ offset + 1 ]; + this.z = array[ offset + 2 ]; + this.w = array[ offset + 3 ]; - if ( idIsIndex ) id = id | 0; // convert to integer + return this; - if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { + }, - // bare name or "pure" bottom-level array "[0]" suffix + toArray: function ( array, offset ) { - addUniform( container, subscript === undefined ? - new SingleUniform( id, activeInfo, addr ) : - new PureArrayUniform( id, activeInfo, addr ) ); + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - break; + array[ offset ] = this.x; + array[ offset + 1 ] = this.y; + array[ offset + 2 ] = this.z; + array[ offset + 3 ] = this.w; - } else { + return array; - // step into inner node / create it in case it doesn't exist + }, - var map = container.map, next = map[ id ]; + fromBufferAttribute: function ( attribute, index, offset ) { - if ( next === undefined ) { + if ( offset !== undefined ) { - next = new StructuredUniform( id ); - addUniform( container, next ); + console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' ); - } + } - container = next; + this.x = attribute.getX( index ); + this.y = attribute.getY( index ); + this.z = attribute.getZ( index ); + this.w = attribute.getW( index ); - } + return this; } - } + } ); - // Root Container + /** + * @author szimek / https://github.com/szimek/ + * @author alteredq / http://alteredqualia.com/ + * @author Marius Kintel / https://github.com/kintel + */ - function WebGLUniforms( gl, program, renderer ) { + /* + In options, we can specify: + * Texture parameters for an auto-generated target texture + * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers + */ + function WebGLRenderTarget( width, height, options ) { - UniformContainer.call( this ); + this.width = width; + this.height = height; - this.renderer = renderer; + this.scissor = new Vector4( 0, 0, width, height ); + this.scissorTest = false; - var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); + this.viewport = new Vector4( 0, 0, width, height ); - for ( var i = 0; i < n; ++ i ) { + options = options || {}; - var info = gl.getActiveUniform( program, i ), - path = info.name, - addr = gl.getUniformLocation( program, path ); + if ( options.minFilter === undefined ) options.minFilter = LinearFilter; - parseUniform( info, addr, this ); + this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); - } + this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; + this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; + this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; } - WebGLUniforms.prototype.setValue = function ( gl, name, value ) { + WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { - var u = this.map[ name ]; + constructor: WebGLRenderTarget, - if ( u !== undefined ) u.setValue( gl, value, this.renderer ); + isWebGLRenderTarget: true, - }; + setSize: function ( width, height ) { - WebGLUniforms.prototype.setOptional = function ( gl, object, name ) { + if ( this.width !== width || this.height !== height ) { - var v = object[ name ]; + this.width = width; + this.height = height; - if ( v !== undefined ) this.setValue( gl, name, v ); + this.dispose(); - }; + } + this.viewport.set( 0, 0, width, height ); + this.scissor.set( 0, 0, width, height ); - // Static interface + }, - WebGLUniforms.upload = function ( gl, seq, values, renderer ) { + clone: function () { - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + return new this.constructor().copy( this ); - var u = seq[ i ], - v = values[ u.id ]; + }, - if ( v.needsUpdate !== false ) { + copy: function ( source ) { - // note: always updating when .needsUpdate is undefined - u.setValue( gl, v.value, renderer ); + this.width = source.width; + this.height = source.height; - } + this.viewport.copy( source.viewport ); - } + this.texture = source.texture.clone(); - }; + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.depthTexture = source.depthTexture; - WebGLUniforms.seqWithValue = function ( seq, values ) { + return this; - var r = []; + }, - for ( var i = 0, n = seq.length; i !== n; ++ i ) { + dispose: function () { - var u = seq[ i ]; - if ( u.id in values ) r.push( u ); + this.dispatchEvent( { type: 'dispose' } ); } - return r; - - }; + } ); /** - * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com */ - var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, - 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, - 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, - 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, - 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, - 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, - 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, - 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, - 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, - 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, - 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, - 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, - 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, - 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, - 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, - 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, - 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, - 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, - 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, - 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, - 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, - 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, - 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, - 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; + function WebGLRenderTargetCube( width, height, options ) { - function Color( r, g, b ) { + WebGLRenderTarget.call( this, width, height, options ); - if ( g === undefined && b === undefined ) { + this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 + this.activeMipMapLevel = 0; - // r is THREE.Color, hex or string - return this.set( r ); + } - } + WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype ); + WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube; - return this.setRGB( r, g, b ); + WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true; - } + /** + * @author alteredq / http://alteredqualia.com/ + */ - Object.assign( Color.prototype, { + function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { - isColor: true, + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - r: 1, g: 1, b: 1, + this.image = { data: data, width: width, height: height }; - set: function ( value ) { + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; - if ( value && value.isColor ) { + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; - this.copy( value ); + } - } else if ( typeof value === 'number' ) { + DataTexture.prototype = Object.create( Texture.prototype ); + DataTexture.prototype.constructor = DataTexture; - this.setHex( value ); + DataTexture.prototype.isDataTexture = true; - } else if ( typeof value === 'string' ) { + /** + * @author bhouston / http://clara.io + * @author WestLangley / http://github.com/WestLangley + */ - this.setStyle( value ); + function Box3( min, max ) { - } + this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity ); - return this; + } - }, + Object.assign( Box3.prototype, { - setScalar: function ( scalar ) { + isBox3: true, - this.r = scalar; - this.g = scalar; - this.b = scalar; + set: function ( min, max ) { + + this.min.copy( min ); + this.max.copy( max ); return this; }, - setHex: function ( hex ) { + setFromArray: function ( array ) { - hex = Math.floor( hex ); + var minX = + Infinity; + var minY = + Infinity; + var minZ = + Infinity; - this.r = ( hex >> 16 & 255 ) / 255; - this.g = ( hex >> 8 & 255 ) / 255; - this.b = ( hex & 255 ) / 255; + var maxX = - Infinity; + var maxY = - Infinity; + var maxZ = - Infinity; - return this; + for ( var i = 0, l = array.length; i < l; i += 3 ) { - }, + var x = array[ i ]; + var y = array[ i + 1 ]; + var z = array[ i + 2 ]; - setRGB: function ( r, g, b ) { + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; - this.r = r; - this.g = g; - this.b = b; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; + + } + + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); return this; }, - setHSL: function () { + setFromBufferAttribute: function ( attribute ) { - function hue2rgb( p, q, t ) { + var minX = + Infinity; + var minY = + Infinity; + var minZ = + Infinity; - if ( t < 0 ) t += 1; - if ( t > 1 ) t -= 1; - if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; - if ( t < 1 / 2 ) return q; - if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); - return p; + var maxX = - Infinity; + var maxY = - Infinity; + var maxZ = - Infinity; + + for ( var i = 0, l = attribute.count; i < l; i ++ ) { + + var x = attribute.getX( i ); + var y = attribute.getY( i ); + var z = attribute.getZ( i ); + + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( z < minZ ) minZ = z; + + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; + if ( z > maxZ ) maxZ = z; } - return function setHSL( h, s, l ) { + this.min.set( minX, minY, minZ ); + this.max.set( maxX, maxY, maxZ ); - // h,s,l ranges are in 0.0 - 1.0 - h = _Math.euclideanModulo( h, 1 ); - s = _Math.clamp( s, 0, 1 ); - l = _Math.clamp( l, 0, 1 ); + return this; - if ( s === 0 ) { + }, - this.r = this.g = this.b = l; + setFromPoints: function ( points ) { - } else { + this.makeEmpty(); - var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); - var q = ( 2 * l ) - p; + for ( var i = 0, il = points.length; i < il; i ++ ) { - this.r = hue2rgb( q, p, h + 1 / 3 ); - this.g = hue2rgb( q, p, h ); - this.b = hue2rgb( q, p, h - 1 / 3 ); + this.expandByPoint( points[ i ] ); - } + } + + return this; + + }, + + setFromCenterAndSize: function () { + + var v1 = new Vector3(); + + return function setFromCenterAndSize( center, size ) { + + var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); return this; @@ -4987,5827 +4796,5521 @@ }(), - setStyle: function ( style ) { + setFromObject: function ( object ) { - function handleAlpha( string ) { + this.makeEmpty(); - if ( string === undefined ) return; + return this.expandByObject( object ); - if ( parseFloat( string ) < 1 ) { + }, - console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); + clone: function () { - } + return new this.constructor().copy( this ); - } + }, + copy: function ( box ) { - var m; + this.min.copy( box.min ); + this.max.copy( box.max ); - if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { + return this; - // rgb / hsl + }, - var color; - var name = m[ 1 ]; - var components = m[ 2 ]; + makeEmpty: function () { - switch ( name ) { + this.min.x = this.min.y = this.min.z = + Infinity; + this.max.x = this.max.y = this.max.z = - Infinity; - case 'rgb': - case 'rgba': + return this; - if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + }, - // rgb(255,0,0) rgba(255,0,0,0.5) - this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; - this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; - this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; + isEmpty: function () { - handleAlpha( color[ 5 ] ); + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - return this; + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); - } + }, - if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + getCenter: function ( target ) { - // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) - this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; - this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; - this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; + if ( target === undefined ) { - handleAlpha( color[ 5 ] ); + console.warn( 'THREE.Box3: .getCenter() target is now required' ); + target = new Vector3(); - return this; + } - } + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - break; + }, - case 'hsl': - case 'hsla': + getSize: function ( target ) { - if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { + if ( target === undefined ) { - // hsl(120,50%,50%) hsla(120,50%,50%,0.5) - var h = parseFloat( color[ 1 ] ) / 360; - var s = parseInt( color[ 2 ], 10 ) / 100; - var l = parseInt( color[ 3 ], 10 ) / 100; + console.warn( 'THREE.Box3: .getSize() target is now required' ); + target = new Vector3(); - handleAlpha( color[ 5 ] ); + } - return this.setHSL( h, s, l ); + return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); - } + }, - break; + expandByPoint: function ( point ) { - } + this.min.min( point ); + this.max.max( point ); - } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { + return this; - // hex color + }, - var hex = m[ 1 ]; - var size = hex.length; + expandByVector: function ( vector ) { - if ( size === 3 ) { + this.min.sub( vector ); + this.max.add( vector ); - // #ff0 - this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255; - this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255; - this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255; + return this; - return this; + }, - } else if ( size === 6 ) { + expandByScalar: function ( scalar ) { - // #ff0000 - this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255; - this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255; - this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255; + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); - return this; + return this; - } + }, - } + expandByObject: function () { - if ( style && style.length > 0 ) { + // Computes the world-axis-aligned bounding box of an object (including its children), + // accounting for both the object's, and children's, world transforms - // color keywords - var hex = ColorKeywords[ style ]; + var scope, i, l; - if ( hex !== undefined ) { + var v1 = new Vector3(); - // red - this.setHex( hex ); + function traverse( node ) { - } else { + var geometry = node.geometry; - // unknown color - console.warn( 'THREE.Color: Unknown color ' + style ); + if ( geometry !== undefined ) { - } + if ( geometry.isGeometry ) { - } + var vertices = geometry.vertices; - return this; + for ( i = 0, l = vertices.length; i < l; i ++ ) { - }, + v1.copy( vertices[ i ] ); + v1.applyMatrix4( node.matrixWorld ); - clone: function () { + scope.expandByPoint( v1 ); - return new this.constructor( this.r, this.g, this.b ); + } - }, + } else if ( geometry.isBufferGeometry ) { - copy: function ( color ) { + var attribute = geometry.attributes.position; - this.r = color.r; - this.g = color.g; - this.b = color.b; + if ( attribute !== undefined ) { - return this; + for ( i = 0, l = attribute.count; i < l; i ++ ) { - }, + v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld ); - copyGammaToLinear: function ( color, gammaFactor ) { + scope.expandByPoint( v1 ); - if ( gammaFactor === undefined ) gammaFactor = 2.0; + } - this.r = Math.pow( color.r, gammaFactor ); - this.g = Math.pow( color.g, gammaFactor ); - this.b = Math.pow( color.b, gammaFactor ); + } - return this; + } - }, + } - copyLinearToGamma: function ( color, gammaFactor ) { + } - if ( gammaFactor === undefined ) gammaFactor = 2.0; + return function expandByObject( object ) { - var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; + scope = this; - this.r = Math.pow( color.r, safeInverse ); - this.g = Math.pow( color.g, safeInverse ); - this.b = Math.pow( color.b, safeInverse ); + object.updateMatrixWorld( true ); - return this; + object.traverse( traverse ); - }, + return this; - convertGammaToLinear: function () { + }; - var r = this.r, g = this.g, b = this.b; + }(), - this.r = r * r; - this.g = g * g; - this.b = b * b; + containsPoint: function ( point ) { - return this; + return point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y || + point.z < this.min.z || point.z > this.max.z ? false : true; }, - convertLinearToGamma: function () { - - this.r = Math.sqrt( this.r ); - this.g = Math.sqrt( this.g ); - this.b = Math.sqrt( this.b ); + containsBox: function ( box ) { - return this; + return this.min.x <= box.min.x && box.max.x <= this.max.x && + this.min.y <= box.min.y && box.max.y <= this.max.y && + this.min.z <= box.min.z && box.max.z <= this.max.z; }, - getHex: function () { + getParameter: function ( point, target ) { - return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; + // This can potentially have a divide by zero if the box + // has a size dimension of 0. + + if ( target === undefined ) { + + console.warn( 'THREE.Box3: .getParameter() target is now required' ); + target = new Vector3(); + + } + + return target.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ), + ( point.z - this.min.z ) / ( this.max.z - this.min.z ) + ); }, - getHexString: function () { + intersectsBox: function ( box ) { - return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); + // using 6 splitting planes to rule out intersections. + return box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y || + box.max.z < this.min.z || box.min.z > this.max.z ? false : true; }, - getHSL: function ( optionalTarget ) { + intersectsSphere: ( function () { - // h,s,l ranges are in 0.0 - 1.0 + var closestPoint = new Vector3(); - var hsl = optionalTarget || { h: 0, s: 0, l: 0 }; + return function intersectsSphere( sphere ) { - var r = this.r, g = this.g, b = this.b; + // Find the point on the AABB closest to the sphere center. + this.clampPoint( sphere.center, closestPoint ); - var max = Math.max( r, g, b ); - var min = Math.min( r, g, b ); + // If that point is inside the sphere, the AABB and sphere intersect. + return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); - var hue, saturation; - var lightness = ( min + max ) / 2.0; + }; - if ( min === max ) { + } )(), - hue = 0; - saturation = 0; + intersectsPlane: function ( plane ) { + + // We compute the minimum and maximum dot product values. If those values + // are on the same side (back or front) of the plane, then there is no intersection. + + var min, max; + + if ( plane.normal.x > 0 ) { + + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; } else { - var delta = max - min; + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; - saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + } - switch ( max ) { + if ( plane.normal.y > 0 ) { - case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; - case g: hue = ( b - r ) / delta + 2; break; - case b: hue = ( r - g ) / delta + 4; break; + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; - } + } else { - hue /= 6; + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; } - hsl.h = hue; - hsl.s = saturation; - hsl.l = lightness; + if ( plane.normal.z > 0 ) { - return hsl; + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; - }, + } else { - getStyle: function () { + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; - return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; + } + + return ( min <= plane.constant && max >= plane.constant ); }, - offsetHSL: function ( h, s, l ) { + intersectsTriangle: ( function () { - var hsl = this.getHSL(); + // triangle centered vertices + var v0 = new Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); - hsl.h += h; hsl.s += s; hsl.l += l; + // triangle edge vectors + var f0 = new Vector3(); + var f1 = new Vector3(); + var f2 = new Vector3(); - this.setHSL( hsl.h, hsl.s, hsl.l ); + var testAxis = new Vector3(); - return this; + var center = new Vector3(); + var extents = new Vector3(); - }, + var triangleNormal = new Vector3(); - add: function ( color ) { + function satForAxes( axes ) { - this.r += color.r; - this.g += color.g; - this.b += color.b; + var i, j; - return this; + for ( i = 0, j = axes.length - 3; i <= j; i += 3 ) { - }, + testAxis.fromArray( axes, i ); + // project the aabb onto the seperating axis + var r = extents.x * Math.abs( testAxis.x ) + extents.y * Math.abs( testAxis.y ) + extents.z * Math.abs( testAxis.z ); + // project all 3 vertices of the triangle onto the seperating axis + var p0 = v0.dot( testAxis ); + var p1 = v1.dot( testAxis ); + var p2 = v2.dot( testAxis ); + // actual test, basically see if either of the most extreme of the triangle points intersects r + if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { - addColors: function ( color1, color2 ) { + // points of the projected triangle are outside the projected half-length of the aabb + // the axis is seperating and we can exit + return false; - this.r = color1.r + color2.r; - this.g = color1.g + color2.g; - this.b = color1.b + color2.b; + } - return this; + } - }, + return true; - addScalar: function ( s ) { + } - this.r += s; - this.g += s; - this.b += s; + return function intersectsTriangle( triangle ) { - return this; + if ( this.isEmpty() ) { - }, + return false; - sub: function( color ) { + } - this.r = Math.max( 0, this.r - color.r ); - this.g = Math.max( 0, this.g - color.g ); - this.b = Math.max( 0, this.b - color.b ); + // compute box center and extents + this.getCenter( center ); + extents.subVectors( this.max, center ); - return this; + // translate triangle to aabb origin + v0.subVectors( triangle.a, center ); + v1.subVectors( triangle.b, center ); + v2.subVectors( triangle.c, center ); - }, + // compute edge vectors for triangle + f0.subVectors( v1, v0 ); + f1.subVectors( v2, v1 ); + f2.subVectors( v0, v2 ); - multiply: function ( color ) { + // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb + // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation + // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) + var axes = [ + 0, - f0.z, f0.y, 0, - f1.z, f1.y, 0, - f2.z, f2.y, + f0.z, 0, - f0.x, f1.z, 0, - f1.x, f2.z, 0, - f2.x, + - f0.y, f0.x, 0, - f1.y, f1.x, 0, - f2.y, f2.x, 0 + ]; + if ( ! satForAxes( axes ) ) { - this.r *= color.r; - this.g *= color.g; - this.b *= color.b; + return false; - return this; + } - }, + // test 3 face normals from the aabb + axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; + if ( ! satForAxes( axes ) ) { - multiplyScalar: function ( s ) { + return false; - this.r *= s; - this.g *= s; - this.b *= s; + } - return this; + // finally testing the face normal of the triangle + // use already existing triangle edge vectors here + triangleNormal.crossVectors( f0, f1 ); + axes = [ triangleNormal.x, triangleNormal.y, triangleNormal.z ]; + return satForAxes( axes ); - }, + }; - lerp: function ( color, alpha ) { + } )(), - this.r += ( color.r - this.r ) * alpha; - this.g += ( color.g - this.g ) * alpha; - this.b += ( color.b - this.b ) * alpha; + clampPoint: function ( point, target ) { - return this; + if ( target === undefined ) { - }, + console.warn( 'THREE.Box3: .clampPoint() target is now required' ); + target = new Vector3(); - equals: function ( c ) { + } - return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); + return target.copy( point ).clamp( this.min, this.max ); }, - fromArray: function ( array, offset ) { + distanceToPoint: function () { - if ( offset === undefined ) offset = 0; + var v1 = new Vector3(); - this.r = array[ offset ]; - this.g = array[ offset + 1 ]; - this.b = array[ offset + 2 ]; + return function distanceToPoint( point ) { - return this; + var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); - }, + }; - toArray: function ( array, offset ) { + }(), - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + getBoundingSphere: function () { - array[ offset ] = this.r; - array[ offset + 1 ] = this.g; - array[ offset + 2 ] = this.b; + var v1 = new Vector3(); - return array; + return function getBoundingSphere( target ) { - }, + if ( target === undefined ) { - toJSON: function () { + console.warn( 'THREE.Box3: .getBoundingSphere() target is now required' ); + target = new Sphere(); - return this.getHex(); + } - } + this.getCenter( target.center ); - } ); + target.radius = this.getSize( v1 ).length() * 0.5; - /** - * Uniforms library for shared webgl shaders - */ + return target; - var UniformsLib = { + }; - common: { + }(), - diffuse: { value: new Color( 0xeeeeee ) }, - opacity: { value: 1.0 }, + intersect: function ( box ) { - map: { value: null }, - offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }, + this.min.max( box.min ); + this.max.min( box.max ); - specularMap: { value: null }, - alphaMap: { value: null }, + // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. + if ( this.isEmpty() ) this.makeEmpty(); - envMap: { value: null }, - flipEnvMap: { value: - 1 }, - reflectivity: { value: 1.0 }, - refractionRatio: { value: 0.98 } + return this; }, - aomap: { + union: function ( box ) { - aoMap: { value: null }, - aoMapIntensity: { value: 1 } + this.min.min( box.min ); + this.max.max( box.max ); + + return this; }, - lightmap: { + applyMatrix4: function () { - lightMap: { value: null }, - lightMapIntensity: { value: 1 } + var points = [ + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3(), + new Vector3() + ]; - }, + return function applyMatrix4( matrix ) { - emissivemap: { + // transform of empty box is an empty box. + if ( this.isEmpty() ) return this; - emissiveMap: { value: null } + // NOTE: I am using a binary pattern to specify all 2^3 combinations below + points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 + points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 + points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 + points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 + points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 + points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 + points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 + points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 - }, + this.setFromPoints( points ); - bumpmap: { + return this; - bumpMap: { value: null }, - bumpScale: { value: 1 } + }; - }, + }(), - normalmap: { + translate: function ( offset ) { - normalMap: { value: null }, - normalScale: { value: new Vector2( 1, 1 ) } + this.min.add( offset ); + this.max.add( offset ); + + return this; }, - displacementmap: { + equals: function ( box ) { - displacementMap: { value: null }, - displacementScale: { value: 1 }, - displacementBias: { value: 0 } + return box.min.equals( this.min ) && box.max.equals( this.max ); - }, + } - roughnessmap: { + } ); - roughnessMap: { value: null } + /** + * @author bhouston / http://clara.io + * @author mrdoob / http://mrdoob.com/ + */ - }, + function Sphere( center, radius ) { - metalnessmap: { + this.center = ( center !== undefined ) ? center : new Vector3(); + this.radius = ( radius !== undefined ) ? radius : 0; - metalnessMap: { value: null } + } - }, + Object.assign( Sphere.prototype, { - gradientmap: { + set: function ( center, radius ) { - gradientMap: { value: null } + this.center.copy( center ); + this.radius = radius; + + return this; }, - fog: { + setFromPoints: function () { - fogDensity: { value: 0.00025 }, - fogNear: { value: 1 }, - fogFar: { value: 2000 }, - fogColor: { value: new Color( 0xffffff ) } + var box = new Box3(); - }, + return function setFromPoints( points, optionalCenter ) { - lights: { + var center = this.center; - ambientLightColor: { value: [] }, + if ( optionalCenter !== undefined ) { - directionalLights: { value: [], properties: { - direction: {}, - color: {}, + center.copy( optionalCenter ); - shadow: {}, - shadowBias: {}, - shadowRadius: {}, - shadowMapSize: {} - } }, + } else { - directionalShadowMap: { value: [] }, - directionalShadowMatrix: { value: [] }, + box.setFromPoints( points ).getCenter( center ); - spotLights: { value: [], properties: { - color: {}, - position: {}, - direction: {}, - distance: {}, - coneCos: {}, - penumbraCos: {}, - decay: {}, + } - shadow: {}, - shadowBias: {}, - shadowRadius: {}, - shadowMapSize: {} - } }, + var maxRadiusSq = 0; - spotShadowMap: { value: [] }, - spotShadowMatrix: { value: [] }, + for ( var i = 0, il = points.length; i < il; i ++ ) { - pointLights: { value: [], properties: { - color: {}, - position: {}, - decay: {}, - distance: {}, + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); - shadow: {}, - shadowBias: {}, - shadowRadius: {}, - shadowMapSize: {} - } }, + } - pointShadowMap: { value: [] }, - pointShadowMatrix: { value: [] }, + this.radius = Math.sqrt( maxRadiusSq ); - hemisphereLights: { value: [], properties: { - direction: {}, - skyColor: {}, - groundColor: {} - } }, + return this; - // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src - rectAreaLights: { value: [], properties: { - color: {}, - position: {}, - width: {}, - height: {} - } } + }; - }, + }(), - points: { + clone: function () { - diffuse: { value: new Color( 0xeeeeee ) }, - opacity: { value: 1.0 }, - size: { value: 1.0 }, - scale: { value: 1.0 }, - map: { value: null }, - offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) } + return new this.constructor().copy( this ); - } + }, - }; + copy: function ( sphere ) { - /** - * Uniform Utilities - */ + this.center.copy( sphere.center ); + this.radius = sphere.radius; - var UniformsUtils = { + return this; - merge: function ( uniforms ) { + }, - var merged = {}; + empty: function () { - for ( var u = 0; u < uniforms.length; u ++ ) { + return ( this.radius <= 0 ); - var tmp = this.clone( uniforms[ u ] ); + }, - for ( var p in tmp ) { + containsPoint: function ( point ) { - merged[ p ] = tmp[ p ]; + return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); - } + }, - } + distanceToPoint: function ( point ) { - return merged; + return ( point.distanceTo( this.center ) - this.radius ); }, - clone: function ( uniforms_src ) { + intersectsSphere: function ( sphere ) { - var uniforms_dst = {}; + var radiusSum = this.radius + sphere.radius; - for ( var u in uniforms_src ) { + return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); - uniforms_dst[ u ] = {}; + }, - for ( var p in uniforms_src[ u ] ) { + intersectsBox: function ( box ) { - var parameter_src = uniforms_src[ u ][ p ]; + return box.intersectsSphere( this ); - if ( parameter_src && ( parameter_src.isColor || - parameter_src.isMatrix3 || parameter_src.isMatrix4 || - parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 || - parameter_src.isTexture ) ) { + }, - uniforms_dst[ u ][ p ] = parameter_src.clone(); + intersectsPlane: function ( plane ) { - } else if ( Array.isArray( parameter_src ) ) { + return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; - uniforms_dst[ u ][ p ] = parameter_src.slice(); + }, - } else { + clampPoint: function ( point, target ) { - uniforms_dst[ u ][ p ] = parameter_src; + var deltaLengthSq = this.center.distanceToSquared( point ); - } + if ( target === undefined ) { - } + console.warn( 'THREE.Sphere: .clampPoint() target is now required' ); + target = new Vector3(); } - return uniforms_dst; - - } + target.copy( point ); - }; + if ( deltaLengthSq > ( this.radius * this.radius ) ) { - var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n"; + target.sub( this.center ).normalize(); + target.multiplyScalar( this.radius ).add( this.center ); - var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n"; + } - var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n"; + return target; - var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n"; + }, - var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; + getBoundingBox: function ( target ) { - var begin_vertex = "\nvec3 transformed = vec3( position );\n"; + if ( target === undefined ) { - var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n"; + console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' ); + target = new Box3(); - var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.86267 + (0.49788 + 0.01436 * y ) * y;\n\tfloat b = 3.45068 + (4.18814 + y) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt( 1.0 - x * x ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tvec3 result = vec3( LTC_ClippedSphereFormFactor( vectorFormFactor ) );\n\treturn result;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n"; + } - var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n"; + target.set( this.center, this.center ); + target.expandByScalar( this.radius ); - var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n"; + return target; - var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n"; + }, - var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n"; + applyMatrix4: function ( matrix ) { - var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n"; + this.center.applyMatrix4( matrix ); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); - var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif"; + return this; - var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n"; + }, - var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; + translate: function ( offset ) { - var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif"; + this.center.add( offset ); - var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transpose( const in mat3 v ) {\n\tmat3 tmp;\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\n\treturn tmp;\n}\n"; + return this; - var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n"; + }, - var defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n"; + equals: function ( sphere ) { - var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n"; + return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); - var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n"; + } - var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n"; + } ); - var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n"; + /** + * @author bhouston / http://clara.io + */ - var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n"; + function Plane( normal, constant ) { - var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n\tXp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract(Le);\n\tvResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n"; + // normal is assumed to be normalized - var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = asin( flipNormal * reflectVec.y ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n"; + this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 ); + this.constant = ( constant !== undefined ) ? constant : 0; - var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n"; + } - var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n"; + Object.assign( Plane.prototype, { - var envmap_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n"; + set: function ( normal, constant ) { - var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif"; + this.normal.copy( normal ); + this.constant = constant; - var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n"; + return this; - var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n"; + }, - var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif\n"; + setComponents: function ( x, y, z, w ) { - var gradientmap_pars_fragment = "#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif\n"; + this.normal.set( x, y, z ); + this.constant = w; - var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n"; + return this; - var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; + }, - var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n"; + setFromNormalAndCoplanarPoint: function ( normal, point ) { - var lights_pars = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n"; + this.normal.copy( normal ); + this.constant = - point.dot( this.normal ); - var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n"; + return this; - var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n"; + }, - var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n"; + setFromCoplanarPoints: function () { - var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tfloat norm = texture2D( ltcMag, uv ).a;\n\t\tvec4 t = texture2D( ltcMat, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( 1, 0, t.y ),\n\t\t\tvec3( 0, t.z, 0 ),\n\t\t\tvec3( t.w, 0, t.x )\n\t\t);\n\t\treflectedLight.directSpecular += lightColor * material.specularColor * norm * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n"; + var v1 = new Vector3(); + var v2 = new Vector3(); - var lights_template = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n"; + return function setFromCoplanarPoints( a, b, c ) { - var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif"; + var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize(); - var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n"; + // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? - var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif"; + this.setFromNormalAndCoplanarPoint( normal, a ); - var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n"; + return this; - var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n"; + }; - var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n"; + }(), - var map_particle_fragment = "#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n"; + clone: function () { - var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n"; + return new this.constructor().copy( this ); - var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n"; + }, - var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; + copy: function ( plane ) { - var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n"; + this.normal.copy( plane.normal ); + this.constant = plane.constant; - var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif"; + return this; - var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n"; + }, - var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n"; + normalize: function () { - var normal_fragment = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n"; + // Note: will lead to a divide by zero if the plane is invalid. - var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n"; + var inverseNormalLength = 1.0 / this.normal.length(); + this.normal.multiplyScalar( inverseNormalLength ); + this.constant *= inverseNormalLength; - var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n"; + return this; - var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n"; + }, - var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n"; + negate: function () { - var dithering_fragment = "#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n"; + this.constant *= - 1; + this.normal.negate(); - var dithering_pars_fragment = "#if defined( DITHERING )\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif\n"; + return this; - var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n"; + }, - var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; + distanceToPoint: function ( point ) { - var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n"; + return this.normal.dot( point ) + this.constant; - var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n"; + }, - var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n"; + distanceToSphere: function ( sphere ) { - var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n"; + return this.distanceToPoint( sphere.center ) - sphere.radius; - var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; + }, - var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n"; + projectPoint: function ( point, target ) { - var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif\n"; + if ( target === undefined ) { - var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n"; + console.warn( 'THREE.Plane: .projectPoint() target is now required' ); + target = new Vector3(); - var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif"; + } - var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; + return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point ); - var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n"; + }, - var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n"; + intersectLine: function () { - var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif"; + var v1 = new Vector3(); - var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n"; + return function intersectLine( line, target ) { - var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif"; + if ( target === undefined ) { - var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif"; + console.warn( 'THREE.Plane: .intersectLine() target is now required' ); + target = new Vector3(); - var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif"; + } - var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif"; + var direction = line.delta( v1 ); - var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n"; + var denominator = this.normal.dot( direction ); - var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n"; + if ( denominator === 0 ) { - var cube_vert = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n"; + // line is coplanar, return origin + if ( this.distanceToPoint( line.start ) === 0 ) { - var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n"; + return target.copy( line.start ); - var depth_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + } - var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include \n#include \n#include \nvoid main () {\n\t#include \n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n"; + // Unsure if this is the correct method to handle this case. + return undefined; - var distanceRGBA_vert = "varying vec4 vWorldPosition;\n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition;\n}\n"; + } - var equirect_frag = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n"; + var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; - var equirect_vert = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n"; + if ( t < 0 || t > 1 ) { - var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + return undefined; - var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}\n"; + } - var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + return target.copy( direction ).multiplyScalar( t ).add( line.start ); - var meshbasic_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + }; - var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + }(), - var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + intersectsLine: function ( line ) { - var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. - var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + var startSign = this.distanceToPoint( line.start ); + var endSign = this.distanceToPoint( line.end ); - var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); - var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}\n"; + }, - var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n"; + intersectsBox: function ( box ) { - var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n"; + return box.intersectsPlane( this ); - var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + }, - var points_vert = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + intersectsSphere: function ( sphere ) { - var shadow_frag = "uniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n"; + return sphere.intersectsPlane( this ); - var shadow_vert = "#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; + }, - var ShaderChunk = { - alphamap_fragment: alphamap_fragment, - alphamap_pars_fragment: alphamap_pars_fragment, - alphatest_fragment: alphatest_fragment, - aomap_fragment: aomap_fragment, - aomap_pars_fragment: aomap_pars_fragment, - begin_vertex: begin_vertex, - beginnormal_vertex: beginnormal_vertex, - bsdfs: bsdfs, - bumpmap_pars_fragment: bumpmap_pars_fragment, - clipping_planes_fragment: clipping_planes_fragment, - clipping_planes_pars_fragment: clipping_planes_pars_fragment, - clipping_planes_pars_vertex: clipping_planes_pars_vertex, - clipping_planes_vertex: clipping_planes_vertex, - color_fragment: color_fragment, - color_pars_fragment: color_pars_fragment, - color_pars_vertex: color_pars_vertex, - color_vertex: color_vertex, - common: common, - cube_uv_reflection_fragment: cube_uv_reflection_fragment, - defaultnormal_vertex: defaultnormal_vertex, - displacementmap_pars_vertex: displacementmap_pars_vertex, - displacementmap_vertex: displacementmap_vertex, - emissivemap_fragment: emissivemap_fragment, - emissivemap_pars_fragment: emissivemap_pars_fragment, - encodings_fragment: encodings_fragment, - encodings_pars_fragment: encodings_pars_fragment, - envmap_fragment: envmap_fragment, - envmap_pars_fragment: envmap_pars_fragment, - envmap_pars_vertex: envmap_pars_vertex, - envmap_vertex: envmap_vertex, - fog_vertex: fog_vertex, - fog_pars_vertex: fog_pars_vertex, - fog_fragment: fog_fragment, - fog_pars_fragment: fog_pars_fragment, - gradientmap_pars_fragment: gradientmap_pars_fragment, - lightmap_fragment: lightmap_fragment, - lightmap_pars_fragment: lightmap_pars_fragment, - lights_lambert_vertex: lights_lambert_vertex, - lights_pars: lights_pars, - lights_phong_fragment: lights_phong_fragment, - lights_phong_pars_fragment: lights_phong_pars_fragment, - lights_physical_fragment: lights_physical_fragment, - lights_physical_pars_fragment: lights_physical_pars_fragment, - lights_template: lights_template, - logdepthbuf_fragment: logdepthbuf_fragment, - logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, - logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, - logdepthbuf_vertex: logdepthbuf_vertex, - map_fragment: map_fragment, - map_pars_fragment: map_pars_fragment, - map_particle_fragment: map_particle_fragment, - map_particle_pars_fragment: map_particle_pars_fragment, - metalnessmap_fragment: metalnessmap_fragment, - metalnessmap_pars_fragment: metalnessmap_pars_fragment, - morphnormal_vertex: morphnormal_vertex, - morphtarget_pars_vertex: morphtarget_pars_vertex, - morphtarget_vertex: morphtarget_vertex, - normal_flip: normal_flip, - normal_fragment: normal_fragment, - normalmap_pars_fragment: normalmap_pars_fragment, - packing: packing, - premultiplied_alpha_fragment: premultiplied_alpha_fragment, - project_vertex: project_vertex, - dithering_fragment: dithering_fragment, - dithering_pars_fragment: dithering_pars_fragment, - roughnessmap_fragment: roughnessmap_fragment, - roughnessmap_pars_fragment: roughnessmap_pars_fragment, - shadowmap_pars_fragment: shadowmap_pars_fragment, - shadowmap_pars_vertex: shadowmap_pars_vertex, - shadowmap_vertex: shadowmap_vertex, - shadowmask_pars_fragment: shadowmask_pars_fragment, - skinbase_vertex: skinbase_vertex, - skinning_pars_vertex: skinning_pars_vertex, - skinning_vertex: skinning_vertex, - skinnormal_vertex: skinnormal_vertex, - specularmap_fragment: specularmap_fragment, - specularmap_pars_fragment: specularmap_pars_fragment, - tonemapping_fragment: tonemapping_fragment, - tonemapping_pars_fragment: tonemapping_pars_fragment, - uv_pars_fragment: uv_pars_fragment, - uv_pars_vertex: uv_pars_vertex, - uv_vertex: uv_vertex, - uv2_pars_fragment: uv2_pars_fragment, - uv2_pars_vertex: uv2_pars_vertex, - uv2_vertex: uv2_vertex, - worldpos_vertex: worldpos_vertex, + coplanarPoint: function ( target ) { - cube_frag: cube_frag, - cube_vert: cube_vert, - depth_frag: depth_frag, - depth_vert: depth_vert, - distanceRGBA_frag: distanceRGBA_frag, - distanceRGBA_vert: distanceRGBA_vert, - equirect_frag: equirect_frag, - equirect_vert: equirect_vert, - linedashed_frag: linedashed_frag, - linedashed_vert: linedashed_vert, - meshbasic_frag: meshbasic_frag, - meshbasic_vert: meshbasic_vert, - meshlambert_frag: meshlambert_frag, - meshlambert_vert: meshlambert_vert, - meshphong_frag: meshphong_frag, - meshphong_vert: meshphong_vert, - meshphysical_frag: meshphysical_frag, - meshphysical_vert: meshphysical_vert, - normal_frag: normal_frag, - normal_vert: normal_vert, - points_frag: points_frag, - points_vert: points_vert, - shadow_frag: shadow_frag, - shadow_vert: shadow_vert - }; + if ( target === undefined ) { - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - */ + console.warn( 'THREE.Plane: .coplanarPoint() target is now required' ); + target = new Vector3(); - var ShaderLib = { + } - basic: { + return target.copy( this.normal ).multiplyScalar( - this.constant ); - uniforms: UniformsUtils.merge( [ - UniformsLib.common, - UniformsLib.aomap, - UniformsLib.lightmap, - UniformsLib.fog - ] ), + }, - vertexShader: ShaderChunk.meshbasic_vert, - fragmentShader: ShaderChunk.meshbasic_frag + applyMatrix4: function () { - }, + var v1 = new Vector3(); + var m1 = new Matrix3(); - lambert: { + return function applyMatrix4( matrix, optionalNormalMatrix ) { - uniforms: UniformsUtils.merge( [ - UniformsLib.common, - UniformsLib.aomap, - UniformsLib.lightmap, - UniformsLib.emissivemap, - UniformsLib.fog, - UniformsLib.lights, - { - emissive: { value: new Color( 0x000000 ) } - } - ] ), + var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix ); - vertexShader: ShaderChunk.meshlambert_vert, - fragmentShader: ShaderChunk.meshlambert_frag + var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix ); - }, + var normal = this.normal.applyMatrix3( normalMatrix ).normalize(); - phong: { + this.constant = - referencePoint.dot( normal ); - uniforms: UniformsUtils.merge( [ - UniformsLib.common, - UniformsLib.aomap, - UniformsLib.lightmap, - UniformsLib.emissivemap, - UniformsLib.bumpmap, - UniformsLib.normalmap, - UniformsLib.displacementmap, - UniformsLib.gradientmap, - UniformsLib.fog, - UniformsLib.lights, - { - emissive: { value: new Color( 0x000000 ) }, - specular: { value: new Color( 0x111111 ) }, - shininess: { value: 30 } - } - ] ), + return this; - vertexShader: ShaderChunk.meshphong_vert, - fragmentShader: ShaderChunk.meshphong_frag + }; - }, + }(), - standard: { + translate: function ( offset ) { - uniforms: UniformsUtils.merge( [ - UniformsLib.common, - UniformsLib.aomap, - UniformsLib.lightmap, - UniformsLib.emissivemap, - UniformsLib.bumpmap, - UniformsLib.normalmap, - UniformsLib.displacementmap, - UniformsLib.roughnessmap, - UniformsLib.metalnessmap, - UniformsLib.fog, - UniformsLib.lights, - { - emissive: { value: new Color( 0x000000 ) }, - roughness: { value: 0.5 }, - metalness: { value: 0.5 }, - envMapIntensity: { value: 1 } // temporary - } - ] ), + this.constant -= offset.dot( this.normal ); - vertexShader: ShaderChunk.meshphysical_vert, - fragmentShader: ShaderChunk.meshphysical_frag + return this; }, - points: { - - uniforms: UniformsUtils.merge( [ - UniformsLib.points, - UniformsLib.fog - ] ), - - vertexShader: ShaderChunk.points_vert, - fragmentShader: ShaderChunk.points_frag - - }, - - dashed: { - - uniforms: UniformsUtils.merge( [ - UniformsLib.common, - UniformsLib.fog, - { - scale: { value: 1 }, - dashSize: { value: 1 }, - totalSize: { value: 2 } - } - ] ), - - vertexShader: ShaderChunk.linedashed_vert, - fragmentShader: ShaderChunk.linedashed_frag - - }, - - depth: { - - uniforms: UniformsUtils.merge( [ - UniformsLib.common, - UniformsLib.displacementmap - ] ), - - vertexShader: ShaderChunk.depth_vert, - fragmentShader: ShaderChunk.depth_frag - - }, - - normal: { - - uniforms: UniformsUtils.merge( [ - UniformsLib.common, - UniformsLib.bumpmap, - UniformsLib.normalmap, - UniformsLib.displacementmap, - { - opacity: { value: 1.0 } - } - ] ), - - vertexShader: ShaderChunk.normal_vert, - fragmentShader: ShaderChunk.normal_frag - - }, - - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ - - cube: { - - uniforms: { - tCube: { value: null }, - tFlip: { value: - 1 }, - opacity: { value: 1.0 } - }, - - vertexShader: ShaderChunk.cube_vert, - fragmentShader: ShaderChunk.cube_frag - - }, - - /* ------------------------------------------------------------------------- - // Cube map shader - ------------------------------------------------------------------------- */ - - equirect: { - - uniforms: { - tEquirect: { value: null }, - tFlip: { value: - 1 } - }, - - vertexShader: ShaderChunk.equirect_vert, - fragmentShader: ShaderChunk.equirect_frag - - }, - - distanceRGBA: { - - uniforms: { - lightPos: { value: new Vector3() } - }, + equals: function ( plane ) { - vertexShader: ShaderChunk.distanceRGBA_vert, - fragmentShader: ShaderChunk.distanceRGBA_frag + return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); } - }; - - ShaderLib.physical = { - - uniforms: UniformsUtils.merge( [ - ShaderLib.standard.uniforms, - { - clearCoat: { value: 0 }, - clearCoatRoughness: { value: 0 } - } - ] ), - - vertexShader: ShaderChunk.meshphysical_vert, - fragmentShader: ShaderChunk.meshphysical_frag - - }; + } ); /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ * @author bhouston / http://clara.io */ - function Box2( min, max ) { - - this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); - - } - - Object.assign( Box2.prototype, { - - set: function ( min, max ) { + function Frustum( p0, p1, p2, p3, p4, p5 ) { - this.min.copy( min ); - this.max.copy( max ); + this.planes = [ - return this; + ( p0 !== undefined ) ? p0 : new Plane(), + ( p1 !== undefined ) ? p1 : new Plane(), + ( p2 !== undefined ) ? p2 : new Plane(), + ( p3 !== undefined ) ? p3 : new Plane(), + ( p4 !== undefined ) ? p4 : new Plane(), + ( p5 !== undefined ) ? p5 : new Plane() - }, + ]; - setFromPoints: function ( points ) { + } - this.makeEmpty(); + Object.assign( Frustum.prototype, { - for ( var i = 0, il = points.length; i < il; i ++ ) { + set: function ( p0, p1, p2, p3, p4, p5 ) { - this.expandByPoint( points[ i ] ); + var planes = this.planes; - } + planes[ 0 ].copy( p0 ); + planes[ 1 ].copy( p1 ); + planes[ 2 ].copy( p2 ); + planes[ 3 ].copy( p3 ); + planes[ 4 ].copy( p4 ); + planes[ 5 ].copy( p5 ); return this; }, - setFromCenterAndSize: function () { - - var v1 = new Vector2(); - - return function setFromCenterAndSize( center, size ) { - - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); - - return this; - - }; - - }(), - clone: function () { return new this.constructor().copy( this ); }, - copy: function ( box ) { - - this.min.copy( box.min ); - this.max.copy( box.max ); - - return this; - - }, - - makeEmpty: function () { - - this.min.x = this.min.y = + Infinity; - this.max.x = this.max.y = - Infinity; - - return this; - - }, - - isEmpty: function () { - - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes - - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); - - }, - - getCenter: function ( optionalTarget ) { - - var result = optionalTarget || new Vector2(); - return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); - - }, - - getSize: function ( optionalTarget ) { + copy: function ( frustum ) { - var result = optionalTarget || new Vector2(); - return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min ); + var planes = this.planes; - }, + for ( var i = 0; i < 6; i ++ ) { - expandByPoint: function ( point ) { + planes[ i ].copy( frustum.planes[ i ] ); - this.min.min( point ); - this.max.max( point ); + } return this; }, - expandByVector: function ( vector ) { - - this.min.sub( vector ); - this.max.add( vector ); - - return this; - - }, + setFromMatrix: function ( m ) { - expandByScalar: function ( scalar ) { + var planes = this.planes; + var me = m.elements; + var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; + var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; + var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; + var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); + planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); + planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); + planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); + planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); + planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); return this; }, - containsPoint: function ( point ) { - - return point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y ? false : true; - - }, - - containsBox: function ( box ) { - - return this.min.x <= box.min.x && box.max.x <= this.max.x && - this.min.y <= box.min.y && box.max.y <= this.max.y; - - }, - - getParameter: function ( point, optionalTarget ) { - - // This can potentially have a divide by zero if the box - // has a size dimension of 0. - - var result = optionalTarget || new Vector2(); + intersectsObject: function () { - return result.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ) - ); + var sphere = new Sphere(); - }, + return function intersectsObject( object ) { - intersectsBox: function ( box ) { + var geometry = object.geometry; - // using 4 splitting planes to rule out intersections + if ( geometry.boundingSphere === null ) + geometry.computeBoundingSphere(); - return box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y ? false : true; + sphere.copy( geometry.boundingSphere ) + .applyMatrix4( object.matrixWorld ); - }, + return this.intersectsSphere( sphere ); - clampPoint: function ( point, optionalTarget ) { + }; - var result = optionalTarget || new Vector2(); - return result.copy( point ).clamp( this.min, this.max ); + }(), - }, + intersectsSprite: function () { - distanceToPoint: function () { + var sphere = new Sphere(); - var v1 = new Vector2(); + return function intersectsSprite( sprite ) { - return function distanceToPoint( point ) { + sphere.center.set( 0, 0, 0 ); + sphere.radius = 0.7071067811865476; + sphere.applyMatrix4( sprite.matrixWorld ); - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + return this.intersectsSphere( sphere ); }; }(), - intersect: function ( box ) { - - this.min.max( box.min ); - this.max.min( box.max ); - - return this; + intersectsSphere: function ( sphere ) { - }, + var planes = this.planes; + var center = sphere.center; + var negRadius = - sphere.radius; - union: function ( box ) { + for ( var i = 0; i < 6; i ++ ) { - this.min.min( box.min ); - this.max.max( box.max ); + var distance = planes[ i ].distanceToPoint( center ); - return this; + if ( distance < negRadius ) { - }, + return false; - translate: function ( offset ) { + } - this.min.add( offset ); - this.max.add( offset ); + } - return this; + return true; }, - equals: function ( box ) { - - return box.min.equals( this.min ) && box.max.equals( this.max ); - - } - - } ); - - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ - - function LensFlarePlugin( renderer, flares ) { - - var gl = renderer.context; - var state = renderer.state; - - var vertexBuffer, elementBuffer; - var shader, program, attributes, uniforms; - - var tempTexture, occlusionTexture; - - function init() { - - var vertices = new Float32Array( [ - - 1, - 1, 0, 0, - 1, - 1, 1, 0, - 1, 1, 1, 1, - - 1, 1, 0, 1 - ] ); - - var faces = new Uint16Array( [ - 0, 1, 2, - 0, 2, 3 - ] ); - - // buffers - - vertexBuffer = gl.createBuffer(); - elementBuffer = gl.createBuffer(); - - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); - - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); + intersectsBox: function () { - // textures + var p1 = new Vector3(), + p2 = new Vector3(); - tempTexture = gl.createTexture(); - occlusionTexture = gl.createTexture(); + return function intersectsBox( box ) { - state.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + var planes = this.planes; - state.bindTexture( gl.TEXTURE_2D, occlusionTexture ); - gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); - gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); + for ( var i = 0; i < 6; i ++ ) { - shader = { + var plane = planes[ i ]; - vertexShader: [ + p1.x = plane.normal.x > 0 ? box.min.x : box.max.x; + p2.x = plane.normal.x > 0 ? box.max.x : box.min.x; + p1.y = plane.normal.y > 0 ? box.min.y : box.max.y; + p2.y = plane.normal.y > 0 ? box.max.y : box.min.y; + p1.z = plane.normal.z > 0 ? box.min.z : box.max.z; + p2.z = plane.normal.z > 0 ? box.max.z : box.min.z; - "uniform lowp int renderType;", + var d1 = plane.distanceToPoint( p1 ); + var d2 = plane.distanceToPoint( p2 ); - "uniform vec3 screenPosition;", - "uniform vec2 scale;", - "uniform float rotation;", + // if both outside plane, no intersection - "uniform sampler2D occlusionMap;", + if ( d1 < 0 && d2 < 0 ) { - "attribute vec2 position;", - "attribute vec2 uv;", + return false; - "varying vec2 vUV;", - "varying float vVisibility;", + } - "void main() {", + } - "vUV = uv;", + return true; - "vec2 pos = position;", + }; - "if ( renderType == 2 ) {", + }(), - "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );", - "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );", + containsPoint: function ( point ) { - "vVisibility = visibility.r / 9.0;", - "vVisibility *= 1.0 - visibility.g / 9.0;", - "vVisibility *= visibility.b / 9.0;", - "vVisibility *= 1.0 - visibility.a / 9.0;", + var planes = this.planes; - "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;", - "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;", + for ( var i = 0; i < 6; i ++ ) { - "}", + if ( planes[ i ].distanceToPoint( point ) < 0 ) { - "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );", + return false; - "}" + } - ].join( "\n" ), + } - fragmentShader: [ + return true; - "uniform lowp int renderType;", + } - "uniform sampler2D map;", - "uniform float opacity;", - "uniform vec3 color;", + } ); - "varying vec2 vUV;", - "varying float vVisibility;", + var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n"; - "void main() {", + var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n"; - // pink square + var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n"; - "if ( renderType == 0 ) {", + var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n"; - "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );", + var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; - // restore + var begin_vertex = "\nvec3 transformed = vec3( position );\n"; - "} else if ( renderType == 1 ) {", + var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n"; - "gl_FragColor = texture2D( map, vUV );", + var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n"; - // flare + var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n"; - "} else {", + var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t#endif\n#endif\n"; - "vec4 texture = texture2D( map, vUV );", - "texture.a *= opacity * vVisibility;", - "gl_FragColor = texture;", - "gl_FragColor.rgb *= color;", + var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n"; - "}", + var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n"; - "}" + var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n"; - ].join( "\n" ) + var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif"; - }; + var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n"; - program = createProgram( shader ); + var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; - attributes = { - vertex: gl.getAttribLocation ( program, "position" ), - uv: gl.getAttribLocation ( program, "uv" ) - }; + var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif"; - uniforms = { - renderType: gl.getUniformLocation( program, "renderType" ), - map: gl.getUniformLocation( program, "map" ), - occlusionMap: gl.getUniformLocation( program, "occlusionMap" ), - opacity: gl.getUniformLocation( program, "opacity" ), - color: gl.getUniformLocation( program, "color" ), - scale: gl.getUniformLocation( program, "scale" ), - rotation: gl.getUniformLocation( program, "rotation" ), - screenPosition: gl.getUniformLocation( program, "screenPosition" ) - }; + var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\n"; - } + var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n"; - /* - * Render lens flares - * Method: renders 16x16 0xff00ff-colored points scattered over the light source area, - * reads these back and calculates occlusion. - */ + var defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n"; - this.render = function ( scene, camera, viewport ) { + var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n"; - if ( flares.length === 0 ) return; + var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n"; - var tempPosition = new Vector3(); + var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n"; - var invAspect = viewport.w / viewport.z, - halfViewportWidth = viewport.z * 0.5, - halfViewportHeight = viewport.w * 0.5; + var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n"; - var size = 16 / viewport.w, - scale = new Vector2( size * invAspect, size ); + var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n"; - var screenPosition = new Vector3( 1, 1, 0 ), - screenPositionPixels = new Vector2( 1, 1 ); + var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n\tXp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract(Le);\n\tvResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n"; - var validArea = new Box2(); + var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n"; - validArea.min.set( viewport.x, viewport.y ); - validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) ); + var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n"; - if ( program === undefined ) { + var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n"; - init(); + var envmap_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n"; - } + var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif"; - gl.useProgram( program ); + var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n"; - state.initAttributes(); - state.enableAttribute( attributes.vertex ); - state.enableAttribute( attributes.uv ); - state.disableUnusedAttributes(); + var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n"; - // loop through all lens flares to update their occlusion and positions - // setup gl and common used attribs/uniforms + var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif\n"; - gl.uniform1i( uniforms.occlusionMap, 0 ); - gl.uniform1i( uniforms.map, 1 ); + var gradientmap_pars_fragment = "#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif\n"; - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 ); - gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); + var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n"; - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; - state.disable( gl.CULL_FACE ); - state.buffers.depth.setMask( false ); + var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n"; - for ( var i = 0, l = flares.length; i < l; i ++ ) { + var lights_pars_begin = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n"; - size = 16 / viewport.w; - scale.set( size * invAspect, size ); + var lights_pars_maps = "#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n"; - // calc object screen position + var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n"; - var flare = flares[ i ]; + var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n"; - tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] ); + var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n"; - tempPosition.applyMatrix4( camera.matrixWorldInverse ); - tempPosition.applyMatrix4( camera.projectionMatrix ); + var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n"; - // setup arrays for gl programs + var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearCoatRadiance = vec3( 0.0 );\n#endif\n"; - screenPosition.copy( tempPosition ); + var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), maxMipLevel );\n\t#ifndef STANDARD\n\t\tclearCoatRadiance += getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), maxMipLevel );\n\t#endif\n#endif\n"; - // horizontal and vertical coordinate of the lower left corner of the pixels to copy + var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n"; - screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8; - screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8; + var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; - // screen cull + var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n"; - if ( validArea.containsPoint( screenPositionPixels ) === true ) { + var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif"; - // save current RGB to temp texture + var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\tgl_Position.z *= gl_Position.w;\n\t#endif\n#endif\n"; - state.activeTexture( gl.TEXTURE0 ); - state.bindTexture( gl.TEXTURE_2D, null ); - state.activeTexture( gl.TEXTURE1 ); - state.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 ); + var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n"; + var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n"; - // render pink quad + var map_particle_fragment = "#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n"; - gl.uniform1i( uniforms.renderType, 0 ); - gl.uniform2f( uniforms.scale, scale.x, scale.y ); - gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); + var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif\n"; - state.disable( gl.BLEND ); - state.enable( gl.DEPTH_TEST ); + var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n"; - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; + var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n"; - // copy result to occlusionMap + var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif"; - state.activeTexture( gl.TEXTURE0 ); - state.bindTexture( gl.TEXTURE_2D, occlusionTexture ); - gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 ); + var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n"; + var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n#endif\n"; - // restore graphics + var normal_fragment_maps = "#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n"; - gl.uniform1i( uniforms.renderType, 1 ); - state.disable( gl.DEPTH_TEST ); + var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n"; - state.activeTexture( gl.TEXTURE1 ); - state.bindTexture( gl.TEXTURE_2D, tempTexture ); - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n"; + var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n"; - // update object positions + var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n"; - flare.positionScreen.copy( screenPosition ); + var dithering_fragment = "#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n"; - if ( flare.customUpdateCallback ) { + var dithering_pars_fragment = "#if defined( DITHERING )\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif\n"; - flare.customUpdateCallback( flare ); + var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n"; - } else { + var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; - flare.updateLensFlares(); + var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n"; - } + var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n"; - // render flares + var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n"; - gl.uniform1i( uniforms.renderType, 2 ); - state.enable( gl.BLEND ); + var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n"; - for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) { + var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; - var sprite = flare.lensFlares[ j ]; + var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n"; - if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) { + var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif\n"; - screenPosition.x = sprite.x; - screenPosition.y = sprite.y; - screenPosition.z = sprite.z; + var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n"; - size = sprite.size * sprite.scale / viewport.w; + var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif"; - scale.x = size * invAspect; - scale.y = size; + var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; - gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z ); - gl.uniform2f( uniforms.scale, scale.x, scale.y ); - gl.uniform1f( uniforms.rotation, sprite.rotation ); + var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n"; - gl.uniform1f( uniforms.opacity, sprite.opacity ); - gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b ); + var tonemapping_pars_fragment = "#ifndef saturate\n\t#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n"; - state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst ); - renderer.setTexture2D( sprite.texture, 1 ); + var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif"; - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\n"; - } + var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif"; - } + var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif"; - } + var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif"; - } + var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif"; - // restore gl + var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n"; - state.enable( gl.CULL_FACE ); - state.enable( gl.DEPTH_TEST ); - state.buffers.depth.setMask( true ); + var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n"; - renderer.resetGLState(); + var cube_vert = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}\n"; - }; + var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n"; - function createProgram( shader ) { + var depth_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - var program = gl.createProgram(); + var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}\n"; - var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); - var vertexShader = gl.createShader( gl.VERTEX_SHADER ); + var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}\n"; - var prefix = "precision " + renderer.getPrecision() + " float;\n"; + var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n"; - gl.shaderSource( fragmentShader, prefix + shader.fragmentShader ); - gl.shaderSource( vertexShader, prefix + shader.vertexShader ); + var equirect_vert = "varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n"; - gl.compileShader( fragmentShader ); - gl.compileShader( vertexShader ); + var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - gl.attachShader( program, fragmentShader ); - gl.attachShader( program, vertexShader ); + var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}\n"; - gl.linkProgram( program ); + var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - return program; + var meshbasic_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - } + var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - } + var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - function SpritePlugin( renderer, sprites ) { + var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - var gl = renderer.context; - var state = renderer.state; + var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - var vertexBuffer, elementBuffer; - var program, attributes, uniforms; + var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}\n"; - var texture; + var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n"; - // decompose matrixWorld + var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n"; - var spritePosition = new Vector3(); - var spriteRotation = new Quaternion(); - var spriteScale = new Vector3(); + var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - function init() { + var points_vert = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - var vertices = new Float32Array( [ - - 0.5, - 0.5, 0, 0, - 0.5, - 0.5, 1, 0, - 0.5, 0.5, 1, 1, - - 0.5, 0.5, 0, 1 - ] ); + var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n}\n"; - var faces = new Uint16Array( [ - 0, 1, 2, - 0, 2, 3 - ] ); + var shadow_vert = "#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"; - vertexBuffer = gl.createBuffer(); - elementBuffer = gl.createBuffer(); + var ShaderChunk = { + alphamap_fragment: alphamap_fragment, + alphamap_pars_fragment: alphamap_pars_fragment, + alphatest_fragment: alphatest_fragment, + aomap_fragment: aomap_fragment, + aomap_pars_fragment: aomap_pars_fragment, + begin_vertex: begin_vertex, + beginnormal_vertex: beginnormal_vertex, + bsdfs: bsdfs, + bumpmap_pars_fragment: bumpmap_pars_fragment, + clipping_planes_fragment: clipping_planes_fragment, + clipping_planes_pars_fragment: clipping_planes_pars_fragment, + clipping_planes_pars_vertex: clipping_planes_pars_vertex, + clipping_planes_vertex: clipping_planes_vertex, + color_fragment: color_fragment, + color_pars_fragment: color_pars_fragment, + color_pars_vertex: color_pars_vertex, + color_vertex: color_vertex, + common: common, + cube_uv_reflection_fragment: cube_uv_reflection_fragment, + defaultnormal_vertex: defaultnormal_vertex, + displacementmap_pars_vertex: displacementmap_pars_vertex, + displacementmap_vertex: displacementmap_vertex, + emissivemap_fragment: emissivemap_fragment, + emissivemap_pars_fragment: emissivemap_pars_fragment, + encodings_fragment: encodings_fragment, + encodings_pars_fragment: encodings_pars_fragment, + envmap_fragment: envmap_fragment, + envmap_pars_fragment: envmap_pars_fragment, + envmap_pars_vertex: envmap_pars_vertex, + envmap_vertex: envmap_vertex, + fog_vertex: fog_vertex, + fog_pars_vertex: fog_pars_vertex, + fog_fragment: fog_fragment, + fog_pars_fragment: fog_pars_fragment, + gradientmap_pars_fragment: gradientmap_pars_fragment, + lightmap_fragment: lightmap_fragment, + lightmap_pars_fragment: lightmap_pars_fragment, + lights_lambert_vertex: lights_lambert_vertex, + lights_pars_begin: lights_pars_begin, + lights_pars_maps: lights_pars_maps, + lights_phong_fragment: lights_phong_fragment, + lights_phong_pars_fragment: lights_phong_pars_fragment, + lights_physical_fragment: lights_physical_fragment, + lights_physical_pars_fragment: lights_physical_pars_fragment, + lights_fragment_begin: lights_fragment_begin, + lights_fragment_maps: lights_fragment_maps, + lights_fragment_end: lights_fragment_end, + logdepthbuf_fragment: logdepthbuf_fragment, + logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, + logdepthbuf_vertex: logdepthbuf_vertex, + map_fragment: map_fragment, + map_pars_fragment: map_pars_fragment, + map_particle_fragment: map_particle_fragment, + map_particle_pars_fragment: map_particle_pars_fragment, + metalnessmap_fragment: metalnessmap_fragment, + metalnessmap_pars_fragment: metalnessmap_pars_fragment, + morphnormal_vertex: morphnormal_vertex, + morphtarget_pars_vertex: morphtarget_pars_vertex, + morphtarget_vertex: morphtarget_vertex, + normal_fragment_begin: normal_fragment_begin, + normal_fragment_maps: normal_fragment_maps, + normalmap_pars_fragment: normalmap_pars_fragment, + packing: packing, + premultiplied_alpha_fragment: premultiplied_alpha_fragment, + project_vertex: project_vertex, + dithering_fragment: dithering_fragment, + dithering_pars_fragment: dithering_pars_fragment, + roughnessmap_fragment: roughnessmap_fragment, + roughnessmap_pars_fragment: roughnessmap_pars_fragment, + shadowmap_pars_fragment: shadowmap_pars_fragment, + shadowmap_pars_vertex: shadowmap_pars_vertex, + shadowmap_vertex: shadowmap_vertex, + shadowmask_pars_fragment: shadowmask_pars_fragment, + skinbase_vertex: skinbase_vertex, + skinning_pars_vertex: skinning_pars_vertex, + skinning_vertex: skinning_vertex, + skinnormal_vertex: skinnormal_vertex, + specularmap_fragment: specularmap_fragment, + specularmap_pars_fragment: specularmap_pars_fragment, + tonemapping_fragment: tonemapping_fragment, + tonemapping_pars_fragment: tonemapping_pars_fragment, + uv_pars_fragment: uv_pars_fragment, + uv_pars_vertex: uv_pars_vertex, + uv_vertex: uv_vertex, + uv2_pars_fragment: uv2_pars_fragment, + uv2_pars_vertex: uv2_pars_vertex, + uv2_vertex: uv2_vertex, + worldpos_vertex: worldpos_vertex, - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); + cube_frag: cube_frag, + cube_vert: cube_vert, + depth_frag: depth_frag, + depth_vert: depth_vert, + distanceRGBA_frag: distanceRGBA_frag, + distanceRGBA_vert: distanceRGBA_vert, + equirect_frag: equirect_frag, + equirect_vert: equirect_vert, + linedashed_frag: linedashed_frag, + linedashed_vert: linedashed_vert, + meshbasic_frag: meshbasic_frag, + meshbasic_vert: meshbasic_vert, + meshlambert_frag: meshlambert_frag, + meshlambert_vert: meshlambert_vert, + meshphong_frag: meshphong_frag, + meshphong_vert: meshphong_vert, + meshphysical_frag: meshphysical_frag, + meshphysical_vert: meshphysical_vert, + normal_frag: normal_frag, + normal_vert: normal_vert, + points_frag: points_frag, + points_vert: points_vert, + shadow_frag: shadow_frag, + shadow_vert: shadow_vert + }; - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); - gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); + /** + * Uniform Utilities + */ - program = createProgram(); + var UniformsUtils = { - attributes = { - position: gl.getAttribLocation ( program, 'position' ), - uv: gl.getAttribLocation ( program, 'uv' ) - }; + merge: function ( uniforms ) { - uniforms = { - uvOffset: gl.getUniformLocation( program, 'uvOffset' ), - uvScale: gl.getUniformLocation( program, 'uvScale' ), + var merged = {}; - rotation: gl.getUniformLocation( program, 'rotation' ), - scale: gl.getUniformLocation( program, 'scale' ), + for ( var u = 0; u < uniforms.length; u ++ ) { - color: gl.getUniformLocation( program, 'color' ), - map: gl.getUniformLocation( program, 'map' ), - opacity: gl.getUniformLocation( program, 'opacity' ), + var tmp = this.clone( uniforms[ u ] ); - modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ), - projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ), + for ( var p in tmp ) { - fogType: gl.getUniformLocation( program, 'fogType' ), - fogDensity: gl.getUniformLocation( program, 'fogDensity' ), - fogNear: gl.getUniformLocation( program, 'fogNear' ), - fogFar: gl.getUniformLocation( program, 'fogFar' ), - fogColor: gl.getUniformLocation( program, 'fogColor' ), + merged[ p ] = tmp[ p ]; - alphaTest: gl.getUniformLocation( program, 'alphaTest' ) - }; + } - var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = 8; - canvas.height = 8; + } - var context = canvas.getContext( '2d' ); - context.fillStyle = 'white'; - context.fillRect( 0, 0, 8, 8 ); + return merged; - texture = new Texture( canvas ); - texture.needsUpdate = true; + }, - } + clone: function ( uniforms_src ) { - this.render = function ( scene, camera ) { + var uniforms_dst = {}; - if ( sprites.length === 0 ) return; + for ( var u in uniforms_src ) { - // setup gl + uniforms_dst[ u ] = {}; - if ( program === undefined ) { + for ( var p in uniforms_src[ u ] ) { - init(); + var parameter_src = uniforms_src[ u ][ p ]; - } + if ( parameter_src && ( parameter_src.isColor || + parameter_src.isMatrix3 || parameter_src.isMatrix4 || + parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 || + parameter_src.isTexture ) ) { - gl.useProgram( program ); + uniforms_dst[ u ][ p ] = parameter_src.clone(); - state.initAttributes(); - state.enableAttribute( attributes.position ); - state.enableAttribute( attributes.uv ); - state.disableUnusedAttributes(); + } else if ( Array.isArray( parameter_src ) ) { - state.disable( gl.CULL_FACE ); - state.enable( gl.BLEND ); + uniforms_dst[ u ][ p ] = parameter_src.slice(); - gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); - gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 ); - gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); + } else { - gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + uniforms_dst[ u ][ p ] = parameter_src; - gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); + } - state.activeTexture( gl.TEXTURE0 ); - gl.uniform1i( uniforms.map, 0 ); + } - var oldFogType = 0; - var sceneFogType = 0; - var fog = scene.fog; + } - if ( fog ) { + return uniforms_dst; - gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); + } - if ( fog.isFog ) { + }; - gl.uniform1f( uniforms.fogNear, fog.near ); - gl.uniform1f( uniforms.fogFar, fog.far ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - gl.uniform1i( uniforms.fogType, 1 ); - oldFogType = 1; - sceneFogType = 1; + var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, + 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, + 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, + 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, + 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, + 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, + 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, + 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, + 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, + 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, + 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, + 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, + 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, + 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, + 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, + 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, + 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, + 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, + 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, + 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, + 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, + 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, + 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, + 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; - } else if ( fog.isFogExp2 ) { + function Color( r, g, b ) { - gl.uniform1f( uniforms.fogDensity, fog.density ); + if ( g === undefined && b === undefined ) { - gl.uniform1i( uniforms.fogType, 2 ); - oldFogType = 2; - sceneFogType = 2; + // r is THREE.Color, hex or string + return this.set( r ); - } + } - } else { + return this.setRGB( r, g, b ); - gl.uniform1i( uniforms.fogType, 0 ); - oldFogType = 0; - sceneFogType = 0; + } - } + Object.assign( Color.prototype, { + isColor: true, - // update positions and sort + r: 1, g: 1, b: 1, - for ( var i = 0, l = sprites.length; i < l; i ++ ) { + set: function ( value ) { - var sprite = sprites[ i ]; + if ( value && value.isColor ) { - sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); - sprite.z = - sprite.modelViewMatrix.elements[ 14 ]; + this.copy( value ); - } + } else if ( typeof value === 'number' ) { - sprites.sort( painterSortStable ); + this.setHex( value ); - // render all sprites + } else if ( typeof value === 'string' ) { - var scale = []; + this.setStyle( value ); - for ( var i = 0, l = sprites.length; i < l; i ++ ) { + } - var sprite = sprites[ i ]; - var material = sprite.material; + return this; - if ( material.visible === false ) continue; + }, - sprite.onBeforeRender( renderer, scene, camera, undefined, material, undefined ); + setScalar: function ( scalar ) { - gl.uniform1f( uniforms.alphaTest, material.alphaTest ); - gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements ); + this.r = scalar; + this.g = scalar; + this.b = scalar; - sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale ); + return this; - scale[ 0 ] = spriteScale.x; - scale[ 1 ] = spriteScale.y; + }, - var fogType = 0; + setHex: function ( hex ) { - if ( scene.fog && material.fog ) { + hex = Math.floor( hex ); - fogType = sceneFogType; + this.r = ( hex >> 16 & 255 ) / 255; + this.g = ( hex >> 8 & 255 ) / 255; + this.b = ( hex & 255 ) / 255; - } + return this; - if ( oldFogType !== fogType ) { + }, - gl.uniform1i( uniforms.fogType, fogType ); - oldFogType = fogType; + setRGB: function ( r, g, b ) { - } + this.r = r; + this.g = g; + this.b = b; - if ( material.map !== null ) { + return this; - gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y ); - gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y ); + }, - } else { + setHSL: function () { - gl.uniform2f( uniforms.uvOffset, 0, 0 ); - gl.uniform2f( uniforms.uvScale, 1, 1 ); + function hue2rgb( p, q, t ) { - } + if ( t < 0 ) t += 1; + if ( t > 1 ) t -= 1; + if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t; + if ( t < 1 / 2 ) return q; + if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t ); + return p; - gl.uniform1f( uniforms.opacity, material.opacity ); - gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b ); + } - gl.uniform1f( uniforms.rotation, material.rotation ); - gl.uniform2fv( uniforms.scale, scale ); + return function setHSL( h, s, l ) { - state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); - state.buffers.depth.setTest( material.depthTest ); - state.buffers.depth.setMask( material.depthWrite ); + // h,s,l ranges are in 0.0 - 1.0 + h = _Math.euclideanModulo( h, 1 ); + s = _Math.clamp( s, 0, 1 ); + l = _Math.clamp( l, 0, 1 ); - if ( material.map ) { + if ( s === 0 ) { - renderer.setTexture2D( material.map, 0 ); + this.r = this.g = this.b = l; } else { - renderer.setTexture2D( texture, 0 ); + var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); + var q = ( 2 * l ) - p; - } + this.r = hue2rgb( q, p, h + 1 / 3 ); + this.g = hue2rgb( q, p, h ); + this.b = hue2rgb( q, p, h - 1 / 3 ); - gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + } - sprite.onAfterRender( renderer, scene, camera, undefined, material, undefined ); + return this; - } + }; - // restore gl + }(), - state.enable( gl.CULL_FACE ); + setStyle: function ( style ) { - renderer.resetGLState(); + function handleAlpha( string ) { - }; + if ( string === undefined ) return; - function createProgram() { + if ( parseFloat( string ) < 1 ) { - var program = gl.createProgram(); + console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); - var vertexShader = gl.createShader( gl.VERTEX_SHADER ); - var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); + } - gl.shaderSource( vertexShader, [ + } - 'precision ' + renderer.getPrecision() + ' float;', - '#define SHADER_NAME ' + 'SpriteMaterial', + var m; - 'uniform mat4 modelViewMatrix;', - 'uniform mat4 projectionMatrix;', - 'uniform float rotation;', - 'uniform vec2 scale;', - 'uniform vec2 uvOffset;', - 'uniform vec2 uvScale;', + if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { - 'attribute vec2 position;', - 'attribute vec2 uv;', + // rgb / hsl - 'varying vec2 vUV;', + var color; + var name = m[ 1 ]; + var components = m[ 2 ]; - 'void main() {', + switch ( name ) { - 'vUV = uvOffset + uv * uvScale;', + case 'rgb': + case 'rgba': - 'vec2 alignedPosition = position * scale;', + if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - 'vec2 rotatedPosition;', - 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;', - 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;', + // rgb(255,0,0) rgba(255,0,0,0.5) + this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; + this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; + this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; - 'vec4 finalPosition;', + handleAlpha( color[ 5 ] ); - 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );', - 'finalPosition.xy += rotatedPosition;', - 'finalPosition = projectionMatrix * finalPosition;', + return this; - 'gl_Position = finalPosition;', + } - '}' + if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - ].join( '\n' ) ); + // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) + this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; + this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; + this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; - gl.shaderSource( fragmentShader, [ + handleAlpha( color[ 5 ] ); - 'precision ' + renderer.getPrecision() + ' float;', + return this; - '#define SHADER_NAME ' + 'SpriteMaterial', + } - 'uniform vec3 color;', - 'uniform sampler2D map;', - 'uniform float opacity;', + break; - 'uniform int fogType;', - 'uniform vec3 fogColor;', - 'uniform float fogDensity;', - 'uniform float fogNear;', - 'uniform float fogFar;', - 'uniform float alphaTest;', + case 'hsl': + case 'hsla': - 'varying vec2 vUV;', + if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { - 'void main() {', + // hsl(120,50%,50%) hsla(120,50%,50%,0.5) + var h = parseFloat( color[ 1 ] ) / 360; + var s = parseInt( color[ 2 ], 10 ) / 100; + var l = parseInt( color[ 3 ], 10 ) / 100; - 'vec4 texture = texture2D( map, vUV );', + handleAlpha( color[ 5 ] ); - 'if ( texture.a < alphaTest ) discard;', + return this.setHSL( h, s, l ); - 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );', + } - 'if ( fogType > 0 ) {', + break; - 'float depth = gl_FragCoord.z / gl_FragCoord.w;', - 'float fogFactor = 0.0;', + } - 'if ( fogType == 1 ) {', + } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { - 'fogFactor = smoothstep( fogNear, fogFar, depth );', + // hex color - '} else {', + var hex = m[ 1 ]; + var size = hex.length; - 'const float LOG2 = 1.442695;', - 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );', - 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );', + if ( size === 3 ) { - '}', + // #ff0 + this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255; + this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255; + this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255; - 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );', + return this; - '}', + } else if ( size === 6 ) { - '}' + // #ff0000 + this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255; + this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255; + this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255; - ].join( '\n' ) ); + return this; - gl.compileShader( vertexShader ); - gl.compileShader( fragmentShader ); + } - gl.attachShader( program, vertexShader ); - gl.attachShader( program, fragmentShader ); + } - gl.linkProgram( program ); + if ( style && style.length > 0 ) { - return program; + // color keywords + var hex = ColorKeywords[ style ]; - } + if ( hex !== undefined ) { - function painterSortStable( a, b ) { + // red + this.setHex( hex ); - if ( a.renderOrder !== b.renderOrder ) { + } else { - return a.renderOrder - b.renderOrder; + // unknown color + console.warn( 'THREE.Color: Unknown color ' + style ); - } else if ( a.z !== b.z ) { + } - return b.z - a.z; + } - } else { + return this; - return b.id - a.id; + }, - } + clone: function () { - } + return new this.constructor( this.r, this.g, this.b ); - } + }, - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + copy: function ( color ) { - var materialId = 0; + this.r = color.r; + this.g = color.g; + this.b = color.b; - function Material() { + return this; - Object.defineProperty( this, 'id', { value: materialId ++ } ); + }, - this.uuid = _Math.generateUUID(); + copyGammaToLinear: function ( color, gammaFactor ) { - this.name = ''; - this.type = 'Material'; + if ( gammaFactor === undefined ) gammaFactor = 2.0; - this.fog = true; - this.lights = true; + this.r = Math.pow( color.r, gammaFactor ); + this.g = Math.pow( color.g, gammaFactor ); + this.b = Math.pow( color.b, gammaFactor ); - this.blending = NormalBlending; - this.side = FrontSide; - this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading - this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors + return this; - this.opacity = 1; - this.transparent = false; + }, - this.blendSrc = SrcAlphaFactor; - this.blendDst = OneMinusSrcAlphaFactor; - this.blendEquation = AddEquation; - this.blendSrcAlpha = null; - this.blendDstAlpha = null; - this.blendEquationAlpha = null; + copyLinearToGamma: function ( color, gammaFactor ) { - this.depthFunc = LessEqualDepth; - this.depthTest = true; - this.depthWrite = true; + if ( gammaFactor === undefined ) gammaFactor = 2.0; - this.clippingPlanes = null; - this.clipIntersection = false; - this.clipShadows = false; + var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; - this.colorWrite = true; + this.r = Math.pow( color.r, safeInverse ); + this.g = Math.pow( color.g, safeInverse ); + this.b = Math.pow( color.b, safeInverse ); - this.precision = null; // override the renderer's default precision for this material + return this; - this.polygonOffset = false; - this.polygonOffsetFactor = 0; - this.polygonOffsetUnits = 0; + }, - this.dithering = false; + convertGammaToLinear: function () { - this.alphaTest = 0; - this.premultipliedAlpha = false; + var r = this.r, g = this.g, b = this.b; - this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer + this.r = r * r; + this.g = g * g; + this.b = b * b; - this.visible = true; + return this; - this.needsUpdate = true; + }, - } + convertLinearToGamma: function () { - Object.assign( Material.prototype, EventDispatcher.prototype, { + this.r = Math.sqrt( this.r ); + this.g = Math.sqrt( this.g ); + this.b = Math.sqrt( this.b ); - isMaterial: true, + return this; - onBeforeCompile: function () {}, + }, - setValues: function ( values ) { + getHex: function () { - if ( values === undefined ) return; + return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; - for ( var key in values ) { + }, - var newValue = values[ key ]; + getHexString: function () { - if ( newValue === undefined ) { + return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); - console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); - continue; + }, - } + getHSL: function ( target ) { - var currentValue = this[ key ]; + // h,s,l ranges are in 0.0 - 1.0 - if ( currentValue === undefined ) { + if ( target === undefined ) { - console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); - continue; + console.warn( 'THREE.Color: .getHSL() target is now required' ); + target = { h: 0, s: 0, l: 0 }; - } + } - if ( currentValue && currentValue.isColor ) { + var r = this.r, g = this.g, b = this.b; - currentValue.set( newValue ); + var max = Math.max( r, g, b ); + var min = Math.min( r, g, b ); - } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) { + var hue, saturation; + var lightness = ( min + max ) / 2.0; - currentValue.copy( newValue ); + if ( min === max ) { - } else if ( key === 'overdraw' ) { + hue = 0; + saturation = 0; - // ensure overdraw is backwards-compatible with legacy boolean type - this[ key ] = Number( newValue ); + } else { - } else { + var delta = max - min; - this[ key ] = newValue; + saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); + + switch ( max ) { + + case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; + case g: hue = ( b - r ) / delta + 2; break; + case b: hue = ( r - g ) / delta + 4; break; } + hue /= 6; + } + target.h = hue; + target.s = saturation; + target.l = lightness; + + return target; + }, - toJSON: function ( meta ) { + getStyle: function () { - var isRoot = meta === undefined; + return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; - if ( isRoot ) { + }, - meta = { - textures: {}, - images: {} - }; + offsetHSL: function () { - } + var hsl = {}; - var data = { - metadata: { - version: 4.5, - type: 'Material', - generator: 'Material.toJSON' - } - }; + return function ( h, s, l ) { - // standard Material serialization - data.uuid = this.uuid; - data.type = this.type; + this.getHSL( hsl ); - if ( this.name !== '' ) data.name = this.name; + hsl.h += h; hsl.s += s; hsl.l += l; - if ( this.color && this.color.isColor ) data.color = this.color.getHex(); + this.setHSL( hsl.h, hsl.s, hsl.l ); - if ( this.roughness !== undefined ) data.roughness = this.roughness; - if ( this.metalness !== undefined ) data.metalness = this.metalness; + return this; - if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); - if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); - if ( this.shininess !== undefined ) data.shininess = this.shininess; - if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat; - if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness; + }; - if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid; - if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; - if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid; - if ( this.bumpMap && this.bumpMap.isTexture ) { + }(), - data.bumpMap = this.bumpMap.toJSON( meta ).uuid; - data.bumpScale = this.bumpScale; + add: function ( color ) { - } - if ( this.normalMap && this.normalMap.isTexture ) { + this.r += color.r; + this.g += color.g; + this.b += color.b; - data.normalMap = this.normalMap.toJSON( meta ).uuid; - data.normalScale = this.normalScale.toArray(); + return this; - } - if ( this.displacementMap && this.displacementMap.isTexture ) { + }, - data.displacementMap = this.displacementMap.toJSON( meta ).uuid; - data.displacementScale = this.displacementScale; - data.displacementBias = this.displacementBias; + addColors: function ( color1, color2 ) { - } - if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; - if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; - if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; - if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid; + return this; - if ( this.envMap && this.envMap.isTexture ) { + }, - data.envMap = this.envMap.toJSON( meta ).uuid; - data.reflectivity = this.reflectivity; // Scale behind envMap + addScalar: function ( s ) { - } + this.r += s; + this.g += s; + this.b += s; - if ( this.gradientMap && this.gradientMap.isTexture ) { + return this; - data.gradientMap = this.gradientMap.toJSON( meta ).uuid; + }, - } + sub: function ( color ) { - if ( this.size !== undefined ) data.size = this.size; - if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; + this.r = Math.max( 0, this.r - color.r ); + this.g = Math.max( 0, this.g - color.g ); + this.b = Math.max( 0, this.b - color.b ); - if ( this.blending !== NormalBlending ) data.blending = this.blending; - if ( this.shading !== SmoothShading ) data.shading = this.shading; - if ( this.side !== FrontSide ) data.side = this.side; - if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors; + return this; - if ( this.opacity < 1 ) data.opacity = this.opacity; - if ( this.transparent === true ) data.transparent = this.transparent; + }, - data.depthFunc = this.depthFunc; - data.depthTest = this.depthTest; - data.depthWrite = this.depthWrite; + multiply: function ( color ) { - if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; - if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; - if ( this.wireframe === true ) data.wireframe = this.wireframe; - if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; - if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap; - if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin; + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; - data.skinning = this.skinning; - data.morphTargets = this.morphTargets; + return this; - data.dithering = this.dithering; + }, - // TODO: Copied from Object3D.toJSON + multiplyScalar: function ( s ) { - function extractFromCache( cache ) { + this.r *= s; + this.g *= s; + this.b *= s; - var values = []; + return this; - for ( var key in cache ) { + }, - var data = cache[ key ]; - delete data.metadata; - values.push( data ); + lerp: function ( color, alpha ) { - } + this.r += ( color.r - this.r ) * alpha; + this.g += ( color.g - this.g ) * alpha; + this.b += ( color.b - this.b ) * alpha; - return values; + return this; - } + }, - if ( isRoot ) { + equals: function ( c ) { - var textures = extractFromCache( meta.textures ); - var images = extractFromCache( meta.images ); + return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); - if ( textures.length > 0 ) data.textures = textures; - if ( images.length > 0 ) data.images = images; + }, - } + fromArray: function ( array, offset ) { - return data; + if ( offset === undefined ) offset = 0; + + this.r = array[ offset ]; + this.g = array[ offset + 1 ]; + this.b = array[ offset + 2 ]; + + return this; }, - clone: function () { + toArray: function ( array, offset ) { - return new this.constructor().copy( this ); + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; + + array[ offset ] = this.r; + array[ offset + 1 ] = this.g; + array[ offset + 2 ] = this.b; + + return array; }, - copy: function ( source ) { + toJSON: function () { - this.name = source.name; + return this.getHex(); - this.fog = source.fog; - this.lights = source.lights; + } - this.blending = source.blending; - this.side = source.side; - this.shading = source.shading; - this.vertexColors = source.vertexColors; + } ); - this.opacity = source.opacity; - this.transparent = source.transparent; + /** + * Uniforms library for shared webgl shaders + */ - this.blendSrc = source.blendSrc; - this.blendDst = source.blendDst; - this.blendEquation = source.blendEquation; - this.blendSrcAlpha = source.blendSrcAlpha; - this.blendDstAlpha = source.blendDstAlpha; - this.blendEquationAlpha = source.blendEquationAlpha; + var UniformsLib = { - this.depthFunc = source.depthFunc; - this.depthTest = source.depthTest; - this.depthWrite = source.depthWrite; + common: { - this.colorWrite = source.colorWrite; + diffuse: { value: new Color( 0xeeeeee ) }, + opacity: { value: 1.0 }, - this.precision = source.precision; + map: { value: null }, + uvTransform: { value: new Matrix3() }, - this.polygonOffset = source.polygonOffset; - this.polygonOffsetFactor = source.polygonOffsetFactor; - this.polygonOffsetUnits = source.polygonOffsetUnits; + alphaMap: { value: null }, - this.dithering = source.dithering; + }, - this.alphaTest = source.alphaTest; + specularmap: { - this.premultipliedAlpha = source.premultipliedAlpha; + specularMap: { value: null }, - this.overdraw = source.overdraw; + }, - this.visible = source.visible; - this.clipShadows = source.clipShadows; - this.clipIntersection = source.clipIntersection; + envmap: { - var srcPlanes = source.clippingPlanes, - dstPlanes = null; + envMap: { value: null }, + flipEnvMap: { value: - 1 }, + reflectivity: { value: 1.0 }, + refractionRatio: { value: 0.98 }, + maxMipLevel: { value: 0 } - if ( srcPlanes !== null ) { + }, - var n = srcPlanes.length; - dstPlanes = new Array( n ); + aomap: { - for ( var i = 0; i !== n; ++ i ) - dstPlanes[ i ] = srcPlanes[ i ].clone(); + aoMap: { value: null }, + aoMapIntensity: { value: 1 } - } + }, - this.clippingPlanes = dstPlanes; + lightmap: { - return this; + lightMap: { value: null }, + lightMapIntensity: { value: 1 } }, - dispose: function () { - - this.dispatchEvent( { type: 'dispose' } ); + emissivemap: { - } + emissiveMap: { value: null } - } ); + }, - /** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * defines: { "label" : "value" }, - * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } }, - * - * fragmentShader: , - * vertexShader: , - * - * wireframe: , - * wireframeLinewidth: , - * - * lights: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + bumpmap: { - function ShaderMaterial( parameters ) { + bumpMap: { value: null }, + bumpScale: { value: 1 } - Material.call( this ); + }, - this.type = 'ShaderMaterial'; + normalmap: { - this.defines = {}; - this.uniforms = {}; + normalMap: { value: null }, + normalScale: { value: new Vector2( 1, 1 ) } - this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}'; - this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}'; + }, - this.linewidth = 1; + displacementmap: { - this.wireframe = false; - this.wireframeLinewidth = 1; + displacementMap: { value: null }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } - this.fog = false; // set to use scene fog - this.lights = false; // set to use scene lights - this.clipping = false; // set to use user-defined clipping planes + }, - this.skinning = false; // set to use skinning attribute streams - this.morphTargets = false; // set to use morph targets - this.morphNormals = false; // set to use morph normals + roughnessmap: { - this.extensions = { - derivatives: false, // set to use derivatives - fragDepth: false, // set to use fragment depth values - drawBuffers: false, // set to use draw buffers - shaderTextureLOD: false // set to use shader texture LOD - }; + roughnessMap: { value: null } - // When rendered geometry doesn't include these attributes but the material does, - // use these default values in WebGL. This avoids errors when buffer data is missing. - this.defaultAttributeValues = { - 'color': [ 1, 1, 1 ], - 'uv': [ 0, 0 ], - 'uv2': [ 0, 0 ] - }; + }, - this.index0AttributeName = undefined; + metalnessmap: { - if ( parameters !== undefined ) { + metalnessMap: { value: null } - if ( parameters.attributes !== undefined ) { + }, - console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); + gradientmap: { - } + gradientMap: { value: null } - this.setValues( parameters ); + }, - } + fog: { - } + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: new Color( 0xffffff ) } - ShaderMaterial.prototype = Object.create( Material.prototype ); - ShaderMaterial.prototype.constructor = ShaderMaterial; + }, - ShaderMaterial.prototype.isShaderMaterial = true; + lights: { - ShaderMaterial.prototype.copy = function ( source ) { + ambientLightColor: { value: [] }, - Material.prototype.copy.call( this, source ); + directionalLights: { value: [], properties: { + direction: {}, + color: {}, - this.fragmentShader = source.fragmentShader; - this.vertexShader = source.vertexShader; + shadow: {}, + shadowBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, - this.uniforms = UniformsUtils.clone( source.uniforms ); + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, - this.defines = source.defines; + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {}, - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + shadow: {}, + shadowBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, - this.lights = source.lights; - this.clipping = source.clipping; + spotShadowMap: { value: [] }, + spotShadowMatrix: { value: [] }, - this.skinning = source.skinning; + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {}, - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + shadow: {}, + shadowBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, - this.extensions = source.extensions; + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, - return this; + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, - }; + // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } } - ShaderMaterial.prototype.toJSON = function ( meta ) { + }, - var data = Material.prototype.toJSON.call( this, meta ); + points: { - data.uniforms = this.uniforms; - data.vertexShader = this.vertexShader; - data.fragmentShader = this.fragmentShader; + diffuse: { value: new Color( 0xeeeeee ) }, + opacity: { value: 1.0 }, + size: { value: 1.0 }, + scale: { value: 1.0 }, + map: { value: null }, + uvTransform: { value: new Matrix3() } - return data; + } }; /** - * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ - * @author bhouston / https://clara.io - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * - * opacity: , - * - * map: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * wireframe: , - * wireframeLinewidth: - * } + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ */ - function MeshDepthMaterial( parameters ) { + var ShaderLib = { - Material.call( this ); + basic: { - this.type = 'MeshDepthMaterial'; + uniforms: UniformsUtils.merge( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.fog + ] ), - this.depthPacking = BasicDepthPacking; - - this.skinning = false; - this.morphTargets = false; + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag - this.map = null; + }, - this.alphaMap = null; + lambert: { - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + uniforms: UniformsUtils.merge( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: new Color( 0x000000 ) } + } + ] ), - this.wireframe = false; - this.wireframeLinewidth = 1; + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag - this.fog = false; - this.lights = false; + }, - this.setValues( parameters ); + phong: { - } + uniforms: UniformsUtils.merge( [ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.gradientmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: new Color( 0x000000 ) }, + specular: { value: new Color( 0x111111 ) }, + shininess: { value: 30 } + } + ] ), - MeshDepthMaterial.prototype = Object.create( Material.prototype ); - MeshDepthMaterial.prototype.constructor = MeshDepthMaterial; + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag - MeshDepthMaterial.prototype.isMeshDepthMaterial = true; + }, - MeshDepthMaterial.prototype.copy = function ( source ) { + standard: { - Material.prototype.copy.call( this, source ); + uniforms: UniformsUtils.merge( [ + UniformsLib.common, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: new Color( 0x000000 ) }, + roughness: { value: 0.5 }, + metalness: { value: 0.5 }, + envMapIntensity: { value: 1 } // temporary + } + ] ), - this.depthPacking = source.depthPacking; + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; + }, - this.map = source.map; + points: { - this.alphaMap = source.alphaMap; + uniforms: UniformsUtils.merge( [ + UniformsLib.points, + UniformsLib.fog + ] ), - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + }, - return this; + dashed: { - }; + uniforms: UniformsUtils.merge( [ + UniformsLib.common, + UniformsLib.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ] ), - /** - * @author bhouston / http://clara.io - * @author WestLangley / http://github.com/WestLangley - */ + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag - function Box3( min, max ) { + }, - this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity ); - this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity ); + depth: { - } + uniforms: UniformsUtils.merge( [ + UniformsLib.common, + UniformsLib.displacementmap + ] ), - Object.assign( Box3.prototype, { + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag - isBox3: true, + }, - set: function ( min, max ) { + normal: { - this.min.copy( min ); - this.max.copy( max ); + uniforms: UniformsUtils.merge( [ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + { + opacity: { value: 1.0 } + } + ] ), - return this; + vertexShader: ShaderChunk.normal_vert, + fragmentShader: ShaderChunk.normal_frag }, - setFromArray: function ( array ) { - - var minX = + Infinity; - var minY = + Infinity; - var minZ = + Infinity; - - var maxX = - Infinity; - var maxY = - Infinity; - var maxZ = - Infinity; + /* ------------------------------------------------------------------------- + // Cube map shader + ------------------------------------------------------------------------- */ - for ( var i = 0, l = array.length; i < l; i += 3 ) { + cube: { - var x = array[ i ]; - var y = array[ i + 1 ]; - var z = array[ i + 2 ]; + uniforms: { + tCube: { value: null }, + tFlip: { value: - 1 }, + opacity: { value: 1.0 } + }, - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( z < minZ ) minZ = z; + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; - if ( z > maxZ ) maxZ = z; + }, - } + equirect: { - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); + uniforms: { + tEquirect: { value: null }, + }, - return this; + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag }, - setFromBufferAttribute: function ( attribute ) { - - var minX = + Infinity; - var minY = + Infinity; - var minZ = + Infinity; + distanceRGBA: { - var maxX = - Infinity; - var maxY = - Infinity; - var maxZ = - Infinity; + uniforms: UniformsUtils.merge( [ + UniformsLib.common, + UniformsLib.displacementmap, + { + referencePosition: { value: new Vector3() }, + nearDistance: { value: 1 }, + farDistance: { value: 1000 } + } + ] ), - for ( var i = 0, l = attribute.count; i < l; i ++ ) { + vertexShader: ShaderChunk.distanceRGBA_vert, + fragmentShader: ShaderChunk.distanceRGBA_frag - var x = attribute.getX( i ); - var y = attribute.getY( i ); - var z = attribute.getZ( i ); + }, - if ( x < minX ) minX = x; - if ( y < minY ) minY = y; - if ( z < minZ ) minZ = z; + shadow: { - if ( x > maxX ) maxX = x; - if ( y > maxY ) maxY = y; - if ( z > maxZ ) maxZ = z; + uniforms: UniformsUtils.merge( [ + UniformsLib.lights, + UniformsLib.fog, + { + color: { value: new Color( 0x00000 ) }, + opacity: { value: 1.0 } + }, + ] ), - } + vertexShader: ShaderChunk.shadow_vert, + fragmentShader: ShaderChunk.shadow_frag - this.min.set( minX, minY, minZ ); - this.max.set( maxX, maxY, maxZ ); + } - return this; + }; - }, + ShaderLib.physical = { - setFromPoints: function ( points ) { + uniforms: UniformsUtils.merge( [ + ShaderLib.standard.uniforms, + { + clearCoat: { value: 0 }, + clearCoatRoughness: { value: 0 } + } + ] ), - this.makeEmpty(); + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag - for ( var i = 0, il = points.length; i < il; i ++ ) { + }; - this.expandByPoint( points[ i ] ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function WebGLAttributes( gl ) { - return this; + var buffers = new WeakMap(); - }, + function createBuffer( attribute, bufferType ) { - setFromCenterAndSize: function () { + var array = attribute.array; + var usage = attribute.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; - var v1 = new Vector3(); + var buffer = gl.createBuffer(); - return function setFromCenterAndSize( center, size ) { + gl.bindBuffer( bufferType, buffer ); + gl.bufferData( bufferType, array, usage ); - var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + attribute.onUploadCallback(); - this.min.copy( center ).sub( halfSize ); - this.max.copy( center ).add( halfSize ); + var type = gl.FLOAT; - return this; + if ( array instanceof Float32Array ) { - }; + type = gl.FLOAT; - }(), + } else if ( array instanceof Float64Array ) { - setFromObject: function ( object ) { + console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' ); - this.makeEmpty(); + } else if ( array instanceof Uint16Array ) { - return this.expandByObject( object ); + type = gl.UNSIGNED_SHORT; - }, + } else if ( array instanceof Int16Array ) { - clone: function () { + type = gl.SHORT; - return new this.constructor().copy( this ); + } else if ( array instanceof Uint32Array ) { - }, + type = gl.UNSIGNED_INT; - copy: function ( box ) { + } else if ( array instanceof Int32Array ) { - this.min.copy( box.min ); - this.max.copy( box.max ); + type = gl.INT; - return this; + } else if ( array instanceof Int8Array ) { - }, + type = gl.BYTE; - makeEmpty: function () { + } else if ( array instanceof Uint8Array ) { - this.min.x = this.min.y = this.min.z = + Infinity; - this.max.x = this.max.y = this.max.z = - Infinity; + type = gl.UNSIGNED_BYTE; - return this; + } - }, + return { + buffer: buffer, + type: type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version + }; - isEmpty: function () { + } - // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + function updateBuffer( buffer, attribute, bufferType ) { - return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); + var array = attribute.array; + var updateRange = attribute.updateRange; - }, + gl.bindBuffer( bufferType, buffer ); - getCenter: function ( optionalTarget ) { + if ( attribute.dynamic === false ) { - var result = optionalTarget || new Vector3(); - return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + gl.bufferData( bufferType, array, gl.STATIC_DRAW ); - }, + } else if ( updateRange.count === - 1 ) { - getSize: function ( optionalTarget ) { + // Not using update ranges - var result = optionalTarget || new Vector3(); - return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min ); + gl.bufferSubData( bufferType, 0, array ); - }, + } else if ( updateRange.count === 0 ) { - expandByPoint: function ( point ) { + console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' ); - this.min.min( point ); - this.max.max( point ); + } else { - return this; + gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, + array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) ); - }, + updateRange.count = - 1; // reset range - expandByVector: function ( vector ) { + } - this.min.sub( vector ); - this.max.add( vector ); + } - return this; + // - }, + function get( attribute ) { - expandByScalar: function ( scalar ) { + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; - this.min.addScalar( - scalar ); - this.max.addScalar( scalar ); + return buffers.get( attribute ); - return this; + } - }, + function remove( attribute ) { - expandByObject: function () { + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; - // Computes the world-axis-aligned bounding box of an object (including its children), - // accounting for both the object's, and children's, world transforms + var data = buffers.get( attribute ); - var v1 = new Vector3(); + if ( data ) { - return function expandByObject( object ) { + gl.deleteBuffer( data.buffer ); - var scope = this; + buffers.delete( attribute ); - object.updateMatrixWorld( true ); + } - object.traverse( function ( node ) { + } - var i, l; + function update( attribute, bufferType ) { - var geometry = node.geometry; + if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; - if ( geometry !== undefined ) { + var data = buffers.get( attribute ); - if ( geometry.isGeometry ) { + if ( data === undefined ) { - var vertices = geometry.vertices; + buffers.set( attribute, createBuffer( attribute, bufferType ) ); - for ( i = 0, l = vertices.length; i < l; i ++ ) { + } else if ( data.version < attribute.version ) { - v1.copy( vertices[ i ] ); - v1.applyMatrix4( node.matrixWorld ); + updateBuffer( data.buffer, attribute, bufferType ); - scope.expandByPoint( v1 ); + data.version = attribute.version; - } + } - } else if ( geometry.isBufferGeometry ) { + } - var attribute = geometry.attributes.position; + return { - if ( attribute !== undefined ) { + get: get, + remove: remove, + update: update - for ( i = 0, l = attribute.count; i < l; i ++ ) { + }; - v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld ); + } - scope.expandByPoint( v1 ); + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://clara.io + */ - } + function Euler( x, y, z, order ) { - } + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._order = order || Euler.DefaultOrder; - } + } - } + Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; - } ); + Euler.DefaultOrder = 'XYZ'; - return this; + Object.defineProperties( Euler.prototype, { - }; + x: { - }(), + get: function () { - containsPoint: function ( point ) { + return this._x; - return point.x < this.min.x || point.x > this.max.x || - point.y < this.min.y || point.y > this.max.y || - point.z < this.min.z || point.z > this.max.z ? false : true; + }, - }, + set: function ( value ) { - containsBox: function ( box ) { + this._x = value; + this.onChangeCallback(); - return this.min.x <= box.min.x && box.max.x <= this.max.x && - this.min.y <= box.min.y && box.max.y <= this.max.y && - this.min.z <= box.min.z && box.max.z <= this.max.z; + } }, - getParameter: function ( point, optionalTarget ) { + y: { - // This can potentially have a divide by zero if the box - // has a size dimension of 0. + get: function () { - var result = optionalTarget || new Vector3(); + return this._y; - return result.set( - ( point.x - this.min.x ) / ( this.max.x - this.min.x ), - ( point.y - this.min.y ) / ( this.max.y - this.min.y ), - ( point.z - this.min.z ) / ( this.max.z - this.min.z ) - ); + }, - }, + set: function ( value ) { - intersectsBox: function ( box ) { + this._y = value; + this.onChangeCallback(); - // using 6 splitting planes to rule out intersections. - return box.max.x < this.min.x || box.min.x > this.max.x || - box.max.y < this.min.y || box.min.y > this.max.y || - box.max.z < this.min.z || box.min.z > this.max.z ? false : true; + } }, - intersectsSphere: ( function () { + z: { - var closestPoint = new Vector3(); + get: function () { - return function intersectsSphere( sphere ) { + return this._z; - // Find the point on the AABB closest to the sphere center. - this.clampPoint( sphere.center, closestPoint ); + }, - // If that point is inside the sphere, the AABB and sphere intersect. - return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); + set: function ( value ) { - }; + this._z = value; + this.onChangeCallback(); - } )(), + } - intersectsPlane: function ( plane ) { + }, - // We compute the minimum and maximum dot product values. If those values - // are on the same side (back or front) of the plane, then there is no intersection. + order: { - var min, max; + get: function () { - if ( plane.normal.x > 0 ) { + return this._order; - min = plane.normal.x * this.min.x; - max = plane.normal.x * this.max.x; + }, - } else { + set: function ( value ) { - min = plane.normal.x * this.max.x; - max = plane.normal.x * this.min.x; + this._order = value; + this.onChangeCallback(); } - if ( plane.normal.y > 0 ) { + } - min += plane.normal.y * this.min.y; - max += plane.normal.y * this.max.y; + } ); - } else { + Object.assign( Euler.prototype, { - min += plane.normal.y * this.max.y; - max += plane.normal.y * this.min.y; + isEuler: true, - } + set: function ( x, y, z, order ) { - if ( plane.normal.z > 0 ) { + this._x = x; + this._y = y; + this._z = z; + this._order = order || this._order; - min += plane.normal.z * this.min.z; - max += plane.normal.z * this.max.z; + this.onChangeCallback(); - } else { + return this; - min += plane.normal.z * this.max.z; - max += plane.normal.z * this.min.z; + }, - } + clone: function () { - return ( min <= plane.constant && max >= plane.constant ); + return new this.constructor( this._x, this._y, this._z, this._order ); }, - clampPoint: function ( point, optionalTarget ) { + copy: function ( euler ) { - var result = optionalTarget || new Vector3(); - return result.copy( point ).clamp( this.min, this.max ); + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; - }, + this.onChangeCallback(); - distanceToPoint: function () { + return this; - var v1 = new Vector3(); + }, - return function distanceToPoint( point ) { + setFromRotationMatrix: function ( m, order, update ) { - var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); - return clampedPoint.sub( point ).length(); + var clamp = _Math.clamp; - }; + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - }(), + var te = m.elements; + var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; + var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; + var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; - getBoundingSphere: function () { + order = order || this._order; - var v1 = new Vector3(); + if ( order === 'XYZ' ) { - return function getBoundingSphere( optionalTarget ) { + this._y = Math.asin( clamp( m13, - 1, 1 ) ); - var result = optionalTarget || new Sphere(); + if ( Math.abs( m13 ) < 0.99999 ) { - this.getCenter( result.center ); + this._x = Math.atan2( - m23, m33 ); + this._z = Math.atan2( - m12, m11 ); - result.radius = this.getSize( v1 ).length() * 0.5; + } else { - return result; + this._x = Math.atan2( m32, m22 ); + this._z = 0; - }; + } - }(), + } else if ( order === 'YXZ' ) { - intersect: function ( box ) { + this._x = Math.asin( - clamp( m23, - 1, 1 ) ); - this.min.max( box.min ); - this.max.min( box.max ); + if ( Math.abs( m23 ) < 0.99999 ) { - // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. - if( this.isEmpty() ) this.makeEmpty(); + this._y = Math.atan2( m13, m33 ); + this._z = Math.atan2( m21, m22 ); - return this; + } else { - }, + this._y = Math.atan2( - m31, m11 ); + this._z = 0; - union: function ( box ) { + } - this.min.min( box.min ); - this.max.max( box.max ); + } else if ( order === 'ZXY' ) { - return this; + this._x = Math.asin( clamp( m32, - 1, 1 ) ); - }, + if ( Math.abs( m32 ) < 0.99999 ) { - applyMatrix4: function () { + this._y = Math.atan2( - m31, m33 ); + this._z = Math.atan2( - m12, m22 ); - var points = [ - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3(), - new Vector3() - ]; + } else { - return function applyMatrix4( matrix ) { + this._y = 0; + this._z = Math.atan2( m21, m11 ); - // transform of empty box is an empty box. - if( this.isEmpty() ) return this; + } - // NOTE: I am using a binary pattern to specify all 2^3 combinations below - points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 - points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 - points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 - points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 - points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 - points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 - points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 - points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 + } else if ( order === 'ZYX' ) { - this.setFromPoints( points ); + this._y = Math.asin( - clamp( m31, - 1, 1 ) ); - return this; + if ( Math.abs( m31 ) < 0.99999 ) { - }; + this._x = Math.atan2( m32, m33 ); + this._z = Math.atan2( m21, m11 ); - }(), + } else { - translate: function ( offset ) { + this._x = 0; + this._z = Math.atan2( - m12, m22 ); - this.min.add( offset ); - this.max.add( offset ); + } - return this; + } else if ( order === 'YZX' ) { - }, + this._z = Math.asin( clamp( m21, - 1, 1 ) ); - equals: function ( box ) { + if ( Math.abs( m21 ) < 0.99999 ) { - return box.min.equals( this.min ) && box.max.equals( this.max ); + this._x = Math.atan2( - m23, m22 ); + this._y = Math.atan2( - m31, m11 ); - } + } else { - } ); + this._x = 0; + this._y = Math.atan2( m13, m33 ); - /** - * @author bhouston / http://clara.io - * @author mrdoob / http://mrdoob.com/ - */ + } - function Sphere( center, radius ) { + } else if ( order === 'XZY' ) { - this.center = ( center !== undefined ) ? center : new Vector3(); - this.radius = ( radius !== undefined ) ? radius : 0; + this._z = Math.asin( - clamp( m12, - 1, 1 ) ); - } + if ( Math.abs( m12 ) < 0.99999 ) { - Object.assign( Sphere.prototype, { + this._x = Math.atan2( m32, m22 ); + this._y = Math.atan2( m13, m11 ); - set: function ( center, radius ) { + } else { - this.center.copy( center ); - this.radius = radius; + this._x = Math.atan2( - m23, m33 ); + this._y = 0; + + } + + } else { + + console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ); + + } + + this._order = order; + + if ( update !== false ) this.onChangeCallback(); return this; }, - setFromPoints: function () { + setFromQuaternion: function () { - var box = new Box3(); + var matrix = new Matrix4(); - return function setFromPoints( points, optionalCenter ) { + return function setFromQuaternion( q, order, update ) { - var center = this.center; + matrix.makeRotationFromQuaternion( q ); - if ( optionalCenter !== undefined ) { + return this.setFromRotationMatrix( matrix, order, update ); - center.copy( optionalCenter ); + }; - } else { + }(), - box.setFromPoints( points ).getCenter( center ); + setFromVector3: function ( v, order ) { - } + return this.set( v.x, v.y, v.z, order || this._order ); - var maxRadiusSq = 0; + }, - for ( var i = 0, il = points.length; i < il; i ++ ) { + reorder: function () { - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); + // WARNING: this discards revolution information -bhouston - } + var q = new Quaternion(); - this.radius = Math.sqrt( maxRadiusSq ); + return function reorder( newOrder ) { - return this; + q.setFromEuler( this ); + + return this.setFromQuaternion( q, newOrder ); }; }(), - clone: function () { + equals: function ( euler ) { - return new this.constructor().copy( this ); + return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); }, - copy: function ( sphere ) { - - this.center.copy( sphere.center ); - this.radius = sphere.radius; - - return this; + fromArray: function ( array ) { - }, + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; - empty: function () { + this.onChangeCallback(); - return ( this.radius <= 0 ); + return this; }, - containsPoint: function ( point ) { - - return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); + toArray: function ( array, offset ) { - }, + if ( array === undefined ) array = []; + if ( offset === undefined ) offset = 0; - distanceToPoint: function ( point ) { + array[ offset ] = this._x; + array[ offset + 1 ] = this._y; + array[ offset + 2 ] = this._z; + array[ offset + 3 ] = this._order; - return ( point.distanceTo( this.center ) - this.radius ); + return array; }, - intersectsSphere: function ( sphere ) { + toVector3: function ( optionalResult ) { - var radiusSum = this.radius + sphere.radius; + if ( optionalResult ) { - return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); + return optionalResult.set( this._x, this._y, this._z ); - }, + } else { - intersectsBox: function ( box ) { + return new Vector3( this._x, this._y, this._z ); - return box.intersectsSphere( this ); + } }, - intersectsPlane: function ( plane ) { + onChange: function ( callback ) { - // We use the following equation to compute the signed distance from - // the center of the sphere to the plane. - // - // distance = q * n - d - // - // If this distance is greater than the radius of the sphere, - // then there is no intersection. + this.onChangeCallback = callback; - return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius; + return this; }, - clampPoint: function ( point, optionalTarget ) { - - var deltaLengthSq = this.center.distanceToSquared( point ); + onChangeCallback: function () {} - var result = optionalTarget || new Vector3(); + } ); - result.copy( point ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( deltaLengthSq > ( this.radius * this.radius ) ) { + function Layers() { - result.sub( this.center ).normalize(); - result.multiplyScalar( this.radius ).add( this.center ); + this.mask = 1 | 0; - } + } - return result; + Object.assign( Layers.prototype, { - }, + set: function ( channel ) { - getBoundingBox: function ( optionalTarget ) { + this.mask = 1 << channel | 0; - var box = optionalTarget || new Box3(); + }, - box.set( this.center, this.center ); - box.expandByScalar( this.radius ); + enable: function ( channel ) { - return box; + this.mask |= 1 << channel | 0; }, - applyMatrix4: function ( matrix ) { - - this.center.applyMatrix4( matrix ); - this.radius = this.radius * matrix.getMaxScaleOnAxis(); + toggle: function ( channel ) { - return this; + this.mask ^= 1 << channel | 0; }, - translate: function ( offset ) { - - this.center.add( offset ); + disable: function ( channel ) { - return this; + this.mask &= ~ ( 1 << channel | 0 ); }, - equals: function ( sphere ) { + test: function ( layers ) { - return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); + return ( this.mask & layers.mask ) !== 0; } } ); /** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - * @author tschw + * @author elephantatwork / www.elephantatwork.ch */ - function Matrix3() { + var object3DId = 0; - this.elements = [ + function Object3D() { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + Object.defineProperty( this, 'id', { value: object3DId ++ } ); - ]; + this.uuid = _Math.generateUUID(); - if ( arguments.length > 0 ) { + this.name = ''; + this.type = 'Object3D'; - console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); + this.parent = null; + this.children = []; - } + this.up = Object3D.DefaultUp.clone(); - } + var position = new Vector3(); + var rotation = new Euler(); + var quaternion = new Quaternion(); + var scale = new Vector3( 1, 1, 1 ); - Object.assign( Matrix3.prototype, { + function onRotationChange() { - isMatrix3: true, + quaternion.setFromEuler( rotation, false ); - set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { + } - var te = this.elements; + function onQuaternionChange() { - te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; - te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; - te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; + rotation.setFromQuaternion( quaternion, undefined, false ); - return this; + } - }, + rotation.onChange( onRotationChange ); + quaternion.onChange( onQuaternionChange ); - identity: function () { + Object.defineProperties( this, { + position: { + enumerable: true, + value: position + }, + rotation: { + enumerable: true, + value: rotation + }, + quaternion: { + enumerable: true, + value: quaternion + }, + scale: { + enumerable: true, + value: scale + }, + modelViewMatrix: { + value: new Matrix4() + }, + normalMatrix: { + value: new Matrix3() + } + } ); - this.set( + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 + this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; + this.matrixWorldNeedsUpdate = false; - ); + this.layers = new Layers(); + this.visible = true; - return this; + this.castShadow = false; + this.receiveShadow = false; - }, + this.frustumCulled = true; + this.renderOrder = 0; - clone: function () { + this.userData = {}; - return new this.constructor().fromArray( this.elements ); + } - }, + Object3D.DefaultUp = new Vector3( 0, 1, 0 ); + Object3D.DefaultMatrixAutoUpdate = true; - copy: function ( m ) { + Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { - var te = this.elements; - var me = m.elements; + constructor: Object3D, - te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; - te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; - te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; + isObject3D: true, - return this; + onBeforeRender: function () {}, + onAfterRender: function () {}, - }, + applyMatrix: function ( matrix ) { - setFromMatrix4: function ( m ) { + this.matrix.multiplyMatrices( matrix, this.matrix ); - var me = m.elements; + this.matrix.decompose( this.position, this.quaternion, this.scale ); - this.set( + }, - me[ 0 ], me[ 4 ], me[ 8 ], - me[ 1 ], me[ 5 ], me[ 9 ], - me[ 2 ], me[ 6 ], me[ 10 ] + applyQuaternion: function ( q ) { - ); + this.quaternion.premultiply( q ); return this; }, - applyToBufferAttribute: function () { + setRotationFromAxisAngle: function ( axis, angle ) { - var v1 = new Vector3(); + // assumes axis is normalized - return function applyToBufferAttribute( attribute ) { + this.quaternion.setFromAxisAngle( axis, angle ); - for ( var i = 0, l = attribute.count; i < l; i ++ ) { + }, - v1.x = attribute.getX( i ); - v1.y = attribute.getY( i ); - v1.z = attribute.getZ( i ); + setRotationFromEuler: function ( euler ) { - v1.applyMatrix3( this ); + this.quaternion.setFromEuler( euler, true ); - attribute.setXYZ( i, v1.x, v1.y, v1.z ); + }, - } + setRotationFromMatrix: function ( m ) { - return attribute; + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - }; + this.quaternion.setFromRotationMatrix( m ); - }(), + }, - multiply: function ( m ) { + setRotationFromQuaternion: function ( q ) { - return this.multiplyMatrices( this, m ); + // assumes q is normalized + + this.quaternion.copy( q ); }, - premultiply: function ( m ) { + rotateOnAxis: function () { - return this.multiplyMatrices( m, this ); + // rotate object on axis in object space + // axis is assumed to be normalized - }, + var q1 = new Quaternion(); - multiplyMatrices: function ( a, b ) { + return function rotateOnAxis( axis, angle ) { - var ae = a.elements; - var be = b.elements; - var te = this.elements; + q1.setFromAxisAngle( axis, angle ); - var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ]; - var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ]; - var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ]; + this.quaternion.multiply( q1 ); - var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ]; - var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ]; - var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ]; + return this; - te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31; - te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32; - te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33; + }; - te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31; - te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32; - te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33; + }(), - te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31; - te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32; - te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33; + rotateOnWorldAxis: function () { - return this; + // rotate object on axis in world space + // axis is assumed to be normalized + // method assumes no rotated parent - }, + var q1 = new Quaternion(); - multiplyScalar: function ( s ) { + return function rotateOnWorldAxis( axis, angle ) { - var te = this.elements; + q1.setFromAxisAngle( axis, angle ); - te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; - te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; - te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; + this.quaternion.premultiply( q1 ); - return this; + return this; - }, + }; - determinant: function () { + }(), - var te = this.elements; + rotateX: function () { - var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], - d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], - g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; + var v1 = new Vector3( 1, 0, 0 ); - return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + return function rotateX( angle ) { - }, + return this.rotateOnAxis( v1, angle ); - getInverse: function ( matrix, throwOnDegenerate ) { + }; - if ( matrix && matrix.isMatrix4 ) { + }(), - console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." ); + rotateY: function () { - } + var v1 = new Vector3( 0, 1, 0 ); - var me = matrix.elements, - te = this.elements, + return function rotateY( angle ) { - n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], - n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ], - n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ], + return this.rotateOnAxis( v1, angle ); - t11 = n33 * n22 - n32 * n23, - t12 = n32 * n13 - n33 * n12, - t13 = n23 * n12 - n22 * n13, + }; - det = n11 * t11 + n21 * t12 + n31 * t13; + }(), - if ( det === 0 ) { + rotateZ: function () { - var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0"; + var v1 = new Vector3( 0, 0, 1 ); - if ( throwOnDegenerate === true ) { + return function rotateZ( angle ) { - throw new Error( msg ); + return this.rotateOnAxis( v1, angle ); - } else { + }; - console.warn( msg ); + }(), - } + translateOnAxis: function () { - return this.identity(); + // translate object by distance along axis in object space + // axis is assumed to be normalized - } + var v1 = new Vector3(); - var detInv = 1 / det; + return function translateOnAxis( axis, distance ) { - te[ 0 ] = t11 * detInv; - te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; - te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; + v1.copy( axis ).applyQuaternion( this.quaternion ); - te[ 3 ] = t12 * detInv; - te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; - te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; + this.position.add( v1.multiplyScalar( distance ) ); - te[ 6 ] = t13 * detInv; - te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; - te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; + return this; - return this; + }; - }, + }(), - transpose: function () { + translateX: function () { - var tmp, m = this.elements; + var v1 = new Vector3( 1, 0, 0 ); - tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; - tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; - tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; + return function translateX( distance ) { - return this; + return this.translateOnAxis( v1, distance ); - }, + }; - getNormalMatrix: function ( matrix4 ) { + }(), - return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose(); + translateY: function () { - }, + var v1 = new Vector3( 0, 1, 0 ); - transposeIntoArray: function ( r ) { + return function translateY( distance ) { - var m = this.elements; + return this.translateOnAxis( v1, distance ); - r[ 0 ] = m[ 0 ]; - r[ 1 ] = m[ 3 ]; - r[ 2 ] = m[ 6 ]; - r[ 3 ] = m[ 1 ]; - r[ 4 ] = m[ 4 ]; - r[ 5 ] = m[ 7 ]; - r[ 6 ] = m[ 2 ]; - r[ 7 ] = m[ 5 ]; - r[ 8 ] = m[ 8 ]; + }; - return this; + }(), - }, + translateZ: function () { - equals: function ( matrix ) { + var v1 = new Vector3( 0, 0, 1 ); - var te = this.elements; - var me = matrix.elements; + return function translateZ( distance ) { - for ( var i = 0; i < 9; i ++ ) { + return this.translateOnAxis( v1, distance ); - if ( te[ i ] !== me[ i ] ) return false; + }; - } + }(), - return true; + localToWorld: function ( vector ) { - }, + return vector.applyMatrix4( this.matrixWorld ); - fromArray: function ( array, offset ) { + }, - if ( offset === undefined ) offset = 0; + worldToLocal: function () { - for ( var i = 0; i < 9; i ++ ) { + var m1 = new Matrix4(); - this.elements[ i ] = array[ i + offset ]; + return function worldToLocal( vector ) { - } + return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); - return this; + }; - }, + }(), - toArray: function ( array, offset ) { + lookAt: function () { - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + // This method does not support objects with rotated and/or translated parent(s) - var te = this.elements; + var m1 = new Matrix4(); + var vector = new Vector3(); - array[ offset ] = te[ 0 ]; - array[ offset + 1 ] = te[ 1 ]; - array[ offset + 2 ] = te[ 2 ]; + return function lookAt( x, y, z ) { - array[ offset + 3 ] = te[ 3 ]; - array[ offset + 4 ] = te[ 4 ]; - array[ offset + 5 ] = te[ 5 ]; + if ( x.isVector3 ) { - array[ offset + 6 ] = te[ 6 ]; - array[ offset + 7 ] = te[ 7 ]; - array[ offset + 8 ] = te[ 8 ]; + vector.copy( x ); - return array; + } else { - } + vector.set( x, y, z ); - } ); + } - /** - * @author bhouston / http://clara.io - */ + if ( this.isCamera ) { - function Plane( normal, constant ) { + m1.lookAt( this.position, vector, this.up ); - this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 ); - this.constant = ( constant !== undefined ) ? constant : 0; + } else { - } + m1.lookAt( vector, this.position, this.up ); - Object.assign( Plane.prototype, { + } - set: function ( normal, constant ) { + this.quaternion.setFromRotationMatrix( m1 ); - this.normal.copy( normal ); - this.constant = constant; + }; - return this; + }(), - }, + add: function ( object ) { - setComponents: function ( x, y, z, w ) { + if ( arguments.length > 1 ) { - this.normal.set( x, y, z ); - this.constant = w; + for ( var i = 0; i < arguments.length; i ++ ) { - return this; + this.add( arguments[ i ] ); - }, + } - setFromNormalAndCoplanarPoint: function ( normal, point ) { + return this; - this.normal.copy( normal ); - this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized + } - return this; + if ( object === this ) { - }, + console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); + return this; - setFromCoplanarPoints: function () { + } - var v1 = new Vector3(); - var v2 = new Vector3(); + if ( ( object && object.isObject3D ) ) { - return function setFromCoplanarPoints( a, b, c ) { + if ( object.parent !== null ) { - var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize(); + object.parent.remove( object ); - // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? + } - this.setFromNormalAndCoplanarPoint( normal, a ); + object.parent = this; + object.dispatchEvent( { type: 'added' } ); - return this; + this.children.push( object ); - }; + } else { - }(), + console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); - clone: function () { + } - return new this.constructor().copy( this ); + return this; }, - copy: function ( plane ) { + remove: function ( object ) { - this.normal.copy( plane.normal ); - this.constant = plane.constant; + if ( arguments.length > 1 ) { - return this; + for ( var i = 0; i < arguments.length; i ++ ) { - }, + this.remove( arguments[ i ] ); - normalize: function () { + } - // Note: will lead to a divide by zero if the plane is invalid. + return this; - var inverseNormalLength = 1.0 / this.normal.length(); - this.normal.multiplyScalar( inverseNormalLength ); - this.constant *= inverseNormalLength; + } - return this; + var index = this.children.indexOf( object ); - }, + if ( index !== - 1 ) { - negate: function () { + object.parent = null; - this.constant *= - 1; - this.normal.negate(); + object.dispatchEvent( { type: 'removed' } ); + + this.children.splice( index, 1 ); + + } return this; }, - distanceToPoint: function ( point ) { + getObjectById: function ( id ) { - return this.normal.dot( point ) + this.constant; + return this.getObjectByProperty( 'id', id ); }, - distanceToSphere: function ( sphere ) { + getObjectByName: function ( name ) { - return this.distanceToPoint( sphere.center ) - sphere.radius; + return this.getObjectByProperty( 'name', name ); }, - projectPoint: function ( point, optionalTarget ) { + getObjectByProperty: function ( name, value ) { - return this.orthoPoint( point, optionalTarget ).sub( point ).negate(); + if ( this[ name ] === value ) return this; - }, + for ( var i = 0, l = this.children.length; i < l; i ++ ) { - orthoPoint: function ( point, optionalTarget ) { + var child = this.children[ i ]; + var object = child.getObjectByProperty( name, value ); - var perpendicularMagnitude = this.distanceToPoint( point ); + if ( object !== undefined ) { - var result = optionalTarget || new Vector3(); - return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude ); + return object; - }, + } - intersectLine: function () { + } - var v1 = new Vector3(); + return undefined; - return function intersectLine( line, optionalTarget ) { + }, - var result = optionalTarget || new Vector3(); + getWorldPosition: function ( target ) { - var direction = line.delta( v1 ); + if ( target === undefined ) { - var denominator = this.normal.dot( direction ); + console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' ); + target = new Vector3(); - if ( denominator === 0 ) { + } - // line is coplanar, return origin - if ( this.distanceToPoint( line.start ) === 0 ) { + this.updateMatrixWorld( true ); - return result.copy( line.start ); + return target.setFromMatrixPosition( this.matrixWorld ); - } + }, - // Unsure if this is the correct method to handle this case. - return undefined; + getWorldQuaternion: function () { - } + var position = new Vector3(); + var scale = new Vector3(); - var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; + return function getWorldQuaternion( target ) { - if ( t < 0 || t > 1 ) { + if ( target === undefined ) { - return undefined; + console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' ); + target = new Quaternion(); } - return result.copy( direction ).multiplyScalar( t ).add( line.start ); + this.updateMatrixWorld( true ); - }; + this.matrixWorld.decompose( position, target, scale ); - }(), + return target; - intersectsLine: function ( line ) { + }; - // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. + }(), - var startSign = this.distanceToPoint( line.start ); - var endSign = this.distanceToPoint( line.end ); + getWorldScale: function () { - return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); + var position = new Vector3(); + var quaternion = new Quaternion(); - }, + return function getWorldScale( target ) { - intersectsBox: function ( box ) { + if ( target === undefined ) { - return box.intersectsPlane( this ); + console.warn( 'THREE.Object3D: .getWorldScale() target is now required' ); + target = new Vector3(); - }, + } - intersectsSphere: function ( sphere ) { + this.updateMatrixWorld( true ); - return sphere.intersectsPlane( this ); + this.matrixWorld.decompose( position, quaternion, target ); - }, + return target; - coplanarPoint: function ( optionalTarget ) { + }; - var result = optionalTarget || new Vector3(); - return result.copy( this.normal ).multiplyScalar( - this.constant ); + }(), - }, + getWorldDirection: function () { - applyMatrix4: function () { + var quaternion = new Quaternion(); - var v1 = new Vector3(); - var m1 = new Matrix3(); + return function getWorldDirection( target ) { - return function applyMatrix4( matrix, optionalNormalMatrix ) { + if ( target === undefined ) { - var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix ); + console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' ); + target = new Vector3(); - // transform normal based on theory here: - // http://www.songho.ca/opengl/gl_normaltransform.html - var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix ); - var normal = this.normal.applyMatrix3( normalMatrix ).normalize(); + } - // recalculate constant (like in setFromNormalAndCoplanarPoint) - this.constant = - referencePoint.dot( normal ); + this.getWorldQuaternion( quaternion ); - return this; + return target.set( 0, 0, 1 ).applyQuaternion( quaternion ); }; }(), - translate: function ( offset ) { + raycast: function () {}, - this.constant = this.constant - offset.dot( this.normal ); + traverse: function ( callback ) { - return this; + callback( this ); - }, + var children = this.children; - equals: function ( plane ) { + for ( var i = 0, l = children.length; i < l; i ++ ) { - return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); + children[ i ].traverse( callback ); - } + } - } ); + }, - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author bhouston / http://clara.io - */ + traverseVisible: function ( callback ) { - function Frustum( p0, p1, p2, p3, p4, p5 ) { + if ( this.visible === false ) return; - this.planes = [ + callback( this ); - ( p0 !== undefined ) ? p0 : new Plane(), - ( p1 !== undefined ) ? p1 : new Plane(), - ( p2 !== undefined ) ? p2 : new Plane(), - ( p3 !== undefined ) ? p3 : new Plane(), - ( p4 !== undefined ) ? p4 : new Plane(), - ( p5 !== undefined ) ? p5 : new Plane() + var children = this.children; - ]; + for ( var i = 0, l = children.length; i < l; i ++ ) { - } + children[ i ].traverseVisible( callback ); - Object.assign( Frustum.prototype, { + } - set: function ( p0, p1, p2, p3, p4, p5 ) { + }, - var planes = this.planes; + traverseAncestors: function ( callback ) { - planes[ 0 ].copy( p0 ); - planes[ 1 ].copy( p1 ); - planes[ 2 ].copy( p2 ); - planes[ 3 ].copy( p3 ); - planes[ 4 ].copy( p4 ); - planes[ 5 ].copy( p5 ); + var parent = this.parent; - return this; + if ( parent !== null ) { - }, + callback( parent ); - clone: function () { + parent.traverseAncestors( callback ); - return new this.constructor().copy( this ); + } }, - copy: function ( frustum ) { + updateMatrix: function () { - var planes = this.planes; + this.matrix.compose( this.position, this.quaternion, this.scale ); - for ( var i = 0; i < 6; i ++ ) { + this.matrixWorldNeedsUpdate = true; - planes[ i ].copy( frustum.planes[ i ] ); + }, - } + updateMatrixWorld: function ( force ) { - return this; + if ( this.matrixAutoUpdate ) this.updateMatrix(); - }, + if ( this.matrixWorldNeedsUpdate || force ) { - setFromMatrix: function ( m ) { + if ( this.parent === null ) { - var planes = this.planes; - var me = m.elements; - var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; - var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; - var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; - var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; + this.matrixWorld.copy( this.matrix ); - planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); - planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); - planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); - planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); - planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); - planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); + } else { - return this; + this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); - }, + } - intersectsObject: function () { + this.matrixWorldNeedsUpdate = false; - var sphere = new Sphere(); + force = true; - return function intersectsObject( object ) { + } - var geometry = object.geometry; + // update children - if ( geometry.boundingSphere === null ) - geometry.computeBoundingSphere(); + var children = this.children; - sphere.copy( geometry.boundingSphere ) - .applyMatrix4( object.matrixWorld ); + for ( var i = 0, l = children.length; i < l; i ++ ) { - return this.intersectsSphere( sphere ); + children[ i ].updateMatrixWorld( force ); - }; + } - }(), + }, - intersectsSprite: function () { + toJSON: function ( meta ) { - var sphere = new Sphere(); + // meta is a string when called from JSON.stringify + var isRootObject = ( meta === undefined || typeof meta === 'string' ); - return function intersectsSprite( sprite ) { + var output = {}; - sphere.center.set( 0, 0, 0 ); - sphere.radius = 0.7071067811865476; - sphere.applyMatrix4( sprite.matrixWorld ); + // meta is a hash used to collect geometries, materials. + // not providing it implies that this is the root object + // being serialized. + if ( isRootObject ) { - return this.intersectsSphere( sphere ); + // initialize meta obj + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {} + }; - }; + output.metadata = { + version: 4.5, + type: 'Object', + generator: 'Object3D.toJSON' + }; - }(), + } - intersectsSphere: function ( sphere ) { + // standard Object3D serialization - var planes = this.planes; - var center = sphere.center; - var negRadius = - sphere.radius; + var object = {}; - for ( var i = 0; i < 6; i ++ ) { + object.uuid = this.uuid; + object.type = this.type; - var distance = planes[ i ].distanceToPoint( center ); + if ( this.name !== '' ) object.name = this.name; + if ( this.castShadow === true ) object.castShadow = true; + if ( this.receiveShadow === true ) object.receiveShadow = true; + if ( this.visible === false ) object.visible = false; + if ( this.frustumCulled === false ) object.frustumCulled = false; + if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder; + if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; - if ( distance < negRadius ) { + object.matrix = this.matrix.toArray(); - return false; + // + + function serialize( library, element ) { + + if ( library[ element.uuid ] === undefined ) { + + library[ element.uuid ] = element.toJSON( meta ); } - } + return element.uuid; - return true; + } - }, + if ( this.geometry !== undefined ) { - intersectsBox: function () { + object.geometry = serialize( meta.geometries, this.geometry ); - var p1 = new Vector3(), - p2 = new Vector3(); + var parameters = this.geometry.parameters; - return function intersectsBox( box ) { + if ( parameters !== undefined && parameters.shapes !== undefined ) { - var planes = this.planes; + var shapes = parameters.shapes; - for ( var i = 0; i < 6; i ++ ) { + if ( Array.isArray( shapes ) ) { - var plane = planes[ i ]; + for ( var i = 0, l = shapes.length; i < l; i ++ ) { - p1.x = plane.normal.x > 0 ? box.min.x : box.max.x; - p2.x = plane.normal.x > 0 ? box.max.x : box.min.x; - p1.y = plane.normal.y > 0 ? box.min.y : box.max.y; - p2.y = plane.normal.y > 0 ? box.max.y : box.min.y; - p1.z = plane.normal.z > 0 ? box.min.z : box.max.z; - p2.z = plane.normal.z > 0 ? box.max.z : box.min.z; + var shape = shapes[ i ]; - var d1 = plane.distanceToPoint( p1 ); - var d2 = plane.distanceToPoint( p2 ); + serialize( meta.shapes, shape ); - // if both outside plane, no intersection + } - if ( d1 < 0 && d2 < 0 ) { + } else { - return false; + serialize( meta.shapes, shapes ); } } - return true; + } - }; + if ( this.material !== undefined ) { - }(), + if ( Array.isArray( this.material ) ) { - containsPoint: function ( point ) { + var uuids = []; - var planes = this.planes; + for ( var i = 0, l = this.material.length; i < l; i ++ ) { - for ( var i = 0; i < 6; i ++ ) { + uuids.push( serialize( meta.materials, this.material[ i ] ) ); - if ( planes[ i ].distanceToPoint( point ) < 0 ) { + } - return false; + object.material = uuids; - } + } else { - } + object.material = serialize( meta.materials, this.material ); - return true; + } - } + } - } ); + // - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + if ( this.children.length > 0 ) { - function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) { + object.children = []; - var _gl = _renderer.context, - _state = _renderer.state, - _frustum = new Frustum(), - _projScreenMatrix = new Matrix4(), + for ( var i = 0; i < this.children.length; i ++ ) { - _lightShadows = _lights.shadows, + object.children.push( this.children[ i ].toJSON( meta ).object ); - _shadowMapSize = new Vector2(), - _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ), + } - _lookTarget = new Vector3(), - _lightPositionWorld = new Vector3(), + } - _MorphingFlag = 1, - _SkinningFlag = 2, + if ( isRootObject ) { - _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1, + var geometries = extractFromCache( meta.geometries ); + var materials = extractFromCache( meta.materials ); + var textures = extractFromCache( meta.textures ); + var images = extractFromCache( meta.images ); + var shapes = extractFromCache( meta.shapes ); - _depthMaterials = new Array( _NumberOfMaterialVariants ), - _distanceMaterials = new Array( _NumberOfMaterialVariants ), + if ( geometries.length > 0 ) output.geometries = geometries; + if ( materials.length > 0 ) output.materials = materials; + if ( textures.length > 0 ) output.textures = textures; + if ( images.length > 0 ) output.images = images; + if ( shapes.length > 0 ) output.shapes = shapes; - _materialCache = {}; + } - var cubeDirections = [ - new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ), - new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 ) - ]; + output.object = object; - var cubeUps = [ - new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), - new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 ) - ]; + return output; - var cube2DViewPorts = [ - new Vector4(), new Vector4(), new Vector4(), - new Vector4(), new Vector4(), new Vector4() - ]; + // extract data from the cache hash + // remove metadata on each item + // and return as array + function extractFromCache( cache ) { - // init + var values = []; + for ( var key in cache ) { - var depthMaterialTemplate = new MeshDepthMaterial(); - depthMaterialTemplate.depthPacking = RGBADepthPacking; - depthMaterialTemplate.clipping = true; + var data = cache[ key ]; + delete data.metadata; + values.push( data ); - var distanceShader = ShaderLib[ "distanceRGBA" ]; - var distanceUniforms = UniformsUtils.clone( distanceShader.uniforms ); + } + return values; - for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) { + } - var useMorphing = ( i & _MorphingFlag ) !== 0; - var useSkinning = ( i & _SkinningFlag ) !== 0; + }, - var depthMaterial = depthMaterialTemplate.clone(); - depthMaterial.morphTargets = useMorphing; - depthMaterial.skinning = useSkinning; + clone: function ( recursive ) { - _depthMaterials[ i ] = depthMaterial; + return new this.constructor().copy( this, recursive ); - var distanceMaterial = new ShaderMaterial( { - defines: { - 'USE_SHADOWMAP': '' - }, - uniforms: distanceUniforms, - vertexShader: distanceShader.vertexShader, - fragmentShader: distanceShader.fragmentShader, - morphTargets: useMorphing, - skinning: useSkinning, - clipping: true - } ); + }, - _distanceMaterials[ i ] = distanceMaterial; + copy: function ( source, recursive ) { - } + if ( recursive === undefined ) recursive = true; - // + this.name = source.name; - var scope = this; + this.up.copy( source.up ); - this.enabled = false; + this.position.copy( source.position ); + this.quaternion.copy( source.quaternion ); + this.scale.copy( source.scale ); - this.autoUpdate = true; - this.needsUpdate = false; + this.matrix.copy( source.matrix ); + this.matrixWorld.copy( source.matrixWorld ); - this.type = PCFShadowMap; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; - this.renderReverseSided = true; - this.renderSingleSided = true; + this.layers.mask = source.layers.mask; + this.visible = source.visible; - this.render = function ( scene, camera ) { + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; - if ( scope.enabled === false ) return; - if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; - if ( _lightShadows.length === 0 ) return; + this.userData = JSON.parse( JSON.stringify( source.userData ) ); - // Set GL state for depth map. - _state.disable( _gl.BLEND ); - _state.buffers.color.setClear( 1, 1, 1, 1 ); - _state.buffers.depth.setTest( true ); - _state.setScissorTest( false ); + if ( recursive === true ) { - // render depth map + for ( var i = 0; i < source.children.length; i ++ ) { - var faceCount; + var child = source.children[ i ]; + this.add( child.clone() ); - for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) { + } - var light = _lightShadows[ i ]; - var shadow = light.shadow; - var isPointLight = light && light.isPointLight; + } - if ( shadow === undefined ) { + return this; - console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); - continue; + } - } + } ); - var shadowCamera = shadow.camera; + /** + * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author WestLangley / http://github.com/WestLangley + */ - _shadowMapSize.copy( shadow.mapSize ); - _shadowMapSize.min( _maxShadowMapSize ); + function Camera() { - if ( isPointLight ) { + Object3D.call( this ); - var vpWidth = _shadowMapSize.x; - var vpHeight = _shadowMapSize.y; + this.type = 'Camera'; - // These viewports map a cube-map onto a 2D texture with the - // following orientation: - // - // xzXZ - // y Y - // - // X - Positive x direction - // x - Negative x direction - // Y - Positive y direction - // y - Negative y direction - // Z - Positive z direction - // z - Negative z direction + this.matrixWorldInverse = new Matrix4(); + this.projectionMatrix = new Matrix4(); - // positive X - cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight ); - // negative X - cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight ); - // positive Z - cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight ); - // negative Z - cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight ); - // positive Y - cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight ); - // negative Y - cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight ); + } - _shadowMapSize.x *= 4.0; - _shadowMapSize.y *= 2.0; + Camera.prototype = Object.assign( Object.create( Object3D.prototype ), { - } + constructor: Camera, - if ( shadow.map === null ) { + isCamera: true, - var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; + copy: function ( source, recursive ) { - shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); - shadow.map.texture.name = light.name + ".shadowMap"; + Object3D.prototype.copy.call( this, source, recursive ); - shadowCamera.updateProjectionMatrix(); + this.matrixWorldInverse.copy( source.matrixWorldInverse ); + this.projectionMatrix.copy( source.projectionMatrix ); - } + return this; - if ( shadow.isSpotLightShadow ) { + }, - shadow.update( light ); + getWorldDirection: function () { - } + var quaternion = new Quaternion(); - var shadowMap = shadow.map; - var shadowMatrix = shadow.matrix; + return function getWorldDirection( target ) { - _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); - shadowCamera.position.copy( _lightPositionWorld ); + if ( target === undefined ) { - if ( isPointLight ) { + console.warn( 'THREE.Camera: .getWorldDirection() target is now required' ); + target = new Vector3(); - faceCount = 6; + } - // for point lights we set the shadow matrix to be a translation-only matrix - // equal to inverse of the light's position + this.getWorldQuaternion( quaternion ); - shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z ); + return target.set( 0, 0, - 1 ).applyQuaternion( quaternion ); - } else { + }; - faceCount = 1; + }(), - _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); - shadowCamera.lookAt( _lookTarget ); - shadowCamera.updateMatrixWorld(); + updateMatrixWorld: function ( force ) { - // compute shadow matrix + Object3D.prototype.updateMatrixWorld.call( this, force ); - shadowMatrix.set( - 0.5, 0.0, 0.0, 0.5, - 0.0, 0.5, 0.0, 0.5, - 0.0, 0.0, 0.5, 0.5, - 0.0, 0.0, 0.0, 1.0 - ); + this.matrixWorldInverse.getInverse( this.matrixWorld ); - shadowMatrix.multiply( shadowCamera.projectionMatrix ); - shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); + }, - } + clone: function () { - _renderer.setRenderTarget( shadowMap ); - _renderer.clear(); + return new this.constructor().copy( this ); - // render shadow map for each cube face (if omni-directional) or - // run a single pass if not + } - for ( var face = 0; face < faceCount; face ++ ) { + } ); - if ( isPointLight ) { + /** + * @author alteredq / http://alteredqualia.com/ + * @author arose / http://github.com/arose + */ - _lookTarget.copy( shadowCamera.position ); - _lookTarget.add( cubeDirections[ face ] ); - shadowCamera.up.copy( cubeUps[ face ] ); - shadowCamera.lookAt( _lookTarget ); - shadowCamera.updateMatrixWorld(); + function OrthographicCamera( left, right, top, bottom, near, far ) { - var vpDimensions = cube2DViewPorts[ face ]; - _state.viewport( vpDimensions ); + Camera.call( this ); - } + this.type = 'OrthographicCamera'; - // update camera matrices and frustum + this.zoom = 1; + this.view = null; - _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; - // set object matrices & frustum culling + this.near = ( near !== undefined ) ? near : 0.1; + this.far = ( far !== undefined ) ? far : 2000; - renderObject( scene, camera, shadowCamera, isPointLight ); + this.updateProjectionMatrix(); - } + } - } + OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - // Restore GL state. - var clearColor = _renderer.getClearColor(); - var clearAlpha = _renderer.getClearAlpha(); - _renderer.setClearColor( clearColor, clearAlpha ); + constructor: OrthographicCamera, - scope.needsUpdate = false; + isOrthographicCamera: true, - }; + copy: function ( source, recursive ) { - function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) { + Camera.prototype.copy.call( this, source, recursive ); - var geometry = object.geometry; + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; - var result = null; + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - var materialVariants = _depthMaterials; - var customMaterial = object.customDepthMaterial; + return this; - if ( isPointLight ) { + }, - materialVariants = _distanceMaterials; - customMaterial = object.customDistanceMaterial; + setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { + + if ( this.view === null ) { + + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; } - if ( ! customMaterial ) { + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; - var useMorphing = false; + this.updateProjectionMatrix(); - if ( material.morphTargets ) { + }, - if ( geometry && geometry.isBufferGeometry ) { + clearViewOffset: function () { - useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; + if ( this.view !== null ) { - } else if ( geometry && geometry.isGeometry ) { + this.view.enabled = false; - useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; + } - } + this.updateProjectionMatrix(); - } + }, - if ( object.isSkinnedMesh && material.skinning === false ) { + updateProjectionMatrix: function () { - console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object ); + var dx = ( this.right - this.left ) / ( 2 * this.zoom ); + var dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); + var cx = ( this.right + this.left ) / 2; + var cy = ( this.top + this.bottom ) / 2; - } + var left = cx - dx; + var right = cx + dx; + var top = cy + dy; + var bottom = cy - dy; - var useSkinning = object.isSkinnedMesh && material.skinning; + if ( this.view !== null && this.view.enabled ) { - var variantIndex = 0; + var zoomW = this.zoom / ( this.view.width / this.view.fullWidth ); + var zoomH = this.zoom / ( this.view.height / this.view.fullHeight ); + var scaleW = ( this.right - this.left ) / this.view.width; + var scaleH = ( this.top - this.bottom ) / this.view.height; - if ( useMorphing ) variantIndex |= _MorphingFlag; - if ( useSkinning ) variantIndex |= _SkinningFlag; + left += scaleW * ( this.view.offsetX / zoomW ); + right = left + scaleW * ( this.view.width / zoomW ); + top -= scaleH * ( this.view.offsetY / zoomH ); + bottom = top - scaleH * ( this.view.height / zoomH ); - result = materialVariants[ variantIndex ]; + } - } else { + this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); - result = customMaterial; + }, - } + toJSON: function ( meta ) { - if ( _renderer.localClippingEnabled && - material.clipShadows === true && - material.clippingPlanes.length !== 0 ) { + var data = Object3D.prototype.toJSON.call( this, meta ); - // in this case we need a unique material instance reflecting the - // appropriate state + data.object.zoom = this.zoom; + data.object.left = this.left; + data.object.right = this.right; + data.object.top = this.top; + data.object.bottom = this.bottom; + data.object.near = this.near; + data.object.far = this.far; - var keyA = result.uuid, keyB = material.uuid; + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - var materialsForVariant = _materialCache[ keyA ]; + return data; - if ( materialsForVariant === undefined ) { + } - materialsForVariant = {}; - _materialCache[ keyA ] = materialsForVariant; + } ); - } + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - var cachedMaterial = materialsForVariant[ keyB ]; + function Face3( a, b, c, normal, color, materialIndex ) { - if ( cachedMaterial === undefined ) { + this.a = a; + this.b = b; + this.c = c; - cachedMaterial = result.clone(); - materialsForVariant[ keyB ] = cachedMaterial; + this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3(); + this.vertexNormals = Array.isArray( normal ) ? normal : []; - } + this.color = ( color && color.isColor ) ? color : new Color(); + this.vertexColors = Array.isArray( color ) ? color : []; - result = cachedMaterial; + this.materialIndex = materialIndex !== undefined ? materialIndex : 0; - } + } - result.visible = material.visible; - result.wireframe = material.wireframe; + Object.assign( Face3.prototype, { - var side = material.side; + clone: function () { - if ( scope.renderSingleSided && side == DoubleSide ) { + return new this.constructor().copy( this ); - side = FrontSide; + }, - } + copy: function ( source ) { - if ( scope.renderReverseSided ) { + this.a = source.a; + this.b = source.b; + this.c = source.c; - if ( side === FrontSide ) side = BackSide; - else if ( side === BackSide ) side = FrontSide; + this.normal.copy( source.normal ); + this.color.copy( source.color ); - } + this.materialIndex = source.materialIndex; - result.side = side; + for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { - result.clipShadows = material.clipShadows; - result.clippingPlanes = material.clippingPlanes; + this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); - result.wireframeLinewidth = material.wireframeLinewidth; - result.linewidth = material.linewidth; + } - if ( isPointLight && result.uniforms.lightPos !== undefined ) { + for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { - result.uniforms.lightPos.value.copy( lightPositionWorld ); + this.vertexColors[ i ] = source.vertexColors[ i ].clone(); } - return result; + return this; } - function renderObject( object, camera, shadowCamera, isPointLight ) { + } ); - if ( object.visible === false ) return; + /** + * @author mrdoob / http://mrdoob.com/ + * @author kile / http://kile.stravaganza.org/ + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author bhouston / http://clara.io + */ - var visible = object.layers.test( camera.layers ); + var geometryId = 0; // Geometry uses even numbers as Id - if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) { + function Geometry() { - if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) { + Object.defineProperty( this, 'id', { value: geometryId += 2 } ); - object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + this.uuid = _Math.generateUUID(); - var geometry = _objects.update( object ); - var material = object.material; + this.name = ''; + this.type = 'Geometry'; - if ( Array.isArray( material ) ) { + this.vertices = []; + this.colors = []; + this.faces = []; + this.faceVertexUvs = [[]]; - var groups = geometry.groups; + this.morphTargets = []; + this.morphNormals = []; - for ( var k = 0, kl = groups.length; k < kl; k ++ ) { + this.skinWeights = []; + this.skinIndices = []; - var group = groups[ k ]; - var groupMaterial = material[ group.materialIndex ]; + this.lineDistances = []; - if ( groupMaterial && groupMaterial.visible ) { + this.boundingBox = null; + this.boundingSphere = null; - var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld ); - _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); + // update flags - } + this.elementsNeedUpdate = false; + this.verticesNeedUpdate = false; + this.uvsNeedUpdate = false; + this.normalsNeedUpdate = false; + this.colorsNeedUpdate = false; + this.lineDistancesNeedUpdate = false; + this.groupsNeedUpdate = false; - } + } - } else if ( material.visible ) { + Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { - var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld ); - _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); + constructor: Geometry, - } + isGeometry: true, - } + applyMatrix: function ( matrix ) { + + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); + + for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { + + var vertex = this.vertices[ i ]; + vertex.applyMatrix4( matrix ); } - var children = object.children; + for ( var i = 0, il = this.faces.length; i < il; i ++ ) { - for ( var i = 0, l = children.length; i < l; i ++ ) { + var face = this.faces[ i ]; + face.normal.applyMatrix3( normalMatrix ).normalize(); - renderObject( children[ i ], camera, shadowCamera, isPointLight ); + for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { - } + face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); - } + } - } + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( this.boundingBox !== null ) { - function WebGLAttributes( gl ) { + this.computeBoundingBox(); - var buffers = {}; + } - function createBuffer( attribute, bufferType ) { + if ( this.boundingSphere !== null ) { - var array = attribute.array; - var usage = attribute.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; + this.computeBoundingSphere(); - var buffer = gl.createBuffer(); + } - gl.bindBuffer( bufferType, buffer ); - gl.bufferData( bufferType, array, usage ); + this.verticesNeedUpdate = true; + this.normalsNeedUpdate = true; - attribute.onUploadCallback(); + return this; - var type = gl.FLOAT; + }, - if ( array instanceof Float32Array ) { + rotateX: function () { - type = gl.FLOAT; + // rotate geometry around world x-axis - } else if ( array instanceof Float64Array ) { + var m1 = new Matrix4(); - console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' ); + return function rotateX( angle ) { - } else if ( array instanceof Uint16Array ) { + m1.makeRotationX( angle ); - type = gl.UNSIGNED_SHORT; + this.applyMatrix( m1 ); - } else if ( array instanceof Int16Array ) { + return this; - type = gl.SHORT; + }; - } else if ( array instanceof Uint32Array ) { + }(), - type = gl.UNSIGNED_INT; + rotateY: function () { - } else if ( array instanceof Int32Array ) { + // rotate geometry around world y-axis - type = gl.INT; + var m1 = new Matrix4(); - } else if ( array instanceof Int8Array ) { + return function rotateY( angle ) { - type = gl.BYTE; + m1.makeRotationY( angle ); - } else if ( array instanceof Uint8Array ) { + this.applyMatrix( m1 ); - type = gl.UNSIGNED_BYTE; + return this; - } + }; - return { - buffer: buffer, - type: type, - bytesPerElement: array.BYTES_PER_ELEMENT, - version: attribute.version - }; + }(), - } + rotateZ: function () { - function updateBuffer( buffer, attribute, bufferType ) { + // rotate geometry around world z-axis - var array = attribute.array; - var updateRange = attribute.updateRange; + var m1 = new Matrix4(); - gl.bindBuffer( bufferType, buffer ); + return function rotateZ( angle ) { - if ( attribute.dynamic === false ) { + m1.makeRotationZ( angle ); - gl.bufferData( bufferType, array, gl.STATIC_DRAW ); + this.applyMatrix( m1 ); - } else if ( updateRange.count === - 1 ) { + return this; - // Not using update ranges + }; - gl.bufferSubData( bufferType, 0, array ); + }(), - } else if ( updateRange.count === 0 ) { + translate: function () { - console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' ); + // translate geometry - } else { + var m1 = new Matrix4(); - gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, - array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) ); + return function translate( x, y, z ) { - updateRange.count = -1; // reset range + m1.makeTranslation( x, y, z ); - } + this.applyMatrix( m1 ); - } + return this; - // + }; - function get( attribute ) { + }(), - if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + scale: function () { - return buffers[ attribute.uuid ]; + // scale geometry - } + var m1 = new Matrix4(); - function remove( attribute ) { + return function scale( x, y, z ) { - if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; - - var data = buffers[ attribute.uuid ]; + m1.makeScale( x, y, z ); - if ( data ) { + this.applyMatrix( m1 ); - gl.deleteBuffer( data.buffer ); + return this; - delete buffers[ attribute.uuid ]; + }; - } + }(), - } + lookAt: function () { - function update( attribute, bufferType ) { + var obj = new Object3D(); - if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data; + return function lookAt( vector ) { - var data = buffers[ attribute.uuid ]; + obj.lookAt( vector ); - if ( data === undefined ) { + obj.updateMatrix(); - buffers[ attribute.uuid ] = createBuffer( attribute, bufferType ); + this.applyMatrix( obj.matrix ); - } else if ( data.version < attribute.version ) { + }; - updateBuffer( data.buffer, attribute, bufferType ); + }(), - data.version = attribute.version; + fromBufferGeometry: function ( geometry ) { - } + var scope = this; - } + var indices = geometry.index !== null ? geometry.index.array : undefined; + var attributes = geometry.attributes; - return { + var positions = attributes.position.array; + var normals = attributes.normal !== undefined ? attributes.normal.array : undefined; + var colors = attributes.color !== undefined ? attributes.color.array : undefined; + var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined; + var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined; - get: get, - remove: remove, - update: update + if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = []; - }; + var tempNormals = []; + var tempUVs = []; + var tempUVs2 = []; - } + for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - * @author bhouston / http://clara.io - */ + scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); - function Euler( x, y, z, order ) { + if ( normals !== undefined ) { - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this._order = order || Euler.DefaultOrder; + tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); - } + } - Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; + if ( colors !== undefined ) { - Euler.DefaultOrder = 'XYZ'; + scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); - Object.defineProperties( Euler.prototype, { + } - x: { + if ( uvs !== undefined ) { - get: function () { + tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) ); - return this._x; + } - }, + if ( uvs2 !== undefined ) { - set: function ( value ) { + tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); - this._x = value; - this.onChangeCallback(); + } } - }, + function addFace( a, b, c, materialIndex ) { - y: { + var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : []; + var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : []; - get: function () { + var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); - return this._y; + scope.faces.push( face ); - }, + if ( uvs !== undefined ) { - set: function ( value ) { + scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] ); - this._y = value; - this.onChangeCallback(); + } + + if ( uvs2 !== undefined ) { + + scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] ); + + } } - }, + var groups = geometry.groups; - z: { + if ( groups.length > 0 ) { - get: function () { + for ( var i = 0; i < groups.length; i ++ ) { - return this._z; + var group = groups[ i ]; - }, + var start = group.start; + var count = group.count; - set: function ( value ) { + for ( var j = start, jl = start + count; j < jl; j += 3 ) { - this._z = value; - this.onChangeCallback(); + if ( indices !== undefined ) { - } + addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex ); - }, + } else { - order: { + addFace( j, j + 1, j + 2, group.materialIndex ); - get: function () { + } - return this._order; + } - }, + } - set: function ( value ) { + } else { - this._order = value; - this.onChangeCallback(); + if ( indices !== undefined ) { - } + for ( var i = 0; i < indices.length; i += 3 ) { - } + addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); - } ); + } - Object.assign( Euler.prototype, { + } else { - isEuler: true, + for ( var i = 0; i < positions.length / 3; i += 3 ) { - set: function ( x, y, z, order ) { + addFace( i, i + 1, i + 2 ); - this._x = x; - this._y = y; - this._z = z; - this._order = order || this._order; + } - this.onChangeCallback(); + } - return this; + } - }, + this.computeFaceNormals(); - clone: function () { + if ( geometry.boundingBox !== null ) { - return new this.constructor( this._x, this._y, this._z, this._order ); + this.boundingBox = geometry.boundingBox.clone(); - }, + } - copy: function ( euler ) { + if ( geometry.boundingSphere !== null ) { - this._x = euler._x; - this._y = euler._y; - this._z = euler._z; - this._order = euler._order; + this.boundingSphere = geometry.boundingSphere.clone(); - this.onChangeCallback(); + } return this; }, - setFromRotationMatrix: function ( m, order, update ) { + center: function () { - var clamp = _Math.clamp; + var offset = new Vector3(); - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + return function center() { - var te = m.elements; - var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; - var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; - var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; + this.computeBoundingBox(); - order = order || this._order; + this.boundingBox.getCenter( offset ).negate(); - if ( order === 'XYZ' ) { + this.translate( offset.x, offset.y, offset.z ); - this._y = Math.asin( clamp( m13, - 1, 1 ) ); + return this; - if ( Math.abs( m13 ) < 0.99999 ) { + }; - this._x = Math.atan2( - m23, m33 ); - this._z = Math.atan2( - m12, m11 ); + }(), - } else { + normalize: function () { - this._x = Math.atan2( m32, m22 ); - this._z = 0; + this.computeBoundingSphere(); - } + var center = this.boundingSphere.center; + var radius = this.boundingSphere.radius; - } else if ( order === 'YXZ' ) { + var s = radius === 0 ? 1 : 1.0 / radius; - this._x = Math.asin( - clamp( m23, - 1, 1 ) ); + var matrix = new Matrix4(); + matrix.set( + s, 0, 0, - s * center.x, + 0, s, 0, - s * center.y, + 0, 0, s, - s * center.z, + 0, 0, 0, 1 + ); - if ( Math.abs( m23 ) < 0.99999 ) { + this.applyMatrix( matrix ); - this._y = Math.atan2( m13, m33 ); - this._z = Math.atan2( m21, m22 ); + return this; - } else { + }, - this._y = Math.atan2( - m31, m11 ); - this._z = 0; + computeFaceNormals: function () { - } + var cb = new Vector3(), ab = new Vector3(); - } else if ( order === 'ZXY' ) { + for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { - this._x = Math.asin( clamp( m32, - 1, 1 ) ); + var face = this.faces[ f ]; - if ( Math.abs( m32 ) < 0.99999 ) { + var vA = this.vertices[ face.a ]; + var vB = this.vertices[ face.b ]; + var vC = this.vertices[ face.c ]; - this._y = Math.atan2( - m31, m33 ); - this._z = Math.atan2( - m12, m22 ); + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - } else { + cb.normalize(); - this._y = 0; - this._z = Math.atan2( m21, m11 ); + face.normal.copy( cb ); - } + } - } else if ( order === 'ZYX' ) { + }, - this._y = Math.asin( - clamp( m31, - 1, 1 ) ); + computeVertexNormals: function ( areaWeighted ) { - if ( Math.abs( m31 ) < 0.99999 ) { + if ( areaWeighted === undefined ) areaWeighted = true; - this._x = Math.atan2( m32, m33 ); - this._z = Math.atan2( m21, m11 ); + var v, vl, f, fl, face, vertices; - } else { + vertices = new Array( this.vertices.length ); - this._x = 0; - this._z = Math.atan2( - m12, m22 ); + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - } + vertices[ v ] = new Vector3(); - } else if ( order === 'YZX' ) { + } - this._z = Math.asin( clamp( m21, - 1, 1 ) ); + if ( areaWeighted ) { - if ( Math.abs( m21 ) < 0.99999 ) { + // vertex normals weighted by triangle areas + // http://www.iquilezles.org/www/articles/normals/normals.htm - this._x = Math.atan2( - m23, m22 ); - this._y = Math.atan2( - m31, m11 ); + var vA, vB, vC; + var cb = new Vector3(), ab = new Vector3(); - } else { + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - this._x = 0; - this._y = Math.atan2( m13, m33 ); + face = this.faces[ f ]; - } + vA = this.vertices[ face.a ]; + vB = this.vertices[ face.b ]; + vC = this.vertices[ face.c ]; - } else if ( order === 'XZY' ) { + cb.subVectors( vC, vB ); + ab.subVectors( vA, vB ); + cb.cross( ab ); - this._z = Math.asin( - clamp( m12, - 1, 1 ) ); + vertices[ face.a ].add( cb ); + vertices[ face.b ].add( cb ); + vertices[ face.c ].add( cb ); - if ( Math.abs( m12 ) < 0.99999 ) { + } - this._x = Math.atan2( m32, m22 ); - this._y = Math.atan2( m13, m11 ); + } else { - } else { + this.computeFaceNormals(); - this._x = Math.atan2( - m23, m33 ); - this._y = 0; + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - } + face = this.faces[ f ]; - } else { + vertices[ face.a ].add( face.normal ); + vertices[ face.b ].add( face.normal ); + vertices[ face.c ].add( face.normal ); - console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ); + } } - this._order = order; + for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { - if ( update !== false ) this.onChangeCallback(); + vertices[ v ].normalize(); - return this; + } - }, + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - setFromQuaternion: function () { + face = this.faces[ f ]; - var matrix = new Matrix4(); + var vertexNormals = face.vertexNormals; - return function setFromQuaternion( q, order, update ) { + if ( vertexNormals.length === 3 ) { - matrix.makeRotationFromQuaternion( q ); + vertexNormals[ 0 ].copy( vertices[ face.a ] ); + vertexNormals[ 1 ].copy( vertices[ face.b ] ); + vertexNormals[ 2 ].copy( vertices[ face.c ] ); - return this.setFromRotationMatrix( matrix, order, update ); + } else { - }; + vertexNormals[ 0 ] = vertices[ face.a ].clone(); + vertexNormals[ 1 ] = vertices[ face.b ].clone(); + vertexNormals[ 2 ] = vertices[ face.c ].clone(); - }(), + } - setFromVector3: function ( v, order ) { + } - return this.set( v.x, v.y, v.z, order || this._order ); + if ( this.faces.length > 0 ) { + + this.normalsNeedUpdate = true; + + } }, - reorder: function () { + computeFlatVertexNormals: function () { - // WARNING: this discards revolution information -bhouston + var f, fl, face; - var q = new Quaternion(); + this.computeFaceNormals(); - return function reorder( newOrder ) { + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - q.setFromEuler( this ); + face = this.faces[ f ]; - return this.setFromQuaternion( q, newOrder ); + var vertexNormals = face.vertexNormals; - }; + if ( vertexNormals.length === 3 ) { - }(), + vertexNormals[ 0 ].copy( face.normal ); + vertexNormals[ 1 ].copy( face.normal ); + vertexNormals[ 2 ].copy( face.normal ); - equals: function ( euler ) { + } else { - return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); + vertexNormals[ 0 ] = face.normal.clone(); + vertexNormals[ 1 ] = face.normal.clone(); + vertexNormals[ 2 ] = face.normal.clone(); - }, + } - fromArray: function ( array ) { + } - this._x = array[ 0 ]; - this._y = array[ 1 ]; - this._z = array[ 2 ]; - if ( array[ 3 ] !== undefined ) this._order = array[ 3 ]; + if ( this.faces.length > 0 ) { - this.onChangeCallback(); + this.normalsNeedUpdate = true; - return this; + } }, - toArray: function ( array, offset ) { + computeMorphNormals: function () { - if ( array === undefined ) array = []; - if ( offset === undefined ) offset = 0; + var i, il, f, fl, face; - array[ offset ] = this._x; - array[ offset + 1 ] = this._y; - array[ offset + 2 ] = this._z; - array[ offset + 3 ] = this._order; + // save original normals + // - create temp variables on first access + // otherwise just copy (for faster repeated calls) - return array; + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - }, + face = this.faces[ f ]; - toVector3: function ( optionalResult ) { + if ( ! face.__originalFaceNormal ) { - if ( optionalResult ) { + face.__originalFaceNormal = face.normal.clone(); - return optionalResult.set( this._x, this._y, this._z ); + } else { - } else { + face.__originalFaceNormal.copy( face.normal ); - return new Vector3( this._x, this._y, this._z ); + } - } + if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; - }, + for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { - onChange: function ( callback ) { + if ( ! face.__originalVertexNormals[ i ] ) { - this.onChangeCallback = callback; + face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); - return this; + } else { - }, + face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); - onChangeCallback: function () {} + } - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function Layers() { + // use temp geometry to compute face and vertex normals for each morph - this.mask = 1 | 0; + var tmpGeo = new Geometry(); + tmpGeo.faces = this.faces; - } + for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { - Object.assign( Layers.prototype, { + // create on first access - set: function ( channel ) { + if ( ! this.morphNormals[ i ] ) { - this.mask = 1 << channel | 0; + this.morphNormals[ i ] = {}; + this.morphNormals[ i ].faceNormals = []; + this.morphNormals[ i ].vertexNormals = []; - }, + var dstNormalsFace = this.morphNormals[ i ].faceNormals; + var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; - enable: function ( channel ) { + var faceNormal, vertexNormals; - this.mask |= 1 << channel | 0; + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - }, + faceNormal = new Vector3(); + vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; - toggle: function ( channel ) { + dstNormalsFace.push( faceNormal ); + dstNormalsVertex.push( vertexNormals ); - this.mask ^= 1 << channel | 0; + } - }, + } - disable: function ( channel ) { + var morphNormals = this.morphNormals[ i ]; - this.mask &= ~ ( 1 << channel | 0 ); + // set vertices to morph target - }, + tmpGeo.vertices = this.morphTargets[ i ].vertices; - test: function ( layers ) { + // compute morph normals - return ( this.mask & layers.mask ) !== 0; + tmpGeo.computeFaceNormals(); + tmpGeo.computeVertexNormals(); - } + // store morph normals - } ); + var faceNormal, vertexNormals; - /** - * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author WestLangley / http://github.com/WestLangley - * @author elephantatwork / www.elephantatwork.ch - */ + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - var object3DId = 0; + face = this.faces[ f ]; - function Object3D() { + faceNormal = morphNormals.faceNormals[ f ]; + vertexNormals = morphNormals.vertexNormals[ f ]; - Object.defineProperty( this, 'id', { value: object3DId ++ } ); + faceNormal.copy( face.normal ); - this.uuid = _Math.generateUUID(); + vertexNormals.a.copy( face.vertexNormals[ 0 ] ); + vertexNormals.b.copy( face.vertexNormals[ 1 ] ); + vertexNormals.c.copy( face.vertexNormals[ 2 ] ); - this.name = ''; - this.type = 'Object3D'; + } - this.parent = null; - this.children = []; + } - this.up = Object3D.DefaultUp.clone(); + // restore original normals - var position = new Vector3(); - var rotation = new Euler(); - var quaternion = new Quaternion(); - var scale = new Vector3( 1, 1, 1 ); + for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { - function onRotationChange() { + face = this.faces[ f ]; - quaternion.setFromEuler( rotation, false ); + face.normal = face.__originalFaceNormal; + face.vertexNormals = face.__originalVertexNormals; - } + } - function onQuaternionChange() { + }, - rotation.setFromQuaternion( quaternion, undefined, false ); + computeBoundingBox: function () { - } + if ( this.boundingBox === null ) { - rotation.onChange( onRotationChange ); - quaternion.onChange( onQuaternionChange ); + this.boundingBox = new Box3(); - Object.defineProperties( this, { - position: { - enumerable: true, - value: position - }, - rotation: { - enumerable: true, - value: rotation - }, - quaternion: { - enumerable: true, - value: quaternion - }, - scale: { - enumerable: true, - value: scale - }, - modelViewMatrix: { - value: new Matrix4() - }, - normalMatrix: { - value: new Matrix3() } - } ); - this.matrix = new Matrix4(); - this.matrixWorld = new Matrix4(); + this.boundingBox.setFromPoints( this.vertices ); - this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; - this.matrixWorldNeedsUpdate = false; + }, - this.layers = new Layers(); - this.visible = true; + computeBoundingSphere: function () { - this.castShadow = false; - this.receiveShadow = false; + if ( this.boundingSphere === null ) { - this.frustumCulled = true; - this.renderOrder = 0; + this.boundingSphere = new Sphere(); - this.userData = {}; - } + } - Object3D.DefaultUp = new Vector3( 0, 1, 0 ); - Object3D.DefaultMatrixAutoUpdate = true; + this.boundingSphere.setFromPoints( this.vertices ); - Object.assign( Object3D.prototype, EventDispatcher.prototype, { + }, - isObject3D: true, + merge: function ( geometry, matrix, materialIndexOffset ) { - onBeforeRender: function () {}, - onAfterRender: function () {}, + if ( ! ( geometry && geometry.isGeometry ) ) { - applyMatrix: function ( matrix ) { + console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); + return; - this.matrix.multiplyMatrices( matrix, this.matrix ); + } - this.matrix.decompose( this.position, this.quaternion, this.scale ); + var normalMatrix, + vertexOffset = this.vertices.length, + vertices1 = this.vertices, + vertices2 = geometry.vertices, + faces1 = this.faces, + faces2 = geometry.faces, + uvs1 = this.faceVertexUvs[ 0 ], + uvs2 = geometry.faceVertexUvs[ 0 ], + colors1 = this.colors, + colors2 = geometry.colors; - }, + if ( materialIndexOffset === undefined ) materialIndexOffset = 0; - applyQuaternion: function ( q ) { + if ( matrix !== undefined ) { - this.quaternion.premultiply( q ); + normalMatrix = new Matrix3().getNormalMatrix( matrix ); - return this; + } - }, + // vertices - setRotationFromAxisAngle: function ( axis, angle ) { + for ( var i = 0, il = vertices2.length; i < il; i ++ ) { - // assumes axis is normalized + var vertex = vertices2[ i ]; - this.quaternion.setFromAxisAngle( axis, angle ); + var vertexCopy = vertex.clone(); - }, + if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); - setRotationFromEuler: function ( euler ) { + vertices1.push( vertexCopy ); - this.quaternion.setFromEuler( euler, true ); + } - }, + // colors - setRotationFromMatrix: function ( m ) { + for ( var i = 0, il = colors2.length; i < il; i ++ ) { - // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + colors1.push( colors2[ i ].clone() ); - this.quaternion.setFromRotationMatrix( m ); + } - }, + // faces - setRotationFromQuaternion: function ( q ) { + for ( i = 0, il = faces2.length; i < il; i ++ ) { - // assumes q is normalized + var face = faces2[ i ], faceCopy, normal, color, + faceVertexNormals = face.vertexNormals, + faceVertexColors = face.vertexColors; - this.quaternion.copy( q ); + faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); + faceCopy.normal.copy( face.normal ); - }, + if ( normalMatrix !== undefined ) { - rotateOnAxis: function () { + faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); - // rotate object on axis in object space - // axis is assumed to be normalized + } - var q1 = new Quaternion(); + for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { - return function rotateOnAxis( axis, angle ) { + normal = faceVertexNormals[ j ].clone(); - q1.setFromAxisAngle( axis, angle ); + if ( normalMatrix !== undefined ) { - this.quaternion.multiply( q1 ); + normal.applyMatrix3( normalMatrix ).normalize(); - return this; + } - }; + faceCopy.vertexNormals.push( normal ); - }(), + } - rotateX: function () { + faceCopy.color.copy( face.color ); - var v1 = new Vector3( 1, 0, 0 ); + for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { - return function rotateX( angle ) { + color = faceVertexColors[ j ]; + faceCopy.vertexColors.push( color.clone() ); - return this.rotateOnAxis( v1, angle ); + } - }; + faceCopy.materialIndex = face.materialIndex + materialIndexOffset; - }(), + faces1.push( faceCopy ); - rotateY: function () { + } - var v1 = new Vector3( 0, 1, 0 ); + // uvs - return function rotateY( angle ) { + for ( i = 0, il = uvs2.length; i < il; i ++ ) { - return this.rotateOnAxis( v1, angle ); + var uv = uvs2[ i ], uvCopy = []; - }; + if ( uv === undefined ) { - }(), + continue; - rotateZ: function () { + } - var v1 = new Vector3( 0, 0, 1 ); + for ( var j = 0, jl = uv.length; j < jl; j ++ ) { - return function rotateZ( angle ) { + uvCopy.push( uv[ j ].clone() ); - return this.rotateOnAxis( v1, angle ); + } - }; + uvs1.push( uvCopy ); - }(), + } - translateOnAxis: function () { + }, - // translate object by distance along axis in object space - // axis is assumed to be normalized + mergeMesh: function ( mesh ) { - var v1 = new Vector3(); + if ( ! ( mesh && mesh.isMesh ) ) { - return function translateOnAxis( axis, distance ) { + console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); + return; - v1.copy( axis ).applyQuaternion( this.quaternion ); + } - this.position.add( v1.multiplyScalar( distance ) ); + if ( mesh.matrixAutoUpdate ) mesh.updateMatrix(); - return this; + this.merge( mesh.geometry, mesh.matrix ); - }; + }, - }(), + /* + * Checks for duplicate vertices with hashmap. + * Duplicated vertices are removed + * and faces' vertices are updated. + */ - translateX: function () { + mergeVertices: function () { - var v1 = new Vector3( 1, 0, 0 ); + var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) + var unique = [], changes = []; - return function translateX( distance ) { + var v, key; + var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001 + var precision = Math.pow( 10, precisionPoints ); + var i, il, face; + var indices, j, jl; - return this.translateOnAxis( v1, distance ); + for ( i = 0, il = this.vertices.length; i < il; i ++ ) { - }; + v = this.vertices[ i ]; + key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); - }(), + if ( verticesMap[ key ] === undefined ) { - translateY: function () { + verticesMap[ key ] = i; + unique.push( this.vertices[ i ] ); + changes[ i ] = unique.length - 1; - var v1 = new Vector3( 0, 1, 0 ); + } else { - return function translateY( distance ) { + //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); + changes[ i ] = changes[ verticesMap[ key ] ]; - return this.translateOnAxis( v1, distance ); + } - }; + } - }(), - translateZ: function () { + // if faces are completely degenerate after merging vertices, we + // have to remove them from the geometry. + var faceIndicesToRemove = []; - var v1 = new Vector3( 0, 0, 1 ); + for ( i = 0, il = this.faces.length; i < il; i ++ ) { - return function translateZ( distance ) { + face = this.faces[ i ]; - return this.translateOnAxis( v1, distance ); + face.a = changes[ face.a ]; + face.b = changes[ face.b ]; + face.c = changes[ face.c ]; - }; + indices = [ face.a, face.b, face.c ]; - }(), + // if any duplicate vertices are found in a Face3 + // we have to remove the face as nothing can be saved + for ( var n = 0; n < 3; n ++ ) { - localToWorld: function ( vector ) { + if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { - return vector.applyMatrix4( this.matrixWorld ); + faceIndicesToRemove.push( i ); + break; - }, + } - worldToLocal: function () { + } - var m1 = new Matrix4(); + } - return function worldToLocal( vector ) { + for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { - return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); + var idx = faceIndicesToRemove[ i ]; - }; + this.faces.splice( idx, 1 ); - }(), + for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { - lookAt: function () { + this.faceVertexUvs[ j ].splice( idx, 1 ); - // This method does not support objects with rotated and/or translated parent(s) + } - var m1 = new Matrix4(); + } - return function lookAt( vector ) { + // Use unique set of vertices - if ( this.isCamera ) { + var diff = this.vertices.length - unique.length; + this.vertices = unique; + return diff; - m1.lookAt( this.position, vector, this.up ); + }, - } else { + setFromPoints: function ( points ) { - m1.lookAt( vector, this.position, this.up ); + this.vertices = []; - } + for ( var i = 0, l = points.length; i < l; i ++ ) { - this.quaternion.setFromRotationMatrix( m1 ); + var point = points[ i ]; + this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); - }; + } - }(), + return this; - add: function ( object ) { + }, - if ( arguments.length > 1 ) { + sortFacesByMaterialIndex: function () { - for ( var i = 0; i < arguments.length; i ++ ) { + var faces = this.faces; + var length = faces.length; - this.add( arguments[ i ] ); + // tag faces - } + for ( var i = 0; i < length; i ++ ) { - return this; + faces[ i ]._id = i; } - if ( object === this ) { + // sort faces - console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); - return this; + function materialIndexSort( a, b ) { + + return a.materialIndex - b.materialIndex; } - if ( ( object && object.isObject3D ) ) { + faces.sort( materialIndexSort ); - if ( object.parent !== null ) { + // sort uvs - object.parent.remove( object ); + var uvs1 = this.faceVertexUvs[ 0 ]; + var uvs2 = this.faceVertexUvs[ 1 ]; - } + var newUvs1, newUvs2; - object.parent = this; - object.dispatchEvent( { type: 'added' } ); + if ( uvs1 && uvs1.length === length ) newUvs1 = []; + if ( uvs2 && uvs2.length === length ) newUvs2 = []; - this.children.push( object ); + for ( var i = 0; i < length; i ++ ) { - } else { + var id = faces[ i ]._id; - console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); + if ( newUvs1 ) newUvs1.push( uvs1[ id ] ); + if ( newUvs2 ) newUvs2.push( uvs2[ id ] ); } - return this; + if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1; + if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2; }, - remove: function ( object ) { - - if ( arguments.length > 1 ) { - - for ( var i = 0; i < arguments.length; i ++ ) { - - this.remove( arguments[ i ] ); + toJSON: function () { + var data = { + metadata: { + version: 4.5, + type: 'Geometry', + generator: 'Geometry.toJSON' } + }; - return this; + // standard Geometry serialization - } + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; - var index = this.children.indexOf( object ); + if ( this.parameters !== undefined ) { - if ( index !== - 1 ) { + var parameters = this.parameters; - object.parent = null; + for ( var key in parameters ) { - object.dispatchEvent( { type: 'removed' } ); + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; - this.children.splice( index, 1 ); + } + + return data; } - return this; - - }, + var vertices = []; - getObjectById: function ( id ) { + for ( var i = 0; i < this.vertices.length; i ++ ) { - return this.getObjectByProperty( 'id', id ); + var vertex = this.vertices[ i ]; + vertices.push( vertex.x, vertex.y, vertex.z ); - }, + } - getObjectByName: function ( name ) { + var faces = []; + var normals = []; + var normalsHash = {}; + var colors = []; + var colorsHash = {}; + var uvs = []; + var uvsHash = {}; - return this.getObjectByProperty( 'name', name ); + for ( var i = 0; i < this.faces.length; i ++ ) { - }, + var face = this.faces[ i ]; - getObjectByProperty: function ( name, value ) { + var hasMaterial = true; + var hasFaceUv = false; // deprecated + var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined; + var hasFaceNormal = face.normal.length() > 0; + var hasFaceVertexNormal = face.vertexNormals.length > 0; + var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; + var hasFaceVertexColor = face.vertexColors.length > 0; - if ( this[ name ] === value ) return this; + var faceType = 0; - for ( var i = 0, l = this.children.length; i < l; i ++ ) { + faceType = setBit( faceType, 0, 0 ); // isQuad + faceType = setBit( faceType, 1, hasMaterial ); + faceType = setBit( faceType, 2, hasFaceUv ); + faceType = setBit( faceType, 3, hasFaceVertexUv ); + faceType = setBit( faceType, 4, hasFaceNormal ); + faceType = setBit( faceType, 5, hasFaceVertexNormal ); + faceType = setBit( faceType, 6, hasFaceColor ); + faceType = setBit( faceType, 7, hasFaceVertexColor ); - var child = this.children[ i ]; - var object = child.getObjectByProperty( name, value ); + faces.push( faceType ); + faces.push( face.a, face.b, face.c ); + faces.push( face.materialIndex ); - if ( object !== undefined ) { + if ( hasFaceVertexUv ) { - return object; + var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; + + faces.push( + getUvIndex( faceVertexUvs[ 0 ] ), + getUvIndex( faceVertexUvs[ 1 ] ), + getUvIndex( faceVertexUvs[ 2 ] ) + ); } - } + if ( hasFaceNormal ) { - return undefined; + faces.push( getNormalIndex( face.normal ) ); - }, + } - getWorldPosition: function ( optionalTarget ) { + if ( hasFaceVertexNormal ) { - var result = optionalTarget || new Vector3(); + var vertexNormals = face.vertexNormals; - this.updateMatrixWorld( true ); + faces.push( + getNormalIndex( vertexNormals[ 0 ] ), + getNormalIndex( vertexNormals[ 1 ] ), + getNormalIndex( vertexNormals[ 2 ] ) + ); - return result.setFromMatrixPosition( this.matrixWorld ); + } - }, + if ( hasFaceColor ) { - getWorldQuaternion: function () { + faces.push( getColorIndex( face.color ) ); - var position = new Vector3(); - var scale = new Vector3(); + } - return function getWorldQuaternion( optionalTarget ) { + if ( hasFaceVertexColor ) { - var result = optionalTarget || new Quaternion(); + var vertexColors = face.vertexColors; - this.updateMatrixWorld( true ); + faces.push( + getColorIndex( vertexColors[ 0 ] ), + getColorIndex( vertexColors[ 1 ] ), + getColorIndex( vertexColors[ 2 ] ) + ); - this.matrixWorld.decompose( position, result, scale ); + } - return result; + } - }; + function setBit( value, position, enabled ) { - }(), + return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); - getWorldRotation: function () { + } - var quaternion = new Quaternion(); + function getNormalIndex( normal ) { - return function getWorldRotation( optionalTarget ) { + var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); - var result = optionalTarget || new Euler(); + if ( normalsHash[ hash ] !== undefined ) { - this.getWorldQuaternion( quaternion ); + return normalsHash[ hash ]; - return result.setFromQuaternion( quaternion, this.rotation.order, false ); + } - }; + normalsHash[ hash ] = normals.length / 3; + normals.push( normal.x, normal.y, normal.z ); - }(), + return normalsHash[ hash ]; - getWorldScale: function () { + } - var position = new Vector3(); - var quaternion = new Quaternion(); + function getColorIndex( color ) { - return function getWorldScale( optionalTarget ) { + var hash = color.r.toString() + color.g.toString() + color.b.toString(); - var result = optionalTarget || new Vector3(); + if ( colorsHash[ hash ] !== undefined ) { - this.updateMatrixWorld( true ); + return colorsHash[ hash ]; - this.matrixWorld.decompose( position, quaternion, result ); + } - return result; + colorsHash[ hash ] = colors.length; + colors.push( color.getHex() ); - }; + return colorsHash[ hash ]; - }(), + } - getWorldDirection: function () { + function getUvIndex( uv ) { - var quaternion = new Quaternion(); + var hash = uv.x.toString() + uv.y.toString(); - return function getWorldDirection( optionalTarget ) { + if ( uvsHash[ hash ] !== undefined ) { - var result = optionalTarget || new Vector3(); + return uvsHash[ hash ]; - this.getWorldQuaternion( quaternion ); + } - return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); + uvsHash[ hash ] = uvs.length / 2; + uvs.push( uv.x, uv.y ); - }; + return uvsHash[ hash ]; - }(), + } - raycast: function () {}, + data.data = {}; - traverse: function ( callback ) { + data.data.vertices = vertices; + data.data.normals = normals; + if ( colors.length > 0 ) data.data.colors = colors; + if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility + data.data.faces = faces; - callback( this ); + return data; - var children = this.children; + }, - for ( var i = 0, l = children.length; i < l; i ++ ) { + clone: function () { - children[ i ].traverse( callback ); + /* + // Handle primitives - } + var parameters = this.parameters; - }, + if ( parameters !== undefined ) { - traverseVisible: function ( callback ) { + var values = []; - if ( this.visible === false ) return; + for ( var key in parameters ) { - callback( this ); + values.push( parameters[ key ] ); - var children = this.children; + } - for ( var i = 0, l = children.length; i < l; i ++ ) { + var geometry = Object.create( this.constructor.prototype ); + this.constructor.apply( geometry, values ); + return geometry; - children[ i ].traverseVisible( callback ); + } - } + return new this.constructor().copy( this ); + */ + + return new Geometry().copy( this ); }, - traverseAncestors: function ( callback ) { + copy: function ( source ) { - var parent = this.parent; + var i, il, j, jl, k, kl; - if ( parent !== null ) { + // reset - callback( parent ); + this.vertices = []; + this.colors = []; + this.faces = []; + this.faceVertexUvs = [[]]; + this.morphTargets = []; + this.morphNormals = []; + this.skinWeights = []; + this.skinIndices = []; + this.lineDistances = []; + this.boundingBox = null; + this.boundingSphere = null; - parent.traverseAncestors( callback ); + // name + + this.name = source.name; + + // vertices + + var vertices = source.vertices; + + for ( i = 0, il = vertices.length; i < il; i ++ ) { + + this.vertices.push( vertices[ i ].clone() ); } - }, + // colors - updateMatrix: function () { + var colors = source.colors; - this.matrix.compose( this.position, this.quaternion, this.scale ); + for ( i = 0, il = colors.length; i < il; i ++ ) { - this.matrixWorldNeedsUpdate = true; + this.colors.push( colors[ i ].clone() ); - }, + } - updateMatrixWorld: function ( force ) { + // faces - if ( this.matrixAutoUpdate ) this.updateMatrix(); + var faces = source.faces; - if ( this.matrixWorldNeedsUpdate || force ) { + for ( i = 0, il = faces.length; i < il; i ++ ) { - if ( this.parent === null ) { + this.faces.push( faces[ i ].clone() ); - this.matrixWorld.copy( this.matrix ); + } - } else { + // face vertex uvs - this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); + for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { + + var faceVertexUvs = source.faceVertexUvs[ i ]; + + if ( this.faceVertexUvs[ i ] === undefined ) { + + this.faceVertexUvs[ i ] = []; } - this.matrixWorldNeedsUpdate = false; + for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { - force = true; + var uvs = faceVertexUvs[ j ], uvsCopy = []; - } + for ( k = 0, kl = uvs.length; k < kl; k ++ ) { - // update children + var uv = uvs[ k ]; - var children = this.children; + uvsCopy.push( uv.clone() ); - for ( var i = 0, l = children.length; i < l; i ++ ) { + } - children[ i ].updateMatrixWorld( force ); + this.faceVertexUvs[ i ].push( uvsCopy ); + + } } - }, + // morph targets - toJSON: function ( meta ) { + var morphTargets = source.morphTargets; - // meta is '' when called from JSON.stringify - var isRootObject = ( meta === undefined || meta === '' ); + for ( i = 0, il = morphTargets.length; i < il; i ++ ) { - var output = {}; + var morphTarget = {}; + morphTarget.name = morphTargets[ i ].name; - // meta is a hash used to collect geometries, materials. - // not providing it implies that this is the root object - // being serialized. - if ( isRootObject ) { + // vertices - // initialize meta obj - meta = { - geometries: {}, - materials: {}, - textures: {}, - images: {} - }; + if ( morphTargets[ i ].vertices !== undefined ) { - output.metadata = { - version: 4.5, - type: 'Object', - generator: 'Object3D.toJSON' - }; + morphTarget.vertices = []; - } + for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) { - // standard Object3D serialization + morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() ); - var object = {}; + } - object.uuid = this.uuid; - object.type = this.type; + } - if ( this.name !== '' ) object.name = this.name; - if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; - if ( this.castShadow === true ) object.castShadow = true; - if ( this.receiveShadow === true ) object.receiveShadow = true; - if ( this.visible === false ) object.visible = false; + // normals - object.matrix = this.matrix.toArray(); + if ( morphTargets[ i ].normals !== undefined ) { - // + morphTarget.normals = []; - function serialize( library, element ) { + for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) { - if ( library[ element.uuid ] === undefined ) { + morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() ); - library[ element.uuid ] = element.toJSON( meta ); + } } - return element.uuid; + this.morphTargets.push( morphTarget ); } - if ( this.geometry !== undefined ) { + // morph normals - object.geometry = serialize( meta.geometries, this.geometry ); + var morphNormals = source.morphNormals; - } + for ( i = 0, il = morphNormals.length; i < il; i ++ ) { - if ( this.material !== undefined ) { + var morphNormal = {}; - if ( Array.isArray( this.material ) ) { + // vertex normals - var uuids = []; + if ( morphNormals[ i ].vertexNormals !== undefined ) { - for ( var i = 0, l = this.material.length; i < l; i ++ ) { + morphNormal.vertexNormals = []; - uuids.push( serialize( meta.materials, this.material[ i ] ) ); + for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) { - } + var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ]; + var destVertexNormal = {}; - object.material = uuids; + destVertexNormal.a = srcVertexNormal.a.clone(); + destVertexNormal.b = srcVertexNormal.b.clone(); + destVertexNormal.c = srcVertexNormal.c.clone(); - } else { + morphNormal.vertexNormals.push( destVertexNormal ); - object.material = serialize( meta.materials, this.material ); + } } - } + // face normals - // + if ( morphNormals[ i ].faceNormals !== undefined ) { - if ( this.children.length > 0 ) { + morphNormal.faceNormals = []; - object.children = []; + for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) { - for ( var i = 0; i < this.children.length; i ++ ) { + morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() ); - object.children.push( this.children[ i ].toJSON( meta ).object ); + } } - } + this.morphNormals.push( morphNormal ); - if ( isRootObject ) { + } - var geometries = extractFromCache( meta.geometries ); - var materials = extractFromCache( meta.materials ); - var textures = extractFromCache( meta.textures ); - var images = extractFromCache( meta.images ); + // skin weights - if ( geometries.length > 0 ) output.geometries = geometries; - if ( materials.length > 0 ) output.materials = materials; - if ( textures.length > 0 ) output.textures = textures; - if ( images.length > 0 ) output.images = images; + var skinWeights = source.skinWeights; - } + for ( i = 0, il = skinWeights.length; i < il; i ++ ) { - output.object = object; + this.skinWeights.push( skinWeights[ i ].clone() ); - return output; + } - // extract data from the cache hash - // remove metadata on each item - // and return as array - function extractFromCache( cache ) { + // skin indices - var values = []; - for ( var key in cache ) { + var skinIndices = source.skinIndices; - var data = cache[ key ]; - delete data.metadata; - values.push( data ); + for ( i = 0, il = skinIndices.length; i < il; i ++ ) { - } - return values; + this.skinIndices.push( skinIndices[ i ].clone() ); } - }, + // line distances - clone: function ( recursive ) { + var lineDistances = source.lineDistances; - return new this.constructor().copy( this, recursive ); + for ( i = 0, il = lineDistances.length; i < il; i ++ ) { - }, + this.lineDistances.push( lineDistances[ i ] ); - copy: function ( source, recursive ) { + } - if ( recursive === undefined ) recursive = true; + // bounding box - this.name = source.name; + var boundingBox = source.boundingBox; - this.up.copy( source.up ); + if ( boundingBox !== null ) { - this.position.copy( source.position ); - this.quaternion.copy( source.quaternion ); - this.scale.copy( source.scale ); + this.boundingBox = boundingBox.clone(); - this.matrix.copy( source.matrix ); - this.matrixWorld.copy( source.matrixWorld ); + } - this.matrixAutoUpdate = source.matrixAutoUpdate; - this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + // bounding sphere - this.layers.mask = source.layers.mask; - this.visible = source.visible; + var boundingSphere = source.boundingSphere; - this.castShadow = source.castShadow; - this.receiveShadow = source.receiveShadow; + if ( boundingSphere !== null ) { - this.frustumCulled = source.frustumCulled; - this.renderOrder = source.renderOrder; + this.boundingSphere = boundingSphere.clone(); - this.userData = JSON.parse( JSON.stringify( source.userData ) ); + } - if ( recursive === true ) { + // update flags - for ( var i = 0; i < source.children.length; i ++ ) { + this.elementsNeedUpdate = source.elementsNeedUpdate; + this.verticesNeedUpdate = source.verticesNeedUpdate; + this.uvsNeedUpdate = source.uvsNeedUpdate; + this.normalsNeedUpdate = source.normalsNeedUpdate; + this.colorsNeedUpdate = source.colorsNeedUpdate; + this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate; + this.groupsNeedUpdate = source.groupsNeedUpdate; - var child = source.children[ i ]; - this.add( child.clone() ); + return this; - } + }, - } + dispose: function () { - return this; + this.dispatchEvent( { type: 'dispose' } ); } @@ -10815,1848 +10318,1775 @@ /** * @author mrdoob / http://mrdoob.com/ - * @author mikael emtinger / http://gomo.se/ - * @author WestLangley / http://github.com/WestLangley - */ + */ - function Camera() { + function BufferAttribute( array, itemSize, normalized ) { - Object3D.call( this ); + if ( Array.isArray( array ) ) { - this.type = 'Camera'; + throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); - this.matrixWorldInverse = new Matrix4(); - this.projectionMatrix = new Matrix4(); + } - } + this.name = ''; - Camera.prototype = Object.assign( Object.create( Object3D.prototype ), { + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized === true; - constructor: Camera, + this.dynamic = false; + this.updateRange = { offset: 0, count: - 1 }; - isCamera: true, + this.version = 0; - copy: function ( source, recursive ) { + } - Object3D.prototype.copy.call( this, source, recursive ); + Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', { - this.matrixWorldInverse.copy( source.matrixWorldInverse ); - this.projectionMatrix.copy( source.projectionMatrix ); + set: function ( value ) { - return this; + if ( value === true ) this.version ++; - }, + } - getWorldDirection: function () { + } ); - var quaternion = new Quaternion(); + Object.assign( BufferAttribute.prototype, { - return function getWorldDirection( optionalTarget ) { + isBufferAttribute: true, - var result = optionalTarget || new Vector3(); + onUploadCallback: function () {}, - this.getWorldQuaternion( quaternion ); + setArray: function ( array ) { - return result.set( 0, 0, - 1 ).applyQuaternion( quaternion ); + if ( Array.isArray( array ) ) { - }; + throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); - }(), + } - updateMatrixWorld: function ( force ) { + this.count = array !== undefined ? array.length / this.itemSize : 0; + this.array = array; - Object3D.prototype.updateMatrixWorld.call( this, force ); + }, - this.matrixWorldInverse.getInverse( this.matrixWorld ); + setDynamic: function ( value ) { - }, + this.dynamic = value; - clone: function () { + return this; - return new this.constructor().copy( this ); + }, - } + copy: function ( source ) { - } ); + this.array = new source.array.constructor( source.array ); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; - /** - * @author alteredq / http://alteredqualia.com/ - * @author arose / http://github.com/arose - */ + this.dynamic = source.dynamic; - function OrthographicCamera( left, right, top, bottom, near, far ) { + return this; - Camera.call( this ); + }, - this.type = 'OrthographicCamera'; + copyAt: function ( index1, attribute, index2 ) { - this.zoom = 1; - this.view = null; + index1 *= this.itemSize; + index2 *= attribute.itemSize; - this.left = left; - this.right = right; - this.top = top; - this.bottom = bottom; + for ( var i = 0, l = this.itemSize; i < l; i ++ ) { - this.near = ( near !== undefined ) ? near : 0.1; - this.far = ( far !== undefined ) ? far : 2000; + this.array[ index1 + i ] = attribute.array[ index2 + i ]; - this.updateProjectionMatrix(); + } - } + return this; - OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), { + }, - constructor: OrthographicCamera, + copyArray: function ( array ) { - isOrthographicCamera: true, + this.array.set( array ); - copy: function ( source, recursive ) { + return this; - Camera.prototype.copy.call( this, source, recursive ); + }, - this.left = source.left; - this.right = source.right; - this.top = source.top; - this.bottom = source.bottom; - this.near = source.near; - this.far = source.far; + copyColorsArray: function ( colors ) { - this.zoom = source.zoom; - this.view = source.view === null ? null : Object.assign( {}, source.view ); + var array = this.array, offset = 0; - return this; + for ( var i = 0, l = colors.length; i < l; i ++ ) { - }, + var color = colors[ i ]; - setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) { + if ( color === undefined ) { - this.view = { - fullWidth: fullWidth, - fullHeight: fullHeight, - offsetX: x, - offsetY: y, - width: width, - height: height - }; + console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); + color = new Color(); - this.updateProjectionMatrix(); + } - }, + array[ offset ++ ] = color.r; + array[ offset ++ ] = color.g; + array[ offset ++ ] = color.b; - clearViewOffset: function() { + } - this.view = null; - this.updateProjectionMatrix(); + return this; }, - updateProjectionMatrix: function () { + copyVector2sArray: function ( vectors ) { - var dx = ( this.right - this.left ) / ( 2 * this.zoom ); - var dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); - var cx = ( this.right + this.left ) / 2; - var cy = ( this.top + this.bottom ) / 2; + var array = this.array, offset = 0; - var left = cx - dx; - var right = cx + dx; - var top = cy + dy; - var bottom = cy - dy; + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - if ( this.view !== null ) { + var vector = vectors[ i ]; - var zoomW = this.zoom / ( this.view.width / this.view.fullWidth ); - var zoomH = this.zoom / ( this.view.height / this.view.fullHeight ); - var scaleW = ( this.right - this.left ) / this.view.width; - var scaleH = ( this.top - this.bottom ) / this.view.height; + if ( vector === undefined ) { - left += scaleW * ( this.view.offsetX / zoomW ); - right = left + scaleW * ( this.view.width / zoomW ); - top -= scaleH * ( this.view.offsetY / zoomH ); - bottom = top - scaleH * ( this.view.height / zoomH ); + console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); + vector = new Vector2(); + + } + + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; } - this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); + return this; }, - toJSON: function ( meta ) { + copyVector3sArray: function ( vectors ) { - var data = Object3D.prototype.toJSON.call( this, meta ); + var array = this.array, offset = 0; - data.object.zoom = this.zoom; - data.object.left = this.left; - data.object.right = this.right; - data.object.top = this.top; - data.object.bottom = this.bottom; - data.object.near = this.near; - data.object.far = this.far; + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - - return data; + var vector = vectors[ i ]; - } + if ( vector === undefined ) { - } ); + console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); + vector = new Vector3(); - /** - * @author mrdoob / http://mrdoob.com/ - * @author greggman / http://games.greggman.com/ - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author tschw - */ + } - function PerspectiveCamera( fov, aspect, near, far ) { + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; + array[ offset ++ ] = vector.z; - Camera.call( this ); + } - this.type = 'PerspectiveCamera'; + return this; - this.fov = fov !== undefined ? fov : 50; - this.zoom = 1; + }, - this.near = near !== undefined ? near : 0.1; - this.far = far !== undefined ? far : 2000; - this.focus = 10; + copyVector4sArray: function ( vectors ) { - this.aspect = aspect !== undefined ? aspect : 1; - this.view = null; + var array = this.array, offset = 0; - this.filmGauge = 35; // width of the film (default in millimeters) - this.filmOffset = 0; // horizontal film offset (same unit as gauge) + for ( var i = 0, l = vectors.length; i < l; i ++ ) { - this.updateProjectionMatrix(); + var vector = vectors[ i ]; - } + if ( vector === undefined ) { - PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { + console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); + vector = new Vector4(); - constructor: PerspectiveCamera, + } - isPerspectiveCamera: true, + array[ offset ++ ] = vector.x; + array[ offset ++ ] = vector.y; + array[ offset ++ ] = vector.z; + array[ offset ++ ] = vector.w; - copy: function ( source, recursive ) { + } - Camera.prototype.copy.call( this, source, recursive ); + return this; - this.fov = source.fov; - this.zoom = source.zoom; + }, - this.near = source.near; - this.far = source.far; - this.focus = source.focus; + set: function ( value, offset ) { - this.aspect = source.aspect; - this.view = source.view === null ? null : Object.assign( {}, source.view ); + if ( offset === undefined ) offset = 0; - this.filmGauge = source.filmGauge; - this.filmOffset = source.filmOffset; + this.array.set( value, offset ); return this; }, - /** - * Sets the FOV by focal length in respect to the current .filmGauge. - * - * The default film gauge is 35, so that the focal length can be specified for - * a 35mm (full frame) camera. - * - * Values for focal length and film gauge must have the same unit. - */ - setFocalLength: function ( focalLength ) { - - // see http://www.bobatkins.com/photography/technical/field_of_view.html - var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + getX: function ( index ) { - this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); - this.updateProjectionMatrix(); + return this.array[ index * this.itemSize ]; }, - /** - * Calculates the focal length from the current .fov and .filmGauge. - */ - getFocalLength: function () { + setX: function ( index, x ) { - var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov ); + this.array[ index * this.itemSize ] = x; - return 0.5 * this.getFilmHeight() / vExtentSlope; + return this; }, - getEffectiveFOV: function () { + getY: function ( index ) { - return _Math.RAD2DEG * 2 * Math.atan( - Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); + return this.array[ index * this.itemSize + 1 ]; }, - getFilmWidth: function () { + setY: function ( index, y ) { - // film not completely covered in portrait format (aspect < 1) - return this.filmGauge * Math.min( this.aspect, 1 ); + this.array[ index * this.itemSize + 1 ] = y; + + return this; }, - getFilmHeight: function () { + getZ: function ( index ) { - // film not completely covered in landscape format (aspect > 1) - return this.filmGauge / Math.max( this.aspect, 1 ); + return this.array[ index * this.itemSize + 2 ]; }, - /** - * Sets an offset in a larger frustum. This is useful for multi-window or - * multi-monitor/multi-machine setups. - * - * For example, if you have 3x2 monitors and each monitor is 1920x1080 and - * the monitors are in grid like this - * - * +---+---+---+ - * | A | B | C | - * +---+---+---+ - * | D | E | F | - * +---+---+---+ - * - * then for each monitor you would call it like this - * - * var w = 1920; - * var h = 1080; - * var fullWidth = w * 3; - * var fullHeight = h * 2; - * - * --A-- - * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); - * --B-- - * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); - * --C-- - * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); - * --D-- - * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); - * --E-- - * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); - * --F-- - * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); - * - * Note there is no reason monitors have to be the same size or in a grid. - */ - setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { + setZ: function ( index, z ) { - this.aspect = fullWidth / fullHeight; + this.array[ index * this.itemSize + 2 ] = z; - this.view = { - fullWidth: fullWidth, - fullHeight: fullHeight, - offsetX: x, - offsetY: y, - width: width, - height: height - }; + return this; - this.updateProjectionMatrix(); + }, + + getW: function ( index ) { + + return this.array[ index * this.itemSize + 3 ]; }, - clearViewOffset: function () { + setW: function ( index, w ) { - this.view = null; - this.updateProjectionMatrix(); + this.array[ index * this.itemSize + 3 ] = w; + + return this; }, - updateProjectionMatrix: function () { + setXY: function ( index, x, y ) { - var near = this.near, - top = near * Math.tan( - _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom, - height = 2 * top, - width = this.aspect * height, - left = - 0.5 * width, - view = this.view; + index *= this.itemSize; - if ( view !== null ) { + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; - var fullWidth = view.fullWidth, - fullHeight = view.fullHeight; + return this; - left += view.offsetX * width / fullWidth; - top -= view.offsetY * height / fullHeight; - width *= view.width / fullWidth; - height *= view.height / fullHeight; + }, - } + setXYZ: function ( index, x, y, z ) { - var skew = this.filmOffset; - if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); + index *= this.itemSize; - this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far ); + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + + return this; }, - toJSON: function ( meta ) { + setXYZW: function ( index, x, y, z, w ) { - var data = Object3D.prototype.toJSON.call( this, meta ); + index *= this.itemSize; - data.object.fov = this.fov; - data.object.zoom = this.zoom; + this.array[ index + 0 ] = x; + this.array[ index + 1 ] = y; + this.array[ index + 2 ] = z; + this.array[ index + 3 ] = w; - data.object.near = this.near; - data.object.far = this.far; - data.object.focus = this.focus; + return this; - data.object.aspect = this.aspect; + }, - if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); + onUpload: function ( callback ) { - data.object.filmGauge = this.filmGauge; - data.object.filmOffset = this.filmOffset; + this.onUploadCallback = callback; - return data; + return this; + + }, + + clone: function () { + + return new this.constructor( this.array, this.itemSize ).copy( this ); } } ); - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + // - function Face3( a, b, c, normal, color, materialIndex ) { + function Int8BufferAttribute( array, itemSize, normalized ) { - this.a = a; - this.b = b; - this.c = c; + BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized ); - this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3(); - this.vertexNormals = Array.isArray( normal ) ? normal : []; + } - this.color = ( color && color.isColor ) ? color : new Color(); - this.vertexColors = Array.isArray( color ) ? color : []; + Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); + Int8BufferAttribute.prototype.constructor = Int8BufferAttribute; - this.materialIndex = materialIndex !== undefined ? materialIndex : 0; + + function Uint8BufferAttribute( array, itemSize, normalized ) { + + BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized ); } - Object.assign( Face3.prototype, { + Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); + Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute; - clone: function () { - return new this.constructor().copy( this ); + function Uint8ClampedBufferAttribute( array, itemSize, normalized ) { - }, + BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized ); - copy: function ( source ) { + } - this.a = source.a; - this.b = source.b; - this.c = source.c; + Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype ); + Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute; - this.normal.copy( source.normal ); - this.color.copy( source.color ); - this.materialIndex = source.materialIndex; + function Int16BufferAttribute( array, itemSize, normalized ) { - for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { + BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized ); - this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); + } - } + Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); + Int16BufferAttribute.prototype.constructor = Int16BufferAttribute; - for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { - this.vertexColors[ i ] = source.vertexColors[ i ].clone(); + function Uint16BufferAttribute( array, itemSize, normalized ) { - } + BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized ); - return this; + } - } + Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); + Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute; - } ); - /** - * @author mrdoob / http://mrdoob.com/ - * @author kile / http://kile.stravaganza.org/ - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author bhouston / http://clara.io - */ + function Int32BufferAttribute( array, itemSize, normalized ) { - var count = 0; - function GeometryIdCount() { return count++; } + BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized ); - function Geometry() { + } + + Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); + Int32BufferAttribute.prototype.constructor = Int32BufferAttribute; - Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); - this.uuid = _Math.generateUUID(); + function Uint32BufferAttribute( array, itemSize, normalized ) { - this.name = ''; - this.type = 'Geometry'; + BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized ); + + } + + Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); + Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute; + + + function Float32BufferAttribute( array, itemSize, normalized ) { + + BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized ); + + } + + Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); + Float32BufferAttribute.prototype.constructor = Float32BufferAttribute; + + + function Float64BufferAttribute( array, itemSize, normalized ) { + + BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized ); + + } + + Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); + Float64BufferAttribute.prototype.constructor = Float64BufferAttribute; + + /** + * @author mrdoob / http://mrdoob.com/ + */ + + function DirectGeometry() { this.vertices = []; + this.normals = []; this.colors = []; - this.faces = []; - this.faceVertexUvs = [[]]; + this.uvs = []; + this.uvs2 = []; - this.morphTargets = []; - this.morphNormals = []; + this.groups = []; + + this.morphTargets = {}; this.skinWeights = []; this.skinIndices = []; - this.lineDistances = []; + // this.lineDistances = []; this.boundingBox = null; this.boundingSphere = null; // update flags - this.elementsNeedUpdate = false; this.verticesNeedUpdate = false; - this.uvsNeedUpdate = false; this.normalsNeedUpdate = false; this.colorsNeedUpdate = false; - this.lineDistancesNeedUpdate = false; + this.uvsNeedUpdate = false; this.groupsNeedUpdate = false; } - Object.assign( Geometry.prototype, EventDispatcher.prototype, { - - isGeometry: true, + Object.assign( DirectGeometry.prototype, { - applyMatrix: function ( matrix ) { + computeGroups: function ( geometry ) { - var normalMatrix = new Matrix3().getNormalMatrix( matrix ); + var group; + var groups = []; + var materialIndex = undefined; - for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { + var faces = geometry.faces; - var vertex = this.vertices[ i ]; - vertex.applyMatrix4( matrix ); + for ( var i = 0; i < faces.length; i ++ ) { - } + var face = faces[ i ]; - for ( var i = 0, il = this.faces.length; i < il; i ++ ) { + // materials - var face = this.faces[ i ]; - face.normal.applyMatrix3( normalMatrix ).normalize(); + if ( face.materialIndex !== materialIndex ) { - for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { + materialIndex = face.materialIndex; - face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); + if ( group !== undefined ) { - } + group.count = ( i * 3 ) - group.start; + groups.push( group ); - } + } - if ( this.boundingBox !== null ) { + group = { + start: i * 3, + materialIndex: materialIndex + }; - this.computeBoundingBox(); + } } - if ( this.boundingSphere !== null ) { + if ( group !== undefined ) { - this.computeBoundingSphere(); + group.count = ( i * 3 ) - group.start; + groups.push( group ); } - this.verticesNeedUpdate = true; - this.normalsNeedUpdate = true; - - return this; + this.groups = groups; }, - rotateX: function () { + fromGeometry: function ( geometry ) { - // rotate geometry around world x-axis + var faces = geometry.faces; + var vertices = geometry.vertices; + var faceVertexUvs = geometry.faceVertexUvs; - var m1 = new Matrix4(); + var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0; + var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0; - return function rotateX( angle ) { + // morphs - m1.makeRotationX( angle ); + var morphTargets = geometry.morphTargets; + var morphTargetsLength = morphTargets.length; - this.applyMatrix( m1 ); + var morphTargetsPosition; - return this; + if ( morphTargetsLength > 0 ) { - }; + morphTargetsPosition = []; - }(), + for ( var i = 0; i < morphTargetsLength; i ++ ) { - rotateY: function () { + morphTargetsPosition[ i ] = []; - // rotate geometry around world y-axis + } - var m1 = new Matrix4(); + this.morphTargets.position = morphTargetsPosition; - return function rotateY( angle ) { + } - m1.makeRotationY( angle ); + var morphNormals = geometry.morphNormals; + var morphNormalsLength = morphNormals.length; - this.applyMatrix( m1 ); + var morphTargetsNormal; - return this; + if ( morphNormalsLength > 0 ) { - }; + morphTargetsNormal = []; - }(), + for ( var i = 0; i < morphNormalsLength; i ++ ) { - rotateZ: function () { + morphTargetsNormal[ i ] = []; - // rotate geometry around world z-axis + } - var m1 = new Matrix4(); + this.morphTargets.normal = morphTargetsNormal; - return function rotateZ( angle ) { + } - m1.makeRotationZ( angle ); + // skins - this.applyMatrix( m1 ); + var skinIndices = geometry.skinIndices; + var skinWeights = geometry.skinWeights; - return this; + var hasSkinIndices = skinIndices.length === vertices.length; + var hasSkinWeights = skinWeights.length === vertices.length; - }; + // - }(), + for ( var i = 0; i < faces.length; i ++ ) { - translate: function () { + var face = faces[ i ]; - // translate geometry + this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); - var m1 = new Matrix4(); + var vertexNormals = face.vertexNormals; - return function translate( x, y, z ) { + if ( vertexNormals.length === 3 ) { - m1.makeTranslation( x, y, z ); + this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); - this.applyMatrix( m1 ); + } else { - return this; + var normal = face.normal; - }; + this.normals.push( normal, normal, normal ); - }(), + } - scale: function () { + var vertexColors = face.vertexColors; - // scale geometry + if ( vertexColors.length === 3 ) { - var m1 = new Matrix4(); + this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); - return function scale( x, y, z ) { + } else { - m1.makeScale( x, y, z ); + var color = face.color; - this.applyMatrix( m1 ); + this.colors.push( color, color, color ); - return this; + } - }; + if ( hasFaceVertexUv === true ) { - }(), + var vertexUvs = faceVertexUvs[ 0 ][ i ]; - lookAt: function () { + if ( vertexUvs !== undefined ) { - var obj = new Object3D(); + this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); - return function lookAt( vector ) { + } else { - obj.lookAt( vector ); + console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); - obj.updateMatrix(); + this.uvs.push( new Vector2(), new Vector2(), new Vector2() ); - this.applyMatrix( obj.matrix ); + } - }; + } - }(), + if ( hasFaceVertexUv2 === true ) { - fromBufferGeometry: function ( geometry ) { + var vertexUvs = faceVertexUvs[ 1 ][ i ]; - var scope = this; + if ( vertexUvs !== undefined ) { - var indices = geometry.index !== null ? geometry.index.array : undefined; - var attributes = geometry.attributes; + this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); - var positions = attributes.position.array; - var normals = attributes.normal !== undefined ? attributes.normal.array : undefined; - var colors = attributes.color !== undefined ? attributes.color.array : undefined; - var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined; - var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined; + } else { - if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = []; + console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); - var tempNormals = []; - var tempUVs = []; - var tempUVs2 = []; + this.uvs2.push( new Vector2(), new Vector2(), new Vector2() ); - for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) { + } - scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) ); + } - if ( normals !== undefined ) { + // morphs - tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) ); + for ( var j = 0; j < morphTargetsLength; j ++ ) { + + var morphTarget = morphTargets[ j ].vertices; + + morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); } - if ( colors !== undefined ) { + for ( var j = 0; j < morphNormalsLength; j ++ ) { - scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); + var morphNormal = morphNormals[ j ].vertexNormals[ i ]; + + morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c ); } - if ( uvs !== undefined ) { + // skins - tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) ); + if ( hasSkinIndices ) { + + this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); } - if ( uvs2 !== undefined ) { + if ( hasSkinWeights ) { - tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) ); + this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); } } - function addFace( a, b, c, materialIndex ) { + this.computeGroups( geometry ); - var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : []; - var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : []; + this.verticesNeedUpdate = geometry.verticesNeedUpdate; + this.normalsNeedUpdate = geometry.normalsNeedUpdate; + this.colorsNeedUpdate = geometry.colorsNeedUpdate; + this.uvsNeedUpdate = geometry.uvsNeedUpdate; + this.groupsNeedUpdate = geometry.groupsNeedUpdate; - var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); + return this; - scope.faces.push( face ); + } - if ( uvs !== undefined ) { + } ); - scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function arrayMax( array ) { - if ( uvs2 !== undefined ) { + if ( array.length === 0 ) return - Infinity; - scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] ); + var max = array[ 0 ]; - } + for ( var i = 1, l = array.length; i < l; ++ i ) { - } + if ( array[ i ] > max ) max = array[ i ]; - var groups = geometry.groups; + } - if ( groups.length > 0 ) { + return max; - for ( var i = 0; i < groups.length; i ++ ) { + } - var group = groups[ i ]; + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - var start = group.start; - var count = group.count; + var bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id - for ( var j = start, jl = start + count; j < jl; j += 3 ) { + function BufferGeometry() { - if ( indices !== undefined ) { + Object.defineProperty( this, 'id', { value: bufferGeometryId += 2 } ); - addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex ); + this.uuid = _Math.generateUUID(); - } else { + this.name = ''; + this.type = 'BufferGeometry'; - addFace( j, j + 1, j + 2, group.materialIndex ); + this.index = null; + this.attributes = {}; - } + this.morphAttributes = {}; - } + this.groups = []; - } + this.boundingBox = null; + this.boundingSphere = null; - } else { + this.drawRange = { start: 0, count: Infinity }; - if ( indices !== undefined ) { + } - for ( var i = 0; i < indices.length; i += 3 ) { + BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { - addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); + constructor: BufferGeometry, - } + isBufferGeometry: true, - } else { + getIndex: function () { - for ( var i = 0; i < positions.length / 3; i += 3 ) { + return this.index; - addFace( i, i + 1, i + 2 ); + }, - } + setIndex: function ( index ) { - } + if ( Array.isArray( index ) ) { + + this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 ); + + } else { + + this.index = index; } - this.computeFaceNormals(); + }, - if ( geometry.boundingBox !== null ) { + addAttribute: function ( name, attribute ) { - this.boundingBox = geometry.boundingBox.clone(); + if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) { - } + console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); - if ( geometry.boundingSphere !== null ) { + this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); - this.boundingSphere = geometry.boundingSphere.clone(); + return; } - return this; - - }, + if ( name === 'index' ) { - center: function () { + console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); + this.setIndex( attribute ); - this.computeBoundingBox(); + return; - var offset = this.boundingBox.getCenter().negate(); + } - this.translate( offset.x, offset.y, offset.z ); + this.attributes[ name ] = attribute; - return offset; + return this; }, - normalize: function () { - - this.computeBoundingSphere(); + getAttribute: function ( name ) { - var center = this.boundingSphere.center; - var radius = this.boundingSphere.radius; + return this.attributes[ name ]; - var s = radius === 0 ? 1 : 1.0 / radius; + }, - var matrix = new Matrix4(); - matrix.set( - s, 0, 0, - s * center.x, - 0, s, 0, - s * center.y, - 0, 0, s, - s * center.z, - 0, 0, 0, 1 - ); + removeAttribute: function ( name ) { - this.applyMatrix( matrix ); + delete this.attributes[ name ]; return this; }, - computeFaceNormals: function () { + addGroup: function ( start, count, materialIndex ) { - var cb = new Vector3(), ab = new Vector3(); + this.groups.push( { - for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { + start: start, + count: count, + materialIndex: materialIndex !== undefined ? materialIndex : 0 - var face = this.faces[ f ]; + } ); - var vA = this.vertices[ face.a ]; - var vB = this.vertices[ face.b ]; - var vC = this.vertices[ face.c ]; + }, - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + clearGroups: function () { - cb.normalize(); + this.groups = []; - face.normal.copy( cb ); + }, - } + setDrawRange: function ( start, count ) { + + this.drawRange.start = start; + this.drawRange.count = count; }, - computeVertexNormals: function ( areaWeighted ) { + applyMatrix: function ( matrix ) { - if ( areaWeighted === undefined ) areaWeighted = true; + var position = this.attributes.position; - var v, vl, f, fl, face, vertices; + if ( position !== undefined ) { - vertices = new Array( this.vertices.length ); + matrix.applyToBufferAttribute( position ); + position.needsUpdate = true; - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + } - vertices[ v ] = new Vector3(); + var normal = this.attributes.normal; - } + if ( normal !== undefined ) { - if ( areaWeighted ) { + var normalMatrix = new Matrix3().getNormalMatrix( matrix ); - // vertex normals weighted by triangle areas - // http://www.iquilezles.org/www/articles/normals/normals.htm + normalMatrix.applyToBufferAttribute( normal ); + normal.needsUpdate = true; - var vA, vB, vC; - var cb = new Vector3(), ab = new Vector3(); + } - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + if ( this.boundingBox !== null ) { - face = this.faces[ f ]; + this.computeBoundingBox(); - vA = this.vertices[ face.a ]; - vB = this.vertices[ face.b ]; - vC = this.vertices[ face.c ]; + } - cb.subVectors( vC, vB ); - ab.subVectors( vA, vB ); - cb.cross( ab ); + if ( this.boundingSphere !== null ) { - vertices[ face.a ].add( cb ); - vertices[ face.b ].add( cb ); - vertices[ face.c ].add( cb ); + this.computeBoundingSphere(); - } + } - } else { + return this; - this.computeFaceNormals(); + }, - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + rotateX: function () { - face = this.faces[ f ]; + // rotate geometry around world x-axis - vertices[ face.a ].add( face.normal ); - vertices[ face.b ].add( face.normal ); - vertices[ face.c ].add( face.normal ); + var m1 = new Matrix4(); - } + return function rotateX( angle ) { - } + m1.makeRotationX( angle ); - for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { + this.applyMatrix( m1 ); - vertices[ v ].normalize(); + return this; - } + }; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + }(), - face = this.faces[ f ]; + rotateY: function () { - var vertexNormals = face.vertexNormals; + // rotate geometry around world y-axis - if ( vertexNormals.length === 3 ) { + var m1 = new Matrix4(); - vertexNormals[ 0 ].copy( vertices[ face.a ] ); - vertexNormals[ 1 ].copy( vertices[ face.b ] ); - vertexNormals[ 2 ].copy( vertices[ face.c ] ); + return function rotateY( angle ) { - } else { + m1.makeRotationY( angle ); - vertexNormals[ 0 ] = vertices[ face.a ].clone(); - vertexNormals[ 1 ] = vertices[ face.b ].clone(); - vertexNormals[ 2 ] = vertices[ face.c ].clone(); + this.applyMatrix( m1 ); - } + return this; - } + }; - if ( this.faces.length > 0 ) { + }(), - this.normalsNeedUpdate = true; + rotateZ: function () { - } + // rotate geometry around world z-axis - }, + var m1 = new Matrix4(); - computeFlatVertexNormals: function () { + return function rotateZ( angle ) { - var f, fl, face; + m1.makeRotationZ( angle ); - this.computeFaceNormals(); + this.applyMatrix( m1 ); - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + return this; - face = this.faces[ f ]; + }; - var vertexNormals = face.vertexNormals; + }(), - if ( vertexNormals.length === 3 ) { + translate: function () { - vertexNormals[ 0 ].copy( face.normal ); - vertexNormals[ 1 ].copy( face.normal ); - vertexNormals[ 2 ].copy( face.normal ); + // translate geometry - } else { + var m1 = new Matrix4(); - vertexNormals[ 0 ] = face.normal.clone(); - vertexNormals[ 1 ] = face.normal.clone(); - vertexNormals[ 2 ] = face.normal.clone(); + return function translate( x, y, z ) { - } + m1.makeTranslation( x, y, z ); - } + this.applyMatrix( m1 ); - if ( this.faces.length > 0 ) { + return this; - this.normalsNeedUpdate = true; + }; - } + }(), - }, + scale: function () { - computeMorphNormals: function () { + // scale geometry - var i, il, f, fl, face; + var m1 = new Matrix4(); - // save original normals - // - create temp variables on first access - // otherwise just copy (for faster repeated calls) + return function scale( x, y, z ) { - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + m1.makeScale( x, y, z ); - face = this.faces[ f ]; + this.applyMatrix( m1 ); - if ( ! face.__originalFaceNormal ) { + return this; - face.__originalFaceNormal = face.normal.clone(); + }; - } else { + }(), - face.__originalFaceNormal.copy( face.normal ); + lookAt: function () { - } + var obj = new Object3D(); - if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = []; + return function lookAt( vector ) { - for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { + obj.lookAt( vector ); - if ( ! face.__originalVertexNormals[ i ] ) { + obj.updateMatrix(); - face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); + this.applyMatrix( obj.matrix ); - } else { + }; - face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); + }(), - } + center: function () { - } + var offset = new Vector3(); - } + return function center() { - // use temp geometry to compute face and vertex normals for each morph + this.computeBoundingBox(); - var tmpGeo = new Geometry(); - tmpGeo.faces = this.faces; + this.boundingBox.getCenter( offset ).negate(); - for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { + this.translate( offset.x, offset.y, offset.z ); - // create on first access + return this; - if ( ! this.morphNormals[ i ] ) { + }; - this.morphNormals[ i ] = {}; - this.morphNormals[ i ].faceNormals = []; - this.morphNormals[ i ].vertexNormals = []; + }(), - var dstNormalsFace = this.morphNormals[ i ].faceNormals; - var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; + setFromObject: function ( object ) { - var faceNormal, vertexNormals; + // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + var geometry = object.geometry; - faceNormal = new Vector3(); - vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; + if ( object.isPoints || object.isLine ) { - dstNormalsFace.push( faceNormal ); - dstNormalsVertex.push( vertexNormals ); + var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 ); + var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 ); - } + this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); + this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); - } + if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { - var morphNormals = this.morphNormals[ i ]; + var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 ); - // set vertices to morph target + this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); - tmpGeo.vertices = this.morphTargets[ i ].vertices; + } - // compute morph normals + if ( geometry.boundingSphere !== null ) { - tmpGeo.computeFaceNormals(); - tmpGeo.computeVertexNormals(); + this.boundingSphere = geometry.boundingSphere.clone(); - // store morph normals + } - var faceNormal, vertexNormals; + if ( geometry.boundingBox !== null ) { - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + this.boundingBox = geometry.boundingBox.clone(); - face = this.faces[ f ]; + } - faceNormal = morphNormals.faceNormals[ f ]; - vertexNormals = morphNormals.vertexNormals[ f ]; + } else if ( object.isMesh ) { - faceNormal.copy( face.normal ); + if ( geometry && geometry.isGeometry ) { - vertexNormals.a.copy( face.vertexNormals[ 0 ] ); - vertexNormals.b.copy( face.vertexNormals[ 1 ] ); - vertexNormals.c.copy( face.vertexNormals[ 2 ] ); + this.fromGeometry( geometry ); } } - // restore original normals + return this; - for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { + }, - face = this.faces[ f ]; + setFromPoints: function ( points ) { - face.normal = face.__originalFaceNormal; - face.vertexNormals = face.__originalVertexNormals; + var position = []; + + for ( var i = 0, l = points.length; i < l; i ++ ) { + + var point = points[ i ]; + position.push( point.x, point.y, point.z || 0 ); } + this.addAttribute( 'position', new Float32BufferAttribute( position, 3 ) ); + + return this; + }, - computeLineDistances: function () { + updateFromObject: function ( object ) { - var d = 0; - var vertices = this.vertices; + var geometry = object.geometry; + + if ( object.isMesh ) { - for ( var i = 0, il = vertices.length; i < il; i ++ ) { + var direct = geometry.__directGeometry; - if ( i > 0 ) { + if ( geometry.elementsNeedUpdate === true ) { - d += vertices[ i ].distanceTo( vertices[ i - 1 ] ); + direct = undefined; + geometry.elementsNeedUpdate = false; } - this.lineDistances[ i ] = d; + if ( direct === undefined ) { - } + return this.fromGeometry( geometry ); - }, + } - computeBoundingBox: function () { + direct.verticesNeedUpdate = geometry.verticesNeedUpdate; + direct.normalsNeedUpdate = geometry.normalsNeedUpdate; + direct.colorsNeedUpdate = geometry.colorsNeedUpdate; + direct.uvsNeedUpdate = geometry.uvsNeedUpdate; + direct.groupsNeedUpdate = geometry.groupsNeedUpdate; - if ( this.boundingBox === null ) { + geometry.verticesNeedUpdate = false; + geometry.normalsNeedUpdate = false; + geometry.colorsNeedUpdate = false; + geometry.uvsNeedUpdate = false; + geometry.groupsNeedUpdate = false; - this.boundingBox = new Box3(); + geometry = direct; } - this.boundingBox.setFromPoints( this.vertices ); - - }, - - computeBoundingSphere: function () { + var attribute; - if ( this.boundingSphere === null ) { + if ( geometry.verticesNeedUpdate === true ) { - this.boundingSphere = new Sphere(); + attribute = this.attributes.position; - } + if ( attribute !== undefined ) { - this.boundingSphere.setFromPoints( this.vertices ); + attribute.copyVector3sArray( geometry.vertices ); + attribute.needsUpdate = true; - }, + } - merge: function ( geometry, matrix, materialIndexOffset ) { + geometry.verticesNeedUpdate = false; - if ( ! ( geometry && geometry.isGeometry ) ) { + } - console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); - return; + if ( geometry.normalsNeedUpdate === true ) { - } + attribute = this.attributes.normal; - var normalMatrix, - vertexOffset = this.vertices.length, - vertices1 = this.vertices, - vertices2 = geometry.vertices, - faces1 = this.faces, - faces2 = geometry.faces, - uvs1 = this.faceVertexUvs[ 0 ], - uvs2 = geometry.faceVertexUvs[ 0 ], - colors1 = this.colors, - colors2 = geometry.colors; + if ( attribute !== undefined ) { - if ( materialIndexOffset === undefined ) materialIndexOffset = 0; + attribute.copyVector3sArray( geometry.normals ); + attribute.needsUpdate = true; - if ( matrix !== undefined ) { + } - normalMatrix = new Matrix3().getNormalMatrix( matrix ); + geometry.normalsNeedUpdate = false; } - // vertices + if ( geometry.colorsNeedUpdate === true ) { - for ( var i = 0, il = vertices2.length; i < il; i ++ ) { + attribute = this.attributes.color; - var vertex = vertices2[ i ]; + if ( attribute !== undefined ) { - var vertexCopy = vertex.clone(); + attribute.copyColorsArray( geometry.colors ); + attribute.needsUpdate = true; - if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix ); + } - vertices1.push( vertexCopy ); + geometry.colorsNeedUpdate = false; } - // colors + if ( geometry.uvsNeedUpdate ) { - for ( var i = 0, il = colors2.length; i < il; i ++ ) { + attribute = this.attributes.uv; - colors1.push( colors2[ i ].clone() ); - - } - - // faces - - for ( i = 0, il = faces2.length; i < il; i ++ ) { - - var face = faces2[ i ], faceCopy, normal, color, - faceVertexNormals = face.vertexNormals, - faceVertexColors = face.vertexColors; - - faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); - faceCopy.normal.copy( face.normal ); - - if ( normalMatrix !== undefined ) { + if ( attribute !== undefined ) { - faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); + attribute.copyVector2sArray( geometry.uvs ); + attribute.needsUpdate = true; } - for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { + geometry.uvsNeedUpdate = false; - normal = faceVertexNormals[ j ].clone(); + } - if ( normalMatrix !== undefined ) { + if ( geometry.lineDistancesNeedUpdate ) { - normal.applyMatrix3( normalMatrix ).normalize(); + attribute = this.attributes.lineDistance; - } + if ( attribute !== undefined ) { - faceCopy.vertexNormals.push( normal ); + attribute.copyArray( geometry.lineDistances ); + attribute.needsUpdate = true; } - faceCopy.color.copy( face.color ); - - for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { + geometry.lineDistancesNeedUpdate = false; - color = faceVertexColors[ j ]; - faceCopy.vertexColors.push( color.clone() ); + } - } + if ( geometry.groupsNeedUpdate ) { - faceCopy.materialIndex = face.materialIndex + materialIndexOffset; + geometry.computeGroups( object.geometry ); + this.groups = geometry.groups; - faces1.push( faceCopy ); + geometry.groupsNeedUpdate = false; } - // uvs + return this; - for ( i = 0, il = uvs2.length; i < il; i ++ ) { + }, - var uv = uvs2[ i ], uvCopy = []; + fromGeometry: function ( geometry ) { - if ( uv === undefined ) { + geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry ); - continue; + return this.fromDirectGeometry( geometry.__directGeometry ); - } + }, - for ( var j = 0, jl = uv.length; j < jl; j ++ ) { + fromDirectGeometry: function ( geometry ) { - uvCopy.push( uv[ j ].clone() ); + var positions = new Float32Array( geometry.vertices.length * 3 ); + this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); - } + if ( geometry.normals.length > 0 ) { - uvs1.push( uvCopy ); + var normals = new Float32Array( geometry.normals.length * 3 ); + this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); } - }, + if ( geometry.colors.length > 0 ) { - mergeMesh: function ( mesh ) { + var colors = new Float32Array( geometry.colors.length * 3 ); + this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); - if ( ! ( mesh && mesh.isMesh ) ) { + } - console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); - return; + if ( geometry.uvs.length > 0 ) { - } + var uvs = new Float32Array( geometry.uvs.length * 2 ); + this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); - mesh.matrixAutoUpdate && mesh.updateMatrix(); + } - this.merge( mesh.geometry, mesh.matrix ); + if ( geometry.uvs2.length > 0 ) { - }, + var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); + this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); - /* - * Checks for duplicate vertices with hashmap. - * Duplicated vertices are removed - * and faces' vertices are updated. - */ + } - mergeVertices: function () { + // groups - var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) - var unique = [], changes = []; + this.groups = geometry.groups; - var v, key; - var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001 - var precision = Math.pow( 10, precisionPoints ); - var i, il, face; - var indices, j, jl; + // morphs - for ( i = 0, il = this.vertices.length; i < il; i ++ ) { + for ( var name in geometry.morphTargets ) { - v = this.vertices[ i ]; - key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); + var array = []; + var morphTargets = geometry.morphTargets[ name ]; - if ( verticesMap[ key ] === undefined ) { + for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { - verticesMap[ key ] = i; - unique.push( this.vertices[ i ] ); - changes[ i ] = unique.length - 1; + var morphTarget = morphTargets[ i ]; - } else { + var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 ); - //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); - changes[ i ] = changes[ verticesMap[ key ] ]; + array.push( attribute.copyVector3sArray( morphTarget ) ); } - } + this.morphAttributes[ name ] = array; + } - // if faces are completely degenerate after merging vertices, we - // have to remove them from the geometry. - var faceIndicesToRemove = []; + // skinning - for ( i = 0, il = this.faces.length; i < il; i ++ ) { + if ( geometry.skinIndices.length > 0 ) { - face = this.faces[ i ]; + var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 ); + this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); - face.a = changes[ face.a ]; - face.b = changes[ face.b ]; - face.c = changes[ face.c ]; + } - indices = [ face.a, face.b, face.c ]; + if ( geometry.skinWeights.length > 0 ) { - // if any duplicate vertices are found in a Face3 - // we have to remove the face as nothing can be saved - for ( var n = 0; n < 3; n ++ ) { + var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 ); + this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); - if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { + } - faceIndicesToRemove.push( i ); - break; + // - } + if ( geometry.boundingSphere !== null ) { - } + this.boundingSphere = geometry.boundingSphere.clone(); } - for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { - - var idx = faceIndicesToRemove[ i ]; + if ( geometry.boundingBox !== null ) { - this.faces.splice( idx, 1 ); + this.boundingBox = geometry.boundingBox.clone(); - for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { + } - this.faceVertexUvs[ j ].splice( idx, 1 ); + return this; - } + }, - } + computeBoundingBox: function () { - // Use unique set of vertices + if ( this.boundingBox === null ) { - var diff = this.vertices.length - unique.length; - this.vertices = unique; - return diff; + this.boundingBox = new Box3(); - }, + } - sortFacesByMaterialIndex: function () { + var position = this.attributes.position; - var faces = this.faces; - var length = faces.length; + if ( position !== undefined ) { - // tag faces + this.boundingBox.setFromBufferAttribute( position ); - for ( var i = 0; i < length; i ++ ) { + } else { - faces[ i ]._id = i; + this.boundingBox.makeEmpty(); } - // sort faces - - function materialIndexSort( a, b ) { + if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { - return a.materialIndex - b.materialIndex; + console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); } - faces.sort( materialIndexSort ); + }, - // sort uvs + computeBoundingSphere: function () { - var uvs1 = this.faceVertexUvs[ 0 ]; - var uvs2 = this.faceVertexUvs[ 1 ]; + var box = new Box3(); + var vector = new Vector3(); - var newUvs1, newUvs2; + return function computeBoundingSphere() { - if ( uvs1 && uvs1.length === length ) newUvs1 = []; - if ( uvs2 && uvs2.length === length ) newUvs2 = []; + if ( this.boundingSphere === null ) { - for ( var i = 0; i < length; i ++ ) { + this.boundingSphere = new Sphere(); - var id = faces[ i ]._id; + } - if ( newUvs1 ) newUvs1.push( uvs1[ id ] ); - if ( newUvs2 ) newUvs2.push( uvs2[ id ] ); + var position = this.attributes.position; - } + if ( position ) { - if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1; - if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2; + var center = this.boundingSphere.center; - }, + box.setFromBufferAttribute( position ); + box.getCenter( center ); - toJSON: function () { + // hoping to find a boundingSphere with a radius smaller than the + // boundingSphere of the boundingBox: sqrt(3) smaller in the best case - var data = { - metadata: { - version: 4.5, - type: 'Geometry', - generator: 'Geometry.toJSON' - } - }; + var maxRadiusSq = 0; - // standard Geometry serialization + for ( var i = 0, il = position.count; i < il; i ++ ) { - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) data.name = this.name; + vector.x = position.getX( i ); + vector.y = position.getY( i ); + vector.z = position.getZ( i ); + maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); - if ( this.parameters !== undefined ) { + } - var parameters = this.parameters; + this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); - for ( var key in parameters ) { + if ( isNaN( this.boundingSphere.radius ) ) { - if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); + + } } - return data; + }; - } + }(), - var vertices = []; + computeFaceNormals: function () { - for ( var i = 0; i < this.vertices.length; i ++ ) { + // backwards compatibility - var vertex = this.vertices[ i ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + }, - } + computeVertexNormals: function () { - var faces = []; - var normals = []; - var normalsHash = {}; - var colors = []; - var colorsHash = {}; - var uvs = []; - var uvsHash = {}; + var index = this.index; + var attributes = this.attributes; + var groups = this.groups; - for ( var i = 0; i < this.faces.length; i ++ ) { + if ( attributes.position ) { - var face = this.faces[ i ]; + var positions = attributes.position.array; - var hasMaterial = true; - var hasFaceUv = false; // deprecated - var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined; - var hasFaceNormal = face.normal.length() > 0; - var hasFaceVertexNormal = face.vertexNormals.length > 0; - var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; - var hasFaceVertexColor = face.vertexColors.length > 0; + if ( attributes.normal === undefined ) { - var faceType = 0; + this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) ); - faceType = setBit( faceType, 0, 0 ); // isQuad - faceType = setBit( faceType, 1, hasMaterial ); - faceType = setBit( faceType, 2, hasFaceUv ); - faceType = setBit( faceType, 3, hasFaceVertexUv ); - faceType = setBit( faceType, 4, hasFaceNormal ); - faceType = setBit( faceType, 5, hasFaceVertexNormal ); - faceType = setBit( faceType, 6, hasFaceColor ); - faceType = setBit( faceType, 7, hasFaceVertexColor ); + } else { - faces.push( faceType ); - faces.push( face.a, face.b, face.c ); - faces.push( face.materialIndex ); + // reset existing normals to zero - if ( hasFaceVertexUv ) { + var array = attributes.normal.array; - var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; + for ( var i = 0, il = array.length; i < il; i ++ ) { - faces.push( - getUvIndex( faceVertexUvs[ 0 ] ), - getUvIndex( faceVertexUvs[ 1 ] ), - getUvIndex( faceVertexUvs[ 2 ] ) - ); + array[ i ] = 0; - } + } - if ( hasFaceNormal ) { + } - faces.push( getNormalIndex( face.normal ) ); + var normals = attributes.normal.array; - } + var vA, vB, vC; + var pA = new Vector3(), pB = new Vector3(), pC = new Vector3(); + var cb = new Vector3(), ab = new Vector3(); - if ( hasFaceVertexNormal ) { + // indexed elements - var vertexNormals = face.vertexNormals; + if ( index ) { - faces.push( - getNormalIndex( vertexNormals[ 0 ] ), - getNormalIndex( vertexNormals[ 1 ] ), - getNormalIndex( vertexNormals[ 2 ] ) - ); + var indices = index.array; - } + if ( groups.length === 0 ) { - if ( hasFaceColor ) { + this.addGroup( 0, indices.length ); - faces.push( getColorIndex( face.color ) ); + } - } + for ( var j = 0, jl = groups.length; j < jl; ++ j ) { - if ( hasFaceVertexColor ) { + var group = groups[ j ]; - var vertexColors = face.vertexColors; + var start = group.start; + var count = group.count; - faces.push( - getColorIndex( vertexColors[ 0 ] ), - getColorIndex( vertexColors[ 1 ] ), - getColorIndex( vertexColors[ 2 ] ) - ); + for ( var i = start, il = start + count; i < il; i += 3 ) { - } + vA = indices[ i + 0 ] * 3; + vB = indices[ i + 1 ] * 3; + vC = indices[ i + 2 ] * 3; - } + pA.fromArray( positions, vA ); + pB.fromArray( positions, vB ); + pC.fromArray( positions, vC ); - function setBit( value, position, enabled ) { + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); + normals[ vA ] += cb.x; + normals[ vA + 1 ] += cb.y; + normals[ vA + 2 ] += cb.z; - } + normals[ vB ] += cb.x; + normals[ vB + 1 ] += cb.y; + normals[ vB + 2 ] += cb.z; - function getNormalIndex( normal ) { + normals[ vC ] += cb.x; + normals[ vC + 1 ] += cb.y; + normals[ vC + 2 ] += cb.z; - var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); + } - if ( normalsHash[ hash ] !== undefined ) { + } - return normalsHash[ hash ]; + } else { - } + // non-indexed elements (unconnected triangle soup) - normalsHash[ hash ] = normals.length / 3; - normals.push( normal.x, normal.y, normal.z ); + for ( var i = 0, il = positions.length; i < il; i += 9 ) { - return normalsHash[ hash ]; + pA.fromArray( positions, i ); + pB.fromArray( positions, i + 3 ); + pC.fromArray( positions, i + 6 ); - } + cb.subVectors( pC, pB ); + ab.subVectors( pA, pB ); + cb.cross( ab ); - function getColorIndex( color ) { + normals[ i ] = cb.x; + normals[ i + 1 ] = cb.y; + normals[ i + 2 ] = cb.z; - var hash = color.r.toString() + color.g.toString() + color.b.toString(); + normals[ i + 3 ] = cb.x; + normals[ i + 4 ] = cb.y; + normals[ i + 5 ] = cb.z; - if ( colorsHash[ hash ] !== undefined ) { + normals[ i + 6 ] = cb.x; + normals[ i + 7 ] = cb.y; + normals[ i + 8 ] = cb.z; - return colorsHash[ hash ]; + } } - colorsHash[ hash ] = colors.length; - colors.push( color.getHex() ); + this.normalizeNormals(); - return colorsHash[ hash ]; + attributes.normal.needsUpdate = true; } - function getUvIndex( uv ) { + }, - var hash = uv.x.toString() + uv.y.toString(); + merge: function ( geometry, offset ) { - if ( uvsHash[ hash ] !== undefined ) { + if ( ! ( geometry && geometry.isBufferGeometry ) ) { - return uvsHash[ hash ]; + console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); + return; - } + } - uvsHash[ hash ] = uvs.length / 2; - uvs.push( uv.x, uv.y ); + if ( offset === undefined ) { - return uvsHash[ hash ]; + offset = 0; - } + console.warn( + 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.' + ); - data.data = {}; + } - data.data.vertices = vertices; - data.data.normals = normals; - if ( colors.length > 0 ) data.data.colors = colors; - if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility - data.data.faces = faces; + var attributes = this.attributes; - return data; + for ( var key in attributes ) { - }, + if ( geometry.attributes[ key ] === undefined ) continue; - clone: function () { + var attribute1 = attributes[ key ]; + var attributeArray1 = attribute1.array; - /* - // Handle primitives + var attribute2 = geometry.attributes[ key ]; + var attributeArray2 = attribute2.array; - var parameters = this.parameters; + var attributeSize = attribute2.itemSize; - if ( parameters !== undefined ) { + for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) { - var values = []; + attributeArray1[ j ] = attributeArray2[ i ]; - for ( var key in parameters ) { + } - values.push( parameters[ key ] ); + } - } + return this; - var geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + }, - } + normalizeNormals: function () { - return new this.constructor().copy( this ); - */ + var vector = new Vector3(); - return new Geometry().copy( this ); + return function normalizeNormals() { - }, + var normals = this.attributes.normal; - copy: function ( source ) { + for ( var i = 0, il = normals.count; i < il; i ++ ) { - var i, il, j, jl, k, kl; + vector.x = normals.getX( i ); + vector.y = normals.getY( i ); + vector.z = normals.getZ( i ); - // reset + vector.normalize(); - this.vertices = []; - this.colors = []; - this.faces = []; - this.faceVertexUvs = [[]]; - this.morphTargets = []; - this.morphNormals = []; - this.skinWeights = []; - this.skinIndices = []; - this.lineDistances = []; - this.boundingBox = null; - this.boundingSphere = null; + normals.setXYZ( i, vector.x, vector.y, vector.z ); - // name + } - this.name = source.name; + }; - // vertices + }(), - var vertices = source.vertices; + toNonIndexed: function () { - for ( i = 0, il = vertices.length; i < il; i ++ ) { + if ( this.index === null ) { - this.vertices.push( vertices[ i ].clone() ); + console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' ); + return this; } - // colors + var geometry2 = new BufferGeometry(); - var colors = source.colors; + var indices = this.index.array; + var attributes = this.attributes; - for ( i = 0, il = colors.length; i < il; i ++ ) { + for ( var name in attributes ) { - this.colors.push( colors[ i ].clone() ); + var attribute = attributes[ name ]; - } + var array = attribute.array; + var itemSize = attribute.itemSize; - // faces + var array2 = new array.constructor( indices.length * itemSize ); - var faces = source.faces; + var index = 0, index2 = 0; - for ( i = 0, il = faces.length; i < il; i ++ ) { + for ( var i = 0, l = indices.length; i < l; i ++ ) { - this.faces.push( faces[ i ].clone() ); + index = indices[ i ] * itemSize; + + for ( var j = 0; j < itemSize; j ++ ) { + + array2[ index2 ++ ] = array[ index ++ ]; + + } + + } + + geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) ); } - // face vertex uvs + var groups = this.groups; - for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { + for ( var i = 0, l = groups.length; i < l; i ++ ) { - var faceVertexUvs = source.faceVertexUvs[ i ]; + var group = groups[ i ]; + geometry2.addGroup( group.start, group.count, group.materialIndex ); - if ( this.faceVertexUvs[ i ] === undefined ) { + } - this.faceVertexUvs[ i ] = []; + return geometry2; - } + }, - for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { + toJSON: function () { - var uvs = faceVertexUvs[ j ], uvsCopy = []; + var data = { + metadata: { + version: 4.5, + type: 'BufferGeometry', + generator: 'BufferGeometry.toJSON' + } + }; - for ( k = 0, kl = uvs.length; k < kl; k ++ ) { + // standard BufferGeometry serialization - var uv = uvs[ k ]; + data.uuid = this.uuid; + data.type = this.type; + if ( this.name !== '' ) data.name = this.name; - uvsCopy.push( uv.clone() ); + if ( this.parameters !== undefined ) { - } + var parameters = this.parameters; - this.faceVertexUvs[ i ].push( uvsCopy ); + for ( var key in parameters ) { + + if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; } + return data; + } - // morph targets + data.data = { attributes: {} }; - var morphTargets = source.morphTargets; + var index = this.index; - for ( i = 0, il = morphTargets.length; i < il; i ++ ) { + if ( index !== null ) { - var morphTarget = {}; - morphTarget.name = morphTargets[ i ].name; + var array = Array.prototype.slice.call( index.array ); - // vertices + data.data.index = { + type: index.array.constructor.name, + array: array + }; - if ( morphTargets[ i ].vertices !== undefined ) { + } - morphTarget.vertices = []; + var attributes = this.attributes; - for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) { + for ( var key in attributes ) { - morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() ); + var attribute = attributes[ key ]; - } + var array = Array.prototype.slice.call( attribute.array ); - } + data.data.attributes[ key ] = { + itemSize: attribute.itemSize, + type: attribute.array.constructor.name, + array: array, + normalized: attribute.normalized + }; - // normals + } - if ( morphTargets[ i ].normals !== undefined ) { + var groups = this.groups; - morphTarget.normals = []; + if ( groups.length > 0 ) { - for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) { + data.data.groups = JSON.parse( JSON.stringify( groups ) ); - morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() ); + } - } + var boundingSphere = this.boundingSphere; - } + if ( boundingSphere !== null ) { - this.morphTargets.push( morphTarget ); + data.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; } - // morph normals + return data; - var morphNormals = source.morphNormals; + }, - for ( i = 0, il = morphNormals.length; i < il; i ++ ) { + clone: function () { - var morphNormal = {}; + /* + // Handle primitives - // vertex normals + var parameters = this.parameters; - if ( morphNormals[ i ].vertexNormals !== undefined ) { + if ( parameters !== undefined ) { - morphNormal.vertexNormals = []; + var values = []; - for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) { + for ( var key in parameters ) { - var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ]; - var destVertexNormal = {}; + values.push( parameters[ key ] ); - destVertexNormal.a = srcVertexNormal.a.clone(); - destVertexNormal.b = srcVertexNormal.b.clone(); - destVertexNormal.c = srcVertexNormal.c.clone(); + } - morphNormal.vertexNormals.push( destVertexNormal ); + var geometry = Object.create( this.constructor.prototype ); + this.constructor.apply( geometry, values ); + return geometry; - } + } - } + return new this.constructor().copy( this ); + */ - // face normals + return new BufferGeometry().copy( this ); - if ( morphNormals[ i ].faceNormals !== undefined ) { + }, - morphNormal.faceNormals = []; + copy: function ( source ) { - for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) { + var name, i, l; - morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() ); + // reset - } + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; - } + // name - this.morphNormals.push( morphNormal ); + this.name = source.name; + + // index + + var index = source.index; + + if ( index !== null ) { + + this.setIndex( index.clone() ); } - // skin weights + // attributes - var skinWeights = source.skinWeights; + var attributes = source.attributes; - for ( i = 0, il = skinWeights.length; i < il; i ++ ) { + for ( name in attributes ) { - this.skinWeights.push( skinWeights[ i ].clone() ); + var attribute = attributes[ name ]; + this.addAttribute( name, attribute.clone() ); } - // skin indices + // morph attributes - var skinIndices = source.skinIndices; + var morphAttributes = source.morphAttributes; - for ( i = 0, il = skinIndices.length; i < il; i ++ ) { + for ( name in morphAttributes ) { - this.skinIndices.push( skinIndices[ i ].clone() ); + var array = []; + var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes + + for ( i = 0, l = morphAttribute.length; i < l; i ++ ) { + + array.push( morphAttribute[ i ].clone() ); + + } + + this.morphAttributes[ name ] = array; } - // line distances + // groups - var lineDistances = source.lineDistances; + var groups = source.groups; - for ( i = 0, il = lineDistances.length; i < il; i ++ ) { + for ( i = 0, l = groups.length; i < l; i ++ ) { - this.lineDistances.push( lineDistances[ i ] ); + var group = groups[ i ]; + this.addGroup( group.start, group.count, group.materialIndex ); } @@ -12680,15 +12110,10 @@ } - // update flags + // draw range - this.elementsNeedUpdate = source.elementsNeedUpdate; - this.verticesNeedUpdate = source.verticesNeedUpdate; - this.uvsNeedUpdate = source.uvsNeedUpdate; - this.normalsNeedUpdate = source.normalsNeedUpdate; - this.colorsNeedUpdate = source.colorsNeedUpdate; - this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate; - this.groupsNeedUpdate = source.groupsNeedUpdate; + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; return this; @@ -12704,3799 +12129,3973 @@ /** * @author mrdoob / http://mrdoob.com/ + * @author Mugen87 / https://github.com/Mugen87 */ - function BufferAttribute( array, itemSize, normalized ) { + // BoxGeometry - if ( Array.isArray( array ) ) { + function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { - throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); + Geometry.call( this ); - } + this.type = 'BoxGeometry'; - this.uuid = _Math.generateUUID(); - this.name = ''; + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; - this.array = array; - this.itemSize = itemSize; - this.count = array !== undefined ? array.length / itemSize : 0; - this.normalized = normalized === true; + this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); + this.mergeVertices(); - this.dynamic = false; - this.updateRange = { offset: 0, count: - 1 }; + } - this.onUploadCallback = function () {}; + BoxGeometry.prototype = Object.create( Geometry.prototype ); + BoxGeometry.prototype.constructor = BoxGeometry; - this.version = 0; + // BoxBufferGeometry - } + function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { - Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', { + BufferGeometry.call( this ); - set: function ( value ) { + this.type = 'BoxBufferGeometry'; - if ( value === true ) this.version ++; + this.parameters = { + width: width, + height: height, + depth: depth, + widthSegments: widthSegments, + heightSegments: heightSegments, + depthSegments: depthSegments + }; - } + var scope = this; - } ); + width = width || 1; + height = height || 1; + depth = depth || 1; - Object.assign( BufferAttribute.prototype, { + // segments - isBufferAttribute: true, + widthSegments = Math.floor( widthSegments ) || 1; + heightSegments = Math.floor( heightSegments ) || 1; + depthSegments = Math.floor( depthSegments ) || 1; - setArray: function ( array ) { + // buffers - if ( Array.isArray( array ) ) { + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; - throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); + // helper variables - } + var numberOfVertices = 0; + var groupStart = 0; - this.count = array !== undefined ? array.length / this.itemSize : 0; - this.array = array; + // build each side of the box geometry - }, + buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px + buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx + buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py + buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny + buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz + buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz - setDynamic: function ( value ) { + // build geometry - this.dynamic = value; + this.setIndex( indices ); + this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - return this; + function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { - }, + var segmentWidth = width / gridX; + var segmentHeight = height / gridY; - copy: function ( source ) { + var widthHalf = width / 2; + var heightHalf = height / 2; + var depthHalf = depth / 2; - this.array = new source.array.constructor( source.array ); - this.itemSize = source.itemSize; - this.count = source.count; - this.normalized = source.normalized; + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; - this.dynamic = source.dynamic; + var vertexCounter = 0; + var groupCount = 0; - return this; + var ix, iy; - }, + var vector = new Vector3(); - copyAt: function ( index1, attribute, index2 ) { + // generate vertices, normals and uvs - index1 *= this.itemSize; - index2 *= attribute.itemSize; + for ( iy = 0; iy < gridY1; iy ++ ) { - for ( var i = 0, l = this.itemSize; i < l; i ++ ) { + var y = iy * segmentHeight - heightHalf; - this.array[ index1 + i ] = attribute.array[ index2 + i ]; + for ( ix = 0; ix < gridX1; ix ++ ) { - } + var x = ix * segmentWidth - widthHalf; - return this; + // set values to correct vector component - }, + vector[ u ] = x * udir; + vector[ v ] = y * vdir; + vector[ w ] = depthHalf; - copyArray: function ( array ) { + // now apply vector to vertex buffer - this.array.set( array ); + vertices.push( vector.x, vector.y, vector.z ); - return this; + // set values to correct vector component - }, + vector[ u ] = 0; + vector[ v ] = 0; + vector[ w ] = depth > 0 ? 1 : - 1; - copyColorsArray: function ( colors ) { + // now apply vector to normal buffer - var array = this.array, offset = 0; + normals.push( vector.x, vector.y, vector.z ); - for ( var i = 0, l = colors.length; i < l; i ++ ) { + // uvs - var color = colors[ i ]; + uvs.push( ix / gridX ); + uvs.push( 1 - ( iy / gridY ) ); - if ( color === undefined ) { + // counters - console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); - color = new Color(); + vertexCounter += 1; } - array[ offset ++ ] = color.r; - array[ offset ++ ] = color.g; - array[ offset ++ ] = color.b; - } - return this; + // indices - }, + // 1. you need three indices to draw a single face + // 2. a single segment consists of two faces + // 3. so we need to generate six (2*3) indices per segment - copyIndicesArray: function ( indices ) { + for ( iy = 0; iy < gridY; iy ++ ) { - var array = this.array, offset = 0; + for ( ix = 0; ix < gridX; ix ++ ) { - for ( var i = 0, l = indices.length; i < l; i ++ ) { + var a = numberOfVertices + ix + gridX1 * iy; + var b = numberOfVertices + ix + gridX1 * ( iy + 1 ); + var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); + var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; - var index = indices[ i ]; + // faces - array[ offset ++ ] = index.a; - array[ offset ++ ] = index.b; - array[ offset ++ ] = index.c; + indices.push( a, b, d ); + indices.push( b, c, d ); - } + // increase counter - return this; + groupCount += 6; - }, + } - copyVector2sArray: function ( vectors ) { + } - var array = this.array, offset = 0; + // add a group to the geometry. this will ensure multi material support - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + scope.addGroup( groupStart, groupCount, materialIndex ); - var vector = vectors[ i ]; + // calculate new start value for groups - if ( vector === undefined ) { + groupStart += groupCount; - console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); - vector = new Vector2(); + // update total number of vertices - } + numberOfVertices += vertexCounter; - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; + } - } + } - return this; + BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + BoxBufferGeometry.prototype.constructor = BoxBufferGeometry; - }, + /** + * @author mrdoob / http://mrdoob.com/ + * @author Mugen87 / https://github.com/Mugen87 + */ - copyVector3sArray: function ( vectors ) { + // PlaneGeometry - var array = this.array, offset = 0; + function PlaneGeometry( width, height, widthSegments, heightSegments ) { - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + Geometry.call( this ); - var vector = vectors[ i ]; + this.type = 'PlaneGeometry'; - if ( vector === undefined ) { + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; - console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); - vector = new Vector3(); + this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); + this.mergeVertices(); - } + } - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; + PlaneGeometry.prototype = Object.create( Geometry.prototype ); + PlaneGeometry.prototype.constructor = PlaneGeometry; - } + // PlaneBufferGeometry - return this; + function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) { - }, + BufferGeometry.call( this ); - copyVector4sArray: function ( vectors ) { + this.type = 'PlaneBufferGeometry'; - var array = this.array, offset = 0; + this.parameters = { + width: width, + height: height, + widthSegments: widthSegments, + heightSegments: heightSegments + }; - for ( var i = 0, l = vectors.length; i < l; i ++ ) { + width = width || 1; + height = height || 1; - var vector = vectors[ i ]; + var width_half = width / 2; + var height_half = height / 2; - if ( vector === undefined ) { + var gridX = Math.floor( widthSegments ) || 1; + var gridY = Math.floor( heightSegments ) || 1; - console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); - vector = new Vector4(); + var gridX1 = gridX + 1; + var gridY1 = gridY + 1; - } + var segment_width = width / gridX; + var segment_height = height / gridY; - array[ offset ++ ] = vector.x; - array[ offset ++ ] = vector.y; - array[ offset ++ ] = vector.z; - array[ offset ++ ] = vector.w; + var ix, iy; - } + // buffers - return this; + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; - }, + // generate vertices, normals and uvs - set: function ( value, offset ) { + for ( iy = 0; iy < gridY1; iy ++ ) { - if ( offset === undefined ) offset = 0; + var y = iy * segment_height - height_half; - this.array.set( value, offset ); + for ( ix = 0; ix < gridX1; ix ++ ) { - return this; + var x = ix * segment_width - width_half; - }, + vertices.push( x, - y, 0 ); - getX: function ( index ) { + normals.push( 0, 0, 1 ); - return this.array[ index * this.itemSize ]; + uvs.push( ix / gridX ); + uvs.push( 1 - ( iy / gridY ) ); - }, + } - setX: function ( index, x ) { + } - this.array[ index * this.itemSize ] = x; + // indices - return this; + for ( iy = 0; iy < gridY; iy ++ ) { - }, + for ( ix = 0; ix < gridX; ix ++ ) { - getY: function ( index ) { + var a = ix + gridX1 * iy; + var b = ix + gridX1 * ( iy + 1 ); + var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); + var d = ( ix + 1 ) + gridX1 * iy; - return this.array[ index * this.itemSize + 1 ]; + // faces - }, + indices.push( a, b, d ); + indices.push( b, c, d ); - setY: function ( index, y ) { + } - this.array[ index * this.itemSize + 1 ] = y; + } - return this; + // build geometry - }, + this.setIndex( indices ); + this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - getZ: function ( index ) { + } - return this.array[ index * this.itemSize + 2 ]; + PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry; - }, + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - setZ: function ( index, z ) { + var materialId = 0; - this.array[ index * this.itemSize + 2 ] = z; + function Material() { - return this; + Object.defineProperty( this, 'id', { value: materialId ++ } ); - }, + this.uuid = _Math.generateUUID(); - getW: function ( index ) { + this.name = ''; + this.type = 'Material'; - return this.array[ index * this.itemSize + 3 ]; + this.fog = true; + this.lights = true; - }, + this.blending = NormalBlending; + this.side = FrontSide; + this.flatShading = false; + this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors - setW: function ( index, w ) { + this.opacity = 1; + this.transparent = false; - this.array[ index * this.itemSize + 3 ] = w; + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; - return this; + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; - }, + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; - setXY: function ( index, x, y ) { + this.shadowSide = null; - index *= this.itemSize; + this.colorWrite = true; - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; + this.precision = null; // override the renderer's default precision for this material - return this; + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; - }, + this.dithering = false; - setXYZ: function ( index, x, y, z ) { + this.alphaTest = 0; + this.premultipliedAlpha = false; - index *= this.itemSize; + this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; + this.visible = true; - return this; + this.userData = {}; - }, + this.needsUpdate = true; - setXYZW: function ( index, x, y, z, w ) { + } - index *= this.itemSize; + Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { - this.array[ index + 0 ] = x; - this.array[ index + 1 ] = y; - this.array[ index + 2 ] = z; - this.array[ index + 3 ] = w; + constructor: Material, - return this; + isMaterial: true, - }, + onBeforeCompile: function () {}, - onUpload: function ( callback ) { + setValues: function ( values ) { - this.onUploadCallback = callback; + if ( values === undefined ) return; - return this; + for ( var key in values ) { - }, + var newValue = values[ key ]; - clone: function () { + if ( newValue === undefined ) { - return new this.constructor( this.array, this.itemSize ).copy( this ); + console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); + continue; - } + } - } ); + // for backward compatability if shading is set in the constructor + if ( key === 'shading' ) { - // + console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); + this.flatShading = ( newValue === FlatShading ) ? true : false; + continue; - function Int8BufferAttribute( array, itemSize ) { + } - BufferAttribute.call( this, new Int8Array( array ), itemSize ); + var currentValue = this[ key ]; - } + if ( currentValue === undefined ) { - Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Int8BufferAttribute.prototype.constructor = Int8BufferAttribute; + console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); + continue; + } - function Uint8BufferAttribute( array, itemSize ) { + if ( currentValue && currentValue.isColor ) { - BufferAttribute.call( this, new Uint8Array( array ), itemSize ); + currentValue.set( newValue ); - } + } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) { - Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute; + currentValue.copy( newValue ); + } else if ( key === 'overdraw' ) { - function Uint8ClampedBufferAttribute( array, itemSize ) { + // ensure overdraw is backwards-compatible with legacy boolean type + this[ key ] = Number( newValue ); - BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize ); + } else { - } + this[ key ] = newValue; - Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute; + } + } - function Int16BufferAttribute( array, itemSize ) { + }, - BufferAttribute.call( this, new Int16Array( array ), itemSize ); + toJSON: function ( meta ) { - } + var isRoot = ( meta === undefined || typeof meta === 'string' ); - Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Int16BufferAttribute.prototype.constructor = Int16BufferAttribute; + if ( isRoot ) { + meta = { + textures: {}, + images: {} + }; - function Uint16BufferAttribute( array, itemSize ) { + } - BufferAttribute.call( this, new Uint16Array( array ), itemSize ); + var data = { + metadata: { + version: 4.5, + type: 'Material', + generator: 'Material.toJSON' + } + }; - } + // standard Material serialization + data.uuid = this.uuid; + data.type = this.type; - Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute; + if ( this.name !== '' ) data.name = this.name; + if ( this.color && this.color.isColor ) data.color = this.color.getHex(); - function Int32BufferAttribute( array, itemSize ) { + if ( this.roughness !== undefined ) data.roughness = this.roughness; + if ( this.metalness !== undefined ) data.metalness = this.metalness; - BufferAttribute.call( this, new Int32Array( array ), itemSize ); + if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex(); + if ( this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity; - } + if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex(); + if ( this.shininess !== undefined ) data.shininess = this.shininess; + if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat; + if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness; - Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Int32BufferAttribute.prototype.constructor = Int32BufferAttribute; + if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid; + if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid; + if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid; + if ( this.bumpMap && this.bumpMap.isTexture ) { + data.bumpMap = this.bumpMap.toJSON( meta ).uuid; + data.bumpScale = this.bumpScale; - function Uint32BufferAttribute( array, itemSize ) { + } + if ( this.normalMap && this.normalMap.isTexture ) { - BufferAttribute.call( this, new Uint32Array( array ), itemSize ); + data.normalMap = this.normalMap.toJSON( meta ).uuid; + data.normalScale = this.normalScale.toArray(); - } + } + if ( this.displacementMap && this.displacementMap.isTexture ) { - Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute; + data.displacementMap = this.displacementMap.toJSON( meta ).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; + } + if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; + if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; - function Float32BufferAttribute( array, itemSize ) { + if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; + if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid; - BufferAttribute.call( this, new Float32Array( array ), itemSize ); + if ( this.envMap && this.envMap.isTexture ) { - } + data.envMap = this.envMap.toJSON( meta ).uuid; + data.reflectivity = this.reflectivity; // Scale behind envMap - Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Float32BufferAttribute.prototype.constructor = Float32BufferAttribute; + } + if ( this.gradientMap && this.gradientMap.isTexture ) { - function Float64BufferAttribute( array, itemSize ) { + data.gradientMap = this.gradientMap.toJSON( meta ).uuid; - BufferAttribute.call( this, new Float64Array( array ), itemSize ); + } - } + if ( this.size !== undefined ) data.size = this.size; + if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation; - Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); - Float64BufferAttribute.prototype.constructor = Float64BufferAttribute; + if ( this.blending !== NormalBlending ) data.blending = this.blending; + if ( this.flatShading === true ) data.flatShading = this.flatShading; + if ( this.side !== FrontSide ) data.side = this.side; + if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors; - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( this.opacity < 1 ) data.opacity = this.opacity; + if ( this.transparent === true ) data.transparent = this.transparent; - function DirectGeometry() { + data.depthFunc = this.depthFunc; + data.depthTest = this.depthTest; + data.depthWrite = this.depthWrite; - this.indices = []; - this.vertices = []; - this.normals = []; - this.colors = []; - this.uvs = []; - this.uvs2 = []; + // rotation (SpriteMaterial) + if ( this.rotation !== 0 ) data.rotation = this.rotation; - this.groups = []; + if ( this.linewidth !== 1 ) data.linewidth = this.linewidth; + if ( this.dashSize !== undefined ) data.dashSize = this.dashSize; + if ( this.gapSize !== undefined ) data.gapSize = this.gapSize; + if ( this.scale !== undefined ) data.scale = this.scale; - this.morphTargets = {}; + if ( this.dithering === true ) data.dithering = true; - this.skinWeights = []; - this.skinIndices = []; + if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest; + if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha; - // this.lineDistances = []; + if ( this.wireframe === true ) data.wireframe = this.wireframe; + if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth; + if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap; + if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin; - this.boundingBox = null; - this.boundingSphere = null; + if ( this.morphTargets === true ) data.morphTargets = true; + if ( this.skinning === true ) data.skinning = true; - // update flags + if ( this.visible === false ) data.visible = false; + if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData; - this.verticesNeedUpdate = false; - this.normalsNeedUpdate = false; - this.colorsNeedUpdate = false; - this.uvsNeedUpdate = false; - this.groupsNeedUpdate = false; + // TODO: Copied from Object3D.toJSON - } + function extractFromCache( cache ) { - Object.assign( DirectGeometry.prototype, { + var values = []; - computeGroups: function ( geometry ) { + for ( var key in cache ) { - var group; - var groups = []; - var materialIndex = undefined; + var data = cache[ key ]; + delete data.metadata; + values.push( data ); - var faces = geometry.faces; + } - for ( var i = 0; i < faces.length; i ++ ) { + return values; - var face = faces[ i ]; + } - // materials + if ( isRoot ) { - if ( face.materialIndex !== materialIndex ) { + var textures = extractFromCache( meta.textures ); + var images = extractFromCache( meta.images ); - materialIndex = face.materialIndex; + if ( textures.length > 0 ) data.textures = textures; + if ( images.length > 0 ) data.images = images; - if ( group !== undefined ) { + } - group.count = ( i * 3 ) - group.start; - groups.push( group ); + return data; - } + }, - group = { - start: i * 3, - materialIndex: materialIndex - }; + clone: function () { - } + return new this.constructor().copy( this ); - } + }, - if ( group !== undefined ) { + copy: function ( source ) { - group.count = ( i * 3 ) - group.start; - groups.push( group ); + this.name = source.name; - } + this.fog = source.fog; + this.lights = source.lights; - this.groups = groups; + this.blending = source.blending; + this.side = source.side; + this.flatShading = source.flatShading; + this.vertexColors = source.vertexColors; - }, + this.opacity = source.opacity; + this.transparent = source.transparent; - fromGeometry: function ( geometry ) { + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; - var faces = geometry.faces; - var vertices = geometry.vertices; - var faceVertexUvs = geometry.faceVertexUvs; + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; - var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0; - var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0; + this.colorWrite = source.colorWrite; - // morphs + this.precision = source.precision; - var morphTargets = geometry.morphTargets; - var morphTargetsLength = morphTargets.length; + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; - var morphTargetsPosition; + this.dithering = source.dithering; - if ( morphTargetsLength > 0 ) { + this.alphaTest = source.alphaTest; + this.premultipliedAlpha = source.premultipliedAlpha; - morphTargetsPosition = []; + this.overdraw = source.overdraw; - for ( var i = 0; i < morphTargetsLength; i ++ ) { + this.visible = source.visible; + this.userData = JSON.parse( JSON.stringify( source.userData ) ); - morphTargetsPosition[ i ] = []; + this.clipShadows = source.clipShadows; + this.clipIntersection = source.clipIntersection; - } + var srcPlanes = source.clippingPlanes, + dstPlanes = null; - this.morphTargets.position = morphTargetsPosition; + if ( srcPlanes !== null ) { - } + var n = srcPlanes.length; + dstPlanes = new Array( n ); - var morphNormals = geometry.morphNormals; - var morphNormalsLength = morphNormals.length; + for ( var i = 0; i !== n; ++ i ) + dstPlanes[ i ] = srcPlanes[ i ].clone(); - var morphTargetsNormal; + } - if ( morphNormalsLength > 0 ) { + this.clippingPlanes = dstPlanes; - morphTargetsNormal = []; + this.shadowSide = source.shadowSide; - for ( var i = 0; i < morphNormalsLength; i ++ ) { + return this; - morphTargetsNormal[ i ] = []; + }, - } + dispose: function () { - this.morphTargets.normal = morphTargetsNormal; + this.dispatchEvent( { type: 'dispose' } ); - } + } - // skins + } ); - var skinIndices = geometry.skinIndices; - var skinWeights = geometry.skinWeights; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: , + * refractionRatio: , + * + * depthTest: , + * depthWrite: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: + * } + */ - var hasSkinIndices = skinIndices.length === vertices.length; - var hasSkinWeights = skinWeights.length === vertices.length; + function MeshBasicMaterial( parameters ) { - // + Material.call( this ); - for ( var i = 0; i < faces.length; i ++ ) { + this.type = 'MeshBasicMaterial'; - var face = faces[ i ]; + this.color = new Color( 0xffffff ); // emissive - this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); + this.map = null; - var vertexNormals = face.vertexNormals; + this.lightMap = null; + this.lightMapIntensity = 1.0; - if ( vertexNormals.length === 3 ) { + this.aoMap = null; + this.aoMapIntensity = 1.0; - this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); + this.specularMap = null; - } else { + this.alphaMap = null; - var normal = face.normal; + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; - this.normals.push( normal, normal, normal ); + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; - } + this.skinning = false; + this.morphTargets = false; - var vertexColors = face.vertexColors; + this.lights = false; - if ( vertexColors.length === 3 ) { + this.setValues( parameters ); - this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); + } - } else { + MeshBasicMaterial.prototype = Object.create( Material.prototype ); + MeshBasicMaterial.prototype.constructor = MeshBasicMaterial; - var color = face.color; + MeshBasicMaterial.prototype.isMeshBasicMaterial = true; - this.colors.push( color, color, color ); + MeshBasicMaterial.prototype.copy = function ( source ) { - } + Material.prototype.copy.call( this, source ); - if ( hasFaceVertexUv === true ) { + this.color.copy( source.color ); - var vertexUvs = faceVertexUvs[ 0 ][ i ]; + this.map = source.map; - if ( vertexUvs !== undefined ) { + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; - this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; - } else { + this.specularMap = source.specularMap; - console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); + this.alphaMap = source.alphaMap; - this.uvs.push( new Vector2(), new Vector2(), new Vector2() ); + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; - } + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; - } + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - if ( hasFaceVertexUv2 === true ) { + return this; - var vertexUvs = faceVertexUvs[ 1 ][ i ]; + }; - if ( vertexUvs !== undefined ) { + /** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * defines: { "label" : "value" }, + * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } }, + * + * fragmentShader: , + * vertexShader: , + * + * wireframe: , + * wireframeLinewidth: , + * + * lights: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ - this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); + function ShaderMaterial( parameters ) { - } else { + Material.call( this ); - console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); + this.type = 'ShaderMaterial'; - this.uvs2.push( new Vector2(), new Vector2(), new Vector2() ); - - } - - } - - // morphs - - for ( var j = 0; j < morphTargetsLength; j ++ ) { - - var morphTarget = morphTargets[ j ].vertices; + this.defines = {}; + this.uniforms = {}; - morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); + this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}'; + this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}'; - } + this.linewidth = 1; - for ( var j = 0; j < morphNormalsLength; j ++ ) { + this.wireframe = false; + this.wireframeLinewidth = 1; - var morphNormal = morphNormals[ j ].vertexNormals[ i ]; + this.fog = false; // set to use scene fog + this.lights = false; // set to use scene lights + this.clipping = false; // set to use user-defined clipping planes - morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c ); + this.skinning = false; // set to use skinning attribute streams + this.morphTargets = false; // set to use morph targets + this.morphNormals = false; // set to use morph normals - } + this.extensions = { + derivatives: false, // set to use derivatives + fragDepth: false, // set to use fragment depth values + drawBuffers: false, // set to use draw buffers + shaderTextureLOD: false // set to use shader texture LOD + }; - // skins + // When rendered geometry doesn't include these attributes but the material does, + // use these default values in WebGL. This avoids errors when buffer data is missing. + this.defaultAttributeValues = { + 'color': [ 1, 1, 1 ], + 'uv': [ 0, 0 ], + 'uv2': [ 0, 0 ] + }; - if ( hasSkinIndices ) { + this.index0AttributeName = undefined; + this.uniformsNeedUpdate = false; - this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); + if ( parameters !== undefined ) { - } + if ( parameters.attributes !== undefined ) { - if ( hasSkinWeights ) { + console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); - this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); + } - } + this.setValues( parameters ); - } + } - this.computeGroups( geometry ); + } - this.verticesNeedUpdate = geometry.verticesNeedUpdate; - this.normalsNeedUpdate = geometry.normalsNeedUpdate; - this.colorsNeedUpdate = geometry.colorsNeedUpdate; - this.uvsNeedUpdate = geometry.uvsNeedUpdate; - this.groupsNeedUpdate = geometry.groupsNeedUpdate; + ShaderMaterial.prototype = Object.create( Material.prototype ); + ShaderMaterial.prototype.constructor = ShaderMaterial; - return this; + ShaderMaterial.prototype.isShaderMaterial = true; - } + ShaderMaterial.prototype.copy = function ( source ) { - } ); + Material.prototype.copy.call( this, source ); - function arrayMax( array ) { + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; - if ( array.length === 0 ) return - Infinity; + this.uniforms = UniformsUtils.clone( source.uniforms ); - var max = array[ 0 ]; + this.defines = source.defines; - for ( var i = 1, l = array.length; i < l; ++ i ) { + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - if ( array[ i ] > max ) max = array[ i ]; + this.lights = source.lights; + this.clipping = source.clipping; - } + this.skinning = source.skinning; - return max; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; - } + this.extensions = source.extensions; - /** - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + return this; - function BufferGeometry() { + }; - Object.defineProperty( this, 'id', { value: GeometryIdCount() } ); + ShaderMaterial.prototype.toJSON = function ( meta ) { - this.uuid = _Math.generateUUID(); + var data = Material.prototype.toJSON.call( this, meta ); - this.name = ''; - this.type = 'BufferGeometry'; + data.uniforms = this.uniforms; + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; - this.index = null; - this.attributes = {}; + return data; - this.morphAttributes = {}; + }; - this.groups = []; + /** + * @author bhouston / http://clara.io + */ - this.boundingBox = null; - this.boundingSphere = null; + function Ray( origin, direction ) { - this.drawRange = { start: 0, count: Infinity }; + this.origin = ( origin !== undefined ) ? origin : new Vector3(); + this.direction = ( direction !== undefined ) ? direction : new Vector3(); } - BufferGeometry.MaxIndex = 65535; - - Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, { + Object.assign( Ray.prototype, { - isBufferGeometry: true, + set: function ( origin, direction ) { - getIndex: function () { + this.origin.copy( origin ); + this.direction.copy( direction ); - return this.index; + return this; }, - setIndex: function ( index ) { + clone: function () { - if ( Array.isArray( index ) ) { + return new this.constructor().copy( this ); - this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 ); + }, - } else { + copy: function ( ray ) { - this.index = index; + this.origin.copy( ray.origin ); + this.direction.copy( ray.direction ); - } + return this; }, - addAttribute: function ( name, attribute ) { - - if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) { - - console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); + at: function ( t, target ) { - this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); + if ( target === undefined ) { - return; + console.warn( 'THREE.Ray: .at() target is now required' ); + target = new Vector3(); } - if ( name === 'index' ) { - - console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); - this.setIndex( attribute ); + return target.copy( this.direction ).multiplyScalar( t ).add( this.origin ); - return; + }, - } + lookAt: function ( v ) { - this.attributes[ name ] = attribute; + this.direction.copy( v ).sub( this.origin ).normalize(); return this; }, - getAttribute: function ( name ) { + recast: function () { - return this.attributes[ name ]; + var v1 = new Vector3(); - }, + return function recast( t ) { - removeAttribute: function ( name ) { + this.origin.copy( this.at( t, v1 ) ); - delete this.attributes[ name ]; + return this; - return this; + }; - }, + }(), - addGroup: function ( start, count, materialIndex ) { + closestPointToPoint: function ( point, target ) { - this.groups.push( { + if ( target === undefined ) { - start: start, - count: count, - materialIndex: materialIndex !== undefined ? materialIndex : 0 + console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' ); + target = new Vector3(); - } ); + } - }, + target.subVectors( point, this.origin ); - clearGroups: function () { + var directionDistance = target.dot( this.direction ); - this.groups = []; + if ( directionDistance < 0 ) { - }, + return target.copy( this.origin ); - setDrawRange: function ( start, count ) { + } - this.drawRange.start = start; - this.drawRange.count = count; + return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); }, - applyMatrix: function ( matrix ) { - - var position = this.attributes.position; + distanceToPoint: function ( point ) { - if ( position !== undefined ) { + return Math.sqrt( this.distanceSqToPoint( point ) ); - matrix.applyToBufferAttribute( position ); - position.needsUpdate = true; + }, - } + distanceSqToPoint: function () { - var normal = this.attributes.normal; + var v1 = new Vector3(); - if ( normal !== undefined ) { + return function distanceSqToPoint( point ) { - var normalMatrix = new Matrix3().getNormalMatrix( matrix ); + var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); - normalMatrix.applyToBufferAttribute( normal ); - normal.needsUpdate = true; + // point behind the ray - } + if ( directionDistance < 0 ) { - if ( this.boundingBox !== null ) { + return this.origin.distanceToSquared( point ); - this.computeBoundingBox(); + } - } + v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); - if ( this.boundingSphere !== null ) { + return v1.distanceToSquared( point ); - this.computeBoundingSphere(); + }; - } + }(), - return this; + distanceSqToSegment: function () { - }, + var segCenter = new Vector3(); + var segDir = new Vector3(); + var diff = new Vector3(); - rotateX: function () { + return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { - // rotate geometry around world x-axis + // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h + // It returns the min distance between the ray and the segment + // defined by v0 and v1 + // It can also set two optional targets : + // - The closest point on the ray + // - The closest point on the segment - var m1 = new Matrix4(); + segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); + segDir.copy( v1 ).sub( v0 ).normalize(); + diff.copy( this.origin ).sub( segCenter ); - return function rotateX( angle ) { + var segExtent = v0.distanceTo( v1 ) * 0.5; + var a01 = - this.direction.dot( segDir ); + var b0 = diff.dot( this.direction ); + var b1 = - diff.dot( segDir ); + var c = diff.lengthSq(); + var det = Math.abs( 1 - a01 * a01 ); + var s0, s1, sqrDist, extDet; - m1.makeRotationX( angle ); + if ( det > 0 ) { - this.applyMatrix( m1 ); + // The ray and segment are not parallel. - return this; + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; - }; + if ( s0 >= 0 ) { - }(), + if ( s1 >= - extDet ) { - rotateY: function () { + if ( s1 <= extDet ) { - // rotate geometry around world y-axis + // region 0 + // Minimum at interior points of ray and segment. - var m1 = new Matrix4(); + var invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; - return function rotateY( angle ) { + } else { - m1.makeRotationY( angle ); + // region 1 - this.applyMatrix( m1 ); + s1 = segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - return this; + } - }; + } else { - }(), + // region 5 - rotateZ: function () { + s1 = - segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - // rotate geometry around world z-axis + } - var m1 = new Matrix4(); + } else { - return function rotateZ( angle ) { + if ( s1 <= - extDet ) { - m1.makeRotationZ( angle ); + // region 4 - this.applyMatrix( m1 ); + s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); + s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - return this; + } else if ( s1 <= extDet ) { - }; + // region 3 - }(), + s0 = 0; + s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = s1 * ( s1 + 2 * b1 ) + c; - translate: function () { + } else { - // translate geometry + // region 2 - var m1 = new Matrix4(); + s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); + s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - return function translate( x, y, z ) { + } - m1.makeTranslation( x, y, z ); + } - this.applyMatrix( m1 ); + } else { - return this; + // Ray and segment are parallel. - }; + s1 = ( a01 > 0 ) ? - segExtent : segExtent; + s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); + sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; - }(), + } - scale: function () { + if ( optionalPointOnRay ) { - // scale geometry + optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); - var m1 = new Matrix4(); + } - return function scale( x, y, z ) { + if ( optionalPointOnSegment ) { - m1.makeScale( x, y, z ); + optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter ); - this.applyMatrix( m1 ); + } - return this; + return sqrDist; }; }(), - lookAt: function () { - - var obj = new Object3D(); - - return function lookAt( vector ) { + intersectSphere: function () { - obj.lookAt( vector ); + var v1 = new Vector3(); - obj.updateMatrix(); + return function intersectSphere( sphere, target ) { - this.applyMatrix( obj.matrix ); + v1.subVectors( sphere.center, this.origin ); + var tca = v1.dot( this.direction ); + var d2 = v1.dot( v1 ) - tca * tca; + var radius2 = sphere.radius * sphere.radius; - }; + if ( d2 > radius2 ) return null; - }(), + var thc = Math.sqrt( radius2 - d2 ); - center: function () { + // t0 = first intersect point - entrance on front of sphere + var t0 = tca - thc; - this.computeBoundingBox(); + // t1 = second intersect point - exit point on back of sphere + var t1 = tca + thc; - var offset = this.boundingBox.getCenter().negate(); + // test to see if both t0 and t1 are behind the ray - if so, return null + if ( t0 < 0 && t1 < 0 ) return null; - this.translate( offset.x, offset.y, offset.z ); + // test to see if t0 is behind the ray: + // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, + // in order to always return an intersect point that is in front of the ray. + if ( t0 < 0 ) return this.at( t1, target ); - return offset; + // else t0 is in front of the ray, so return the first collision point scaled by t0 + return this.at( t0, target ); - }, + }; - setFromObject: function ( object ) { + }(), - // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); + intersectsSphere: function ( sphere ) { - var geometry = object.geometry; + return this.distanceToPoint( sphere.center ) <= sphere.radius; - if ( object.isPoints || object.isLine ) { + }, - var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 ); - var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 ); + distanceToPlane: function ( plane ) { - this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); - this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); + var denominator = plane.normal.dot( this.direction ); - if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { + if ( denominator === 0 ) { - var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 ); + // line is coplanar, return origin + if ( plane.distanceToPoint( this.origin ) === 0 ) { - this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); + return 0; } - if ( geometry.boundingSphere !== null ) { + // Null is preferable to undefined since undefined means.... it is undefined - this.boundingSphere = geometry.boundingSphere.clone(); + return null; - } + } - if ( geometry.boundingBox !== null ) { + var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; - this.boundingBox = geometry.boundingBox.clone(); + // Return if the ray never intersects the plane - } + return t >= 0 ? t : null; - } else if ( object.isMesh ) { + }, - if ( geometry && geometry.isGeometry ) { + intersectPlane: function ( plane, target ) { - this.fromGeometry( geometry ); + var t = this.distanceToPlane( plane ); - } + if ( t === null ) { + + return null; } - return this; + return this.at( t, target ); }, - updateFromObject: function ( object ) { + intersectsPlane: function ( plane ) { - var geometry = object.geometry; + // check if the ray lies on the plane first - if ( object.isMesh ) { + var distToPoint = plane.distanceToPoint( this.origin ); - var direct = geometry.__directGeometry; + if ( distToPoint === 0 ) { - if ( geometry.elementsNeedUpdate === true ) { + return true; - direct = undefined; - geometry.elementsNeedUpdate = false; + } - } + var denominator = plane.normal.dot( this.direction ); - if ( direct === undefined ) { + if ( denominator * distToPoint < 0 ) { - return this.fromGeometry( geometry ); + return true; - } + } - direct.verticesNeedUpdate = geometry.verticesNeedUpdate; - direct.normalsNeedUpdate = geometry.normalsNeedUpdate; - direct.colorsNeedUpdate = geometry.colorsNeedUpdate; - direct.uvsNeedUpdate = geometry.uvsNeedUpdate; - direct.groupsNeedUpdate = geometry.groupsNeedUpdate; + // ray origin is behind the plane (and is pointing behind it) - geometry.verticesNeedUpdate = false; - geometry.normalsNeedUpdate = false; - geometry.colorsNeedUpdate = false; - geometry.uvsNeedUpdate = false; - geometry.groupsNeedUpdate = false; + return false; - geometry = direct; + }, - } + intersectBox: function ( box, target ) { - var attribute; + var tmin, tmax, tymin, tymax, tzmin, tzmax; - if ( geometry.verticesNeedUpdate === true ) { + var invdirx = 1 / this.direction.x, + invdiry = 1 / this.direction.y, + invdirz = 1 / this.direction.z; - attribute = this.attributes.position; + var origin = this.origin; - if ( attribute !== undefined ) { + if ( invdirx >= 0 ) { - attribute.copyVector3sArray( geometry.vertices ); - attribute.needsUpdate = true; + tmin = ( box.min.x - origin.x ) * invdirx; + tmax = ( box.max.x - origin.x ) * invdirx; - } + } else { - geometry.verticesNeedUpdate = false; + tmin = ( box.max.x - origin.x ) * invdirx; + tmax = ( box.min.x - origin.x ) * invdirx; } - if ( geometry.normalsNeedUpdate === true ) { + if ( invdiry >= 0 ) { - attribute = this.attributes.normal; + tymin = ( box.min.y - origin.y ) * invdiry; + tymax = ( box.max.y - origin.y ) * invdiry; - if ( attribute !== undefined ) { + } else { - attribute.copyVector3sArray( geometry.normals ); - attribute.needsUpdate = true; + tymin = ( box.max.y - origin.y ) * invdiry; + tymax = ( box.min.y - origin.y ) * invdiry; - } + } - geometry.normalsNeedUpdate = false; + if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; - } + // These lines also handle the case where tmin or tmax is NaN + // (result of 0 * Infinity). x !== x returns true if x is NaN - if ( geometry.colorsNeedUpdate === true ) { + if ( tymin > tmin || tmin !== tmin ) tmin = tymin; - attribute = this.attributes.color; + if ( tymax < tmax || tmax !== tmax ) tmax = tymax; - if ( attribute !== undefined ) { + if ( invdirz >= 0 ) { - attribute.copyColorsArray( geometry.colors ); - attribute.needsUpdate = true; + tzmin = ( box.min.z - origin.z ) * invdirz; + tzmax = ( box.max.z - origin.z ) * invdirz; - } + } else { - geometry.colorsNeedUpdate = false; + tzmin = ( box.max.z - origin.z ) * invdirz; + tzmax = ( box.min.z - origin.z ) * invdirz; } - if ( geometry.uvsNeedUpdate ) { + if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; - attribute = this.attributes.uv; - - if ( attribute !== undefined ) { + if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; - attribute.copyVector2sArray( geometry.uvs ); - attribute.needsUpdate = true; + if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; - } + //return point closest to the ray (positive side) - geometry.uvsNeedUpdate = false; + if ( tmax < 0 ) return null; - } + return this.at( tmin >= 0 ? tmin : tmax, target ); - if ( geometry.lineDistancesNeedUpdate ) { + }, - attribute = this.attributes.lineDistance; + intersectsBox: ( function () { - if ( attribute !== undefined ) { + var v = new Vector3(); - attribute.copyArray( geometry.lineDistances ); - attribute.needsUpdate = true; + return function intersectsBox( box ) { - } + return this.intersectBox( box, v ) !== null; - geometry.lineDistancesNeedUpdate = false; + }; - } + } )(), - if ( geometry.groupsNeedUpdate ) { + intersectTriangle: function () { - geometry.computeGroups( object.geometry ); - this.groups = geometry.groups; + // Compute the offset origin, edges, and normal. + var diff = new Vector3(); + var edge1 = new Vector3(); + var edge2 = new Vector3(); + var normal = new Vector3(); - geometry.groupsNeedUpdate = false; + return function intersectTriangle( a, b, c, backfaceCulling, target ) { - } + // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h - return this; + edge1.subVectors( b, a ); + edge2.subVectors( c, a ); + normal.crossVectors( edge1, edge2 ); - }, + // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, + // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by + // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) + // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) + // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) + var DdN = this.direction.dot( normal ); + var sign; - fromGeometry: function ( geometry ) { + if ( DdN > 0 ) { - geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry ); + if ( backfaceCulling ) return null; + sign = 1; - return this.fromDirectGeometry( geometry.__directGeometry ); + } else if ( DdN < 0 ) { - }, + sign = - 1; + DdN = - DdN; - fromDirectGeometry: function ( geometry ) { + } else { - var positions = new Float32Array( geometry.vertices.length * 3 ); - this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); + return null; - if ( geometry.normals.length > 0 ) { + } - var normals = new Float32Array( geometry.normals.length * 3 ); - this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); + diff.subVectors( this.origin, a ); + var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); - } + // b1 < 0, no intersection + if ( DdQxE2 < 0 ) { - if ( geometry.colors.length > 0 ) { + return null; - var colors = new Float32Array( geometry.colors.length * 3 ); - this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); + } - } + var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); - if ( geometry.uvs.length > 0 ) { + // b2 < 0, no intersection + if ( DdE1xQ < 0 ) { - var uvs = new Float32Array( geometry.uvs.length * 2 ); - this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); + return null; - } + } - if ( geometry.uvs2.length > 0 ) { + // b1+b2 > 1, no intersection + if ( DdQxE2 + DdE1xQ > DdN ) { - var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); - this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); + return null; - } + } - if ( geometry.indices.length > 0 ) { + // Line intersects triangle, check if ray does. + var QdN = - sign * diff.dot( normal ); - var TypeArray = arrayMax( geometry.indices ) > 65535 ? Uint32Array : Uint16Array; - var indices = new TypeArray( geometry.indices.length * 3 ); - this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) ); + // t < 0, no intersection + if ( QdN < 0 ) { - } + return null; - // groups + } - this.groups = geometry.groups; + // Ray intersects triangle. + return this.at( QdN / DdN, target ); - // morphs + }; - for ( var name in geometry.morphTargets ) { + }(), - var array = []; - var morphTargets = geometry.morphTargets[ name ]; + applyMatrix4: function ( matrix4 ) { - for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { + this.origin.applyMatrix4( matrix4 ); + this.direction.transformDirection( matrix4 ); - var morphTarget = morphTargets[ i ]; + return this; - var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 ); + }, - array.push( attribute.copyVector3sArray( morphTarget ) ); + equals: function ( ray ) { - } + return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); - this.morphAttributes[ name ] = array; + } - } + } ); - // skinning + /** + * @author bhouston / http://clara.io + */ - if ( geometry.skinIndices.length > 0 ) { + function Line3( start, end ) { - var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 ); - this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); + this.start = ( start !== undefined ) ? start : new Vector3(); + this.end = ( end !== undefined ) ? end : new Vector3(); - } + } - if ( geometry.skinWeights.length > 0 ) { + Object.assign( Line3.prototype, { - var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 ); - this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); + set: function ( start, end ) { - } + this.start.copy( start ); + this.end.copy( end ); - // + return this; - if ( geometry.boundingSphere !== null ) { + }, - this.boundingSphere = geometry.boundingSphere.clone(); + clone: function () { - } + return new this.constructor().copy( this ); - if ( geometry.boundingBox !== null ) { + }, - this.boundingBox = geometry.boundingBox.clone(); + copy: function ( line ) { - } + this.start.copy( line.start ); + this.end.copy( line.end ); return this; }, - computeBoundingBox: function () { + getCenter: function ( target ) { - if ( this.boundingBox === null ) { + if ( target === undefined ) { - this.boundingBox = new Box3(); + console.warn( 'THREE.Line3: .getCenter() target is now required' ); + target = new Vector3(); } - var position = this.attributes.position; + return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); - if ( position !== undefined ) { + }, - this.boundingBox.setFromBufferAttribute( position ); + delta: function ( target ) { - } else { + if ( target === undefined ) { - this.boundingBox.makeEmpty(); + console.warn( 'THREE.Line3: .delta() target is now required' ); + target = new Vector3(); } - if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { - - console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); - - } + return target.subVectors( this.end, this.start ); }, - computeBoundingSphere: function () { + distanceSq: function () { - var box = new Box3(); - var vector = new Vector3(); + return this.start.distanceToSquared( this.end ); - return function computeBoundingSphere() { + }, - if ( this.boundingSphere === null ) { + distance: function () { - this.boundingSphere = new Sphere(); + return this.start.distanceTo( this.end ); - } + }, - var position = this.attributes.position; + at: function ( t, target ) { - if ( position ) { + if ( target === undefined ) { - var center = this.boundingSphere.center; + console.warn( 'THREE.Line3: .at() target is now required' ); + target = new Vector3(); - box.setFromBufferAttribute( position ); - box.getCenter( center ); + } - // hoping to find a boundingSphere with a radius smaller than the - // boundingSphere of the boundingBox: sqrt(3) smaller in the best case + return this.delta( target ).multiplyScalar( t ).add( this.start ); - var maxRadiusSq = 0; + }, - for ( var i = 0, il = position.count; i < il; i ++ ) { + closestPointToPointParameter: function () { - vector.x = position.getX( i ); - vector.y = position.getY( i ); - vector.z = position.getZ( i ); - maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) ); + var startP = new Vector3(); + var startEnd = new Vector3(); - } + return function closestPointToPointParameter( point, clampToLine ) { - this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); + startP.subVectors( point, this.start ); + startEnd.subVectors( this.end, this.start ); - if ( isNaN( this.boundingSphere.radius ) ) { + var startEnd2 = startEnd.dot( startEnd ); + var startEnd_startP = startEnd.dot( startP ); - console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); + var t = startEnd_startP / startEnd2; - } + if ( clampToLine ) { + + t = _Math.clamp( t, 0, 1 ); } + return t; + }; }(), - computeFaceNormals: function () { - - // backwards compatibility + closestPointToPoint: function ( point, clampToLine, target ) { - }, + var t = this.closestPointToPointParameter( point, clampToLine ); - computeVertexNormals: function () { + if ( target === undefined ) { - var index = this.index; - var attributes = this.attributes; - var groups = this.groups; + console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' ); + target = new Vector3(); - if ( attributes.position ) { + } - var positions = attributes.position.array; + return this.delta( target ).multiplyScalar( t ).add( this.start ); - if ( attributes.normal === undefined ) { + }, - this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) ); + applyMatrix4: function ( matrix ) { - } else { + this.start.applyMatrix4( matrix ); + this.end.applyMatrix4( matrix ); - // reset existing normals to zero + return this; - var array = attributes.normal.array; + }, - for ( var i = 0, il = array.length; i < il; i ++ ) { + equals: function ( line ) { - array[ i ] = 0; + return line.start.equals( this.start ) && line.end.equals( this.end ); - } + } - } + } ); - var normals = attributes.normal.array; + /** + * @author bhouston / http://clara.io + * @author mrdoob / http://mrdoob.com/ + */ - var vA, vB, vC; - var pA = new Vector3(), pB = new Vector3(), pC = new Vector3(); - var cb = new Vector3(), ab = new Vector3(); + function Triangle( a, b, c ) { - // indexed elements + this.a = ( a !== undefined ) ? a : new Vector3(); + this.b = ( b !== undefined ) ? b : new Vector3(); + this.c = ( c !== undefined ) ? c : new Vector3(); - if ( index ) { + } - var indices = index.array; + Object.assign( Triangle, { - if ( groups.length === 0 ) { + getNormal: function () { - this.addGroup( 0, indices.length ); + var v0 = new Vector3(); - } + return function getNormal( a, b, c, target ) { - for ( var j = 0, jl = groups.length; j < jl; ++ j ) { + if ( target === undefined ) { - var group = groups[ j ]; + console.warn( 'THREE.Triangle: .getNormal() target is now required' ); + target = new Vector3(); - var start = group.start; - var count = group.count; + } - for ( var i = start, il = start + count; i < il; i += 3 ) { + target.subVectors( c, b ); + v0.subVectors( a, b ); + target.cross( v0 ); - vA = indices[ i + 0 ] * 3; - vB = indices[ i + 1 ] * 3; - vC = indices[ i + 2 ] * 3; + var targetLengthSq = target.lengthSq(); + if ( targetLengthSq > 0 ) { - pA.fromArray( positions, vA ); - pB.fromArray( positions, vB ); - pC.fromArray( positions, vC ); + return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + } - normals[ vA ] += cb.x; - normals[ vA + 1 ] += cb.y; - normals[ vA + 2 ] += cb.z; + return target.set( 0, 0, 0 ); - normals[ vB ] += cb.x; - normals[ vB + 1 ] += cb.y; - normals[ vB + 2 ] += cb.z; + }; - normals[ vC ] += cb.x; - normals[ vC + 1 ] += cb.y; - normals[ vC + 2 ] += cb.z; + }(), - } + // static/instance method to calculate barycentric coordinates + // based on: http://www.blackpawn.com/texts/pointinpoly/default.html + getBarycoord: function () { - } + var v0 = new Vector3(); + var v1 = new Vector3(); + var v2 = new Vector3(); - } else { + return function getBarycoord( point, a, b, c, target ) { - // non-indexed elements (unconnected triangle soup) + v0.subVectors( c, a ); + v1.subVectors( b, a ); + v2.subVectors( point, a ); - for ( var i = 0, il = positions.length; i < il; i += 9 ) { + var dot00 = v0.dot( v0 ); + var dot01 = v0.dot( v1 ); + var dot02 = v0.dot( v2 ); + var dot11 = v1.dot( v1 ); + var dot12 = v1.dot( v2 ); - pA.fromArray( positions, i ); - pB.fromArray( positions, i + 3 ); - pC.fromArray( positions, i + 6 ); + var denom = ( dot00 * dot11 - dot01 * dot01 ); - cb.subVectors( pC, pB ); - ab.subVectors( pA, pB ); - cb.cross( ab ); + if ( target === undefined ) { - normals[ i ] = cb.x; - normals[ i + 1 ] = cb.y; - normals[ i + 2 ] = cb.z; + console.warn( 'THREE.Triangle: .getBarycoord() target is now required' ); + target = new Vector3(); - normals[ i + 3 ] = cb.x; - normals[ i + 4 ] = cb.y; - normals[ i + 5 ] = cb.z; + } - normals[ i + 6 ] = cb.x; - normals[ i + 7 ] = cb.y; - normals[ i + 8 ] = cb.z; + // collinear or singular triangle + if ( denom === 0 ) { - } + // arbitrary location outside of triangle? + // not sure if this is the best idea, maybe should be returning undefined + return target.set( - 2, - 1, - 1 ); } - this.normalizeNormals(); + var invDenom = 1 / denom; + var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; + var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; - attributes.normal.needsUpdate = true; + // barycentric coordinates must always sum to 1 + return target.set( 1 - u - v, v, u ); - } + }; - }, + }(), - merge: function ( geometry, offset ) { + containsPoint: function () { - if ( ! ( geometry && geometry.isBufferGeometry ) ) { + var v1 = new Vector3(); - console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); - return; + return function containsPoint( point, a, b, c ) { - } + Triangle.getBarycoord( point, a, b, c, v1 ); - if ( offset === undefined ) offset = 0; + return ( v1.x >= 0 ) && ( v1.y >= 0 ) && ( ( v1.x + v1.y ) <= 1 ); - var attributes = this.attributes; + }; - for ( var key in attributes ) { + }() - if ( geometry.attributes[ key ] === undefined ) continue; + } ); - var attribute1 = attributes[ key ]; - var attributeArray1 = attribute1.array; + Object.assign( Triangle.prototype, { - var attribute2 = geometry.attributes[ key ]; - var attributeArray2 = attribute2.array; + set: function ( a, b, c ) { - var attributeSize = attribute2.itemSize; + this.a.copy( a ); + this.b.copy( b ); + this.c.copy( c ); - for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) { + return this; - attributeArray1[ j ] = attributeArray2[ i ]; + }, - } + setFromPointsAndIndices: function ( points, i0, i1, i2 ) { - } + this.a.copy( points[ i0 ] ); + this.b.copy( points[ i1 ] ); + this.c.copy( points[ i2 ] ); return this; }, - normalizeNormals: function () { - - var normals = this.attributes.normal; - - var x, y, z, n; + clone: function () { - for ( var i = 0, il = normals.count; i < il; i ++ ) { + return new this.constructor().copy( this ); - x = normals.getX( i ); - y = normals.getY( i ); - z = normals.getZ( i ); + }, - n = 1.0 / Math.sqrt( x * x + y * y + z * z ); + copy: function ( triangle ) { - normals.setXYZ( i, x * n, y * n, z * n ); + this.a.copy( triangle.a ); + this.b.copy( triangle.b ); + this.c.copy( triangle.c ); - } + return this; }, - toNonIndexed: function () { + getArea: function () { - if ( this.index === null ) { + var v0 = new Vector3(); + var v1 = new Vector3(); - console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' ); - return this; + return function getArea() { - } + v0.subVectors( this.c, this.b ); + v1.subVectors( this.a, this.b ); - var geometry2 = new BufferGeometry(); + return v0.cross( v1 ).length() * 0.5; - var indices = this.index.array; - var attributes = this.attributes; + }; - for ( var name in attributes ) { + }(), - var attribute = attributes[ name ]; + getMidpoint: function ( target ) { - var array = attribute.array; - var itemSize = attribute.itemSize; + if ( target === undefined ) { - var array2 = new array.constructor( indices.length * itemSize ); + console.warn( 'THREE.Triangle: .getMidpoint() target is now required' ); + target = new Vector3(); - var index = 0, index2 = 0; + } - for ( var i = 0, l = indices.length; i < l; i ++ ) { + return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); - index = indices[ i ] * itemSize; + }, - for ( var j = 0; j < itemSize; j ++ ) { + getNormal: function ( target ) { - array2[ index2 ++ ] = array[ index ++ ]; + return Triangle.getNormal( this.a, this.b, this.c, target ); - } + }, - } + getPlane: function ( target ) { - geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) ); + if ( target === undefined ) { + + console.warn( 'THREE.Triangle: .getPlane() target is now required' ); + target = new Vector3(); } - return geometry2; + return target.setFromCoplanarPoints( this.a, this.b, this.c ); }, - toJSON: function () { + getBarycoord: function ( point, target ) { - var data = { - metadata: { - version: 4.5, - type: 'BufferGeometry', - generator: 'BufferGeometry.toJSON' - } - }; + return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); - // standard BufferGeometry serialization + }, - data.uuid = this.uuid; - data.type = this.type; - if ( this.name !== '' ) data.name = this.name; + containsPoint: function ( point ) { - if ( this.parameters !== undefined ) { + return Triangle.containsPoint( point, this.a, this.b, this.c ); - var parameters = this.parameters; + }, - for ( var key in parameters ) { + intersectsBox: function ( box ) { - if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ]; + return box.intersectsTriangle( this ); - } + }, - return data; + closestPointToPoint: function () { - } + var plane = new Plane(); + var edgeList = [ new Line3(), new Line3(), new Line3() ]; + var projectedPoint = new Vector3(); + var closestPoint = new Vector3(); - data.data = { attributes: {} }; + return function closestPointToPoint( point, target ) { - var index = this.index; + if ( target === undefined ) { - if ( index !== null ) { + console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' ); + target = new Vector3(); - var array = Array.prototype.slice.call( index.array ); + } - data.data.index = { - type: index.array.constructor.name, - array: array - }; + var minDistance = Infinity; - } + // project the point onto the plane of the triangle - var attributes = this.attributes; + plane.setFromCoplanarPoints( this.a, this.b, this.c ); + plane.projectPoint( point, projectedPoint ); - for ( var key in attributes ) { + // check if the projection lies within the triangle - var attribute = attributes[ key ]; + if ( this.containsPoint( projectedPoint ) === true ) { - var array = Array.prototype.slice.call( attribute.array ); + // if so, this is the closest point - data.data.attributes[ key ] = { - itemSize: attribute.itemSize, - type: attribute.array.constructor.name, - array: array, - normalized: attribute.normalized - }; + target.copy( projectedPoint ); - } + } else { - var groups = this.groups; + // if not, the point falls outside the triangle. the target is the closest point to the triangle's edges or vertices - if ( groups.length > 0 ) { + edgeList[ 0 ].set( this.a, this.b ); + edgeList[ 1 ].set( this.b, this.c ); + edgeList[ 2 ].set( this.c, this.a ); - data.data.groups = JSON.parse( JSON.stringify( groups ) ); + for ( var i = 0; i < edgeList.length; i ++ ) { - } + edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint ); - var boundingSphere = this.boundingSphere; + var distance = projectedPoint.distanceToSquared( closestPoint ); - if ( boundingSphere !== null ) { + if ( distance < minDistance ) { - data.data.boundingSphere = { - center: boundingSphere.center.toArray(), - radius: boundingSphere.radius - }; + minDistance = distance; - } + target.copy( closestPoint ); - return data; + } - }, + } - clone: function () { + } - /* - // Handle primitives + return target; - var parameters = this.parameters; + }; - if ( parameters !== undefined ) { + }(), - var values = []; + equals: function ( triangle ) { - for ( var key in parameters ) { + return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); - values.push( parameters[ key ] ); + } - } + } ); - var geometry = Object.create( this.constructor.prototype ); - this.constructor.apply( geometry, values ); - return geometry; + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author mikael emtinger / http://gomo.se/ + * @author jonobr1 / http://jonobr1.com/ + */ - } + function Mesh( geometry, material ) { - return new this.constructor().copy( this ); - */ + Object3D.call( this ); - return new BufferGeometry().copy( this ); + this.type = 'Mesh'; - }, + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } ); - copy: function ( source ) { + this.drawMode = TrianglesDrawMode; - var name, i, l; + this.updateMorphTargets(); - // reset + } - this.index = null; - this.attributes = {}; - this.morphAttributes = {}; - this.groups = []; - this.boundingBox = null; - this.boundingSphere = null; + Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { - // name + constructor: Mesh, - this.name = source.name; + isMesh: true, - // index + setDrawMode: function ( value ) { - var index = source.index; + this.drawMode = value; - if ( index !== null ) { + }, - this.setIndex( index.clone() ); + copy: function ( source ) { - } + Object3D.prototype.copy.call( this, source ); - // attributes + this.drawMode = source.drawMode; - var attributes = source.attributes; + if ( source.morphTargetInfluences !== undefined ) { - for ( name in attributes ) { + this.morphTargetInfluences = source.morphTargetInfluences.slice(); - var attribute = attributes[ name ]; - this.addAttribute( name, attribute.clone() ); + } + + if ( source.morphTargetDictionary !== undefined ) { + + this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary ); } - // morph attributes + return this; - var morphAttributes = source.morphAttributes; + }, - for ( name in morphAttributes ) { + updateMorphTargets: function () { - var array = []; - var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes + var geometry = this.geometry; + var m, ml, name; - for ( i = 0, l = morphAttribute.length; i < l; i ++ ) { + if ( geometry.isBufferGeometry ) { - array.push( morphAttribute[ i ].clone() ); + var morphAttributes = geometry.morphAttributes; + var keys = Object.keys( morphAttributes ); - } + if ( keys.length > 0 ) { - this.morphAttributes[ name ] = array; + var morphAttribute = morphAttributes[ keys[ 0 ] ]; - } + if ( morphAttribute !== undefined ) { - // groups + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - var groups = source.groups; + for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) { - for ( i = 0, l = groups.length; i < l; i ++ ) { + name = morphAttribute[ m ].name || String( m ); - var group = groups[ i ]; - this.addGroup( group.start, group.count, group.materialIndex ); + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; - } + } - // bounding box + } - var boundingBox = source.boundingBox; + } - if ( boundingBox !== null ) { + } else { - this.boundingBox = boundingBox.clone(); + var morphTargets = geometry.morphTargets; - } + if ( morphTargets !== undefined && morphTargets.length > 0 ) { - // bounding sphere + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; - var boundingSphere = source.boundingSphere; + for ( m = 0, ml = morphTargets.length; m < ml; m ++ ) { - if ( boundingSphere !== null ) { + name = morphTargets[ m ].name || String( m ); - this.boundingSphere = boundingSphere.clone(); + this.morphTargetInfluences.push( 0 ); + this.morphTargetDictionary[ name ] = m; + + } + + } } - // draw range + }, - this.drawRange.start = source.drawRange.start; - this.drawRange.count = source.drawRange.count; + raycast: ( function () { - return this; + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - }, + var vA = new Vector3(); + var vB = new Vector3(); + var vC = new Vector3(); - dispose: function () { + var tempA = new Vector3(); + var tempB = new Vector3(); + var tempC = new Vector3(); - this.dispatchEvent( { type: 'dispose' } ); + var uvA = new Vector2(); + var uvB = new Vector2(); + var uvC = new Vector2(); - } + var barycoord = new Vector3(); - } ); + var intersectionPoint = new Vector3(); + var intersectionPointWorld = new Vector3(); - /** - * @author mrdoob / http://mrdoob.com/ - * @author Mugen87 / https://github.com/Mugen87 - */ + function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { - // BoxGeometry + Triangle.getBarycoord( point, p1, p2, p3, barycoord ); - function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { + uv1.multiplyScalar( barycoord.x ); + uv2.multiplyScalar( barycoord.y ); + uv3.multiplyScalar( barycoord.z ); - Geometry.call( this ); + uv1.add( uv2 ).add( uv3 ); - this.type = 'BoxGeometry'; + return uv1.clone(); - this.parameters = { - width: width, - height: height, - depth: depth, - widthSegments: widthSegments, - heightSegments: heightSegments, - depthSegments: depthSegments - }; + } - this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); - this.mergeVertices(); + function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) { - } + var intersect; - BoxGeometry.prototype = Object.create( Geometry.prototype ); - BoxGeometry.prototype.constructor = BoxGeometry; + if ( material.side === BackSide ) { - // BoxBufferGeometry + intersect = ray.intersectTriangle( pC, pB, pA, true, point ); - function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { + } else { - BufferGeometry.call( this ); + intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point ); - this.type = 'BoxBufferGeometry'; + } - this.parameters = { - width: width, - height: height, - depth: depth, - widthSegments: widthSegments, - heightSegments: heightSegments, - depthSegments: depthSegments - }; + if ( intersect === null ) return null; - var scope = this; + intersectionPointWorld.copy( point ); + intersectionPointWorld.applyMatrix4( object.matrixWorld ); - // segments + var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld ); - widthSegments = Math.floor( widthSegments ) || 1; - heightSegments = Math.floor( heightSegments ) || 1; - depthSegments = Math.floor( depthSegments ) || 1; + if ( distance < raycaster.near || distance > raycaster.far ) return null; - // buffers + return { + distance: distance, + point: intersectionPointWorld.clone(), + object: object + }; - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + } - // helper variables + function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) { - var numberOfVertices = 0; - var groupStart = 0; + vA.fromBufferAttribute( position, a ); + vB.fromBufferAttribute( position, b ); + vC.fromBufferAttribute( position, c ); - // build each side of the box geometry + var intersection = checkIntersection( object, object.material, raycaster, ray, vA, vB, vC, intersectionPoint ); - buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px - buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx - buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py - buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny - buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz - buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz + if ( intersection ) { - // build geometry + if ( uv ) { - this.setIndex( indices ); - this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + uvA.fromBufferAttribute( uv, a ); + uvB.fromBufferAttribute( uv, b ); + uvC.fromBufferAttribute( uv, c ); - function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { + intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC ); - var segmentWidth = width / gridX; - var segmentHeight = height / gridY; + } - var widthHalf = width / 2; - var heightHalf = height / 2; - var depthHalf = depth / 2; + var face = new Face3( a, b, c ); + Triangle.getNormal( vA, vB, vC, face.normal ); - var gridX1 = gridX + 1; - var gridY1 = gridY + 1; + intersection.face = face; + intersection.faceIndex = a; - var vertexCounter = 0; - var groupCount = 0; + } - var ix, iy; + return intersection; - var vector = new Vector3(); + } - // generate vertices, normals and uvs + return function raycast( raycaster, intersects ) { - for ( iy = 0; iy < gridY1; iy ++ ) { + var geometry = this.geometry; + var material = this.material; + var matrixWorld = this.matrixWorld; - var y = iy * segmentHeight - heightHalf; + if ( material === undefined ) return; - for ( ix = 0; ix < gridX1; ix ++ ) { + // Checking boundingSphere distance to ray - var x = ix * segmentWidth - widthHalf; + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - // set values to correct vector component + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); - vector[ u ] = x * udir; - vector[ v ] = y * vdir; - vector[ w ] = depthHalf; + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; - // now apply vector to vertex buffer + // - vertices.push( vector.x, vector.y, vector.z ); + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - // set values to correct vector component + // Check boundingBox before continuing - vector[ u ] = 0; - vector[ v ] = 0; - vector[ w ] = depth > 0 ? 1 : - 1; + if ( geometry.boundingBox !== null ) { - // now apply vector to normal buffer + if ( ray.intersectsBox( geometry.boundingBox ) === false ) return; - normals.push( vector.x, vector.y, vector.z ); + } - // uvs + var intersection; - uvs.push( ix / gridX ); - uvs.push( 1 - ( iy / gridY ) ); + if ( geometry.isBufferGeometry ) { - // counters + var a, b, c; + var index = geometry.index; + var position = geometry.attributes.position; + var uv = geometry.attributes.uv; + var i, l; - vertexCounter += 1; + if ( index !== null ) { - } + // indexed buffer geometry - } + for ( i = 0, l = index.count; i < l; i += 3 ) { - // indices + a = index.getX( i ); + b = index.getX( i + 1 ); + c = index.getX( i + 2 ); - // 1. you need three indices to draw a single face - // 2. a single segment consists of two faces - // 3. so we need to generate six (2*3) indices per segment + intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c ); - for ( iy = 0; iy < gridY; iy ++ ) { + if ( intersection ) { - for ( ix = 0; ix < gridX; ix ++ ) { + intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics + intersects.push( intersection ); - var a = numberOfVertices + ix + gridX1 * iy; - var b = numberOfVertices + ix + gridX1 * ( iy + 1 ); - var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); - var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; + } - // faces + } - indices.push( a, b, d ); - indices.push( b, c, d ); + } else if ( position !== undefined ) { - // increase counter + // non-indexed buffer geometry - groupCount += 6; + for ( i = 0, l = position.count; i < l; i += 3 ) { - } + a = i; + b = i + 1; + c = i + 2; - } + intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c ); - // add a group to the geometry. this will ensure multi material support + if ( intersection ) { - scope.addGroup( groupStart, groupCount, materialIndex ); + intersection.index = a; // triangle number in positions buffer semantics + intersects.push( intersection ); - // calculate new start value for groups + } - groupStart += groupCount; + } - // update total number of vertices + } - numberOfVertices += vertexCounter; + } else if ( geometry.isGeometry ) { - } + var fvA, fvB, fvC; + var isMultiMaterial = Array.isArray( material ); - } + var vertices = geometry.vertices; + var faces = geometry.faces; + var uvs; - BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - BoxBufferGeometry.prototype.constructor = BoxBufferGeometry; + var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; + if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs; - /** - * @author mrdoob / http://mrdoob.com/ - * @author Mugen87 / https://github.com/Mugen87 - */ + for ( var f = 0, fl = faces.length; f < fl; f ++ ) { - // PlaneGeometry + var face = faces[ f ]; + var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material; - function PlaneGeometry( width, height, widthSegments, heightSegments ) { + if ( faceMaterial === undefined ) continue; - Geometry.call( this ); + fvA = vertices[ face.a ]; + fvB = vertices[ face.b ]; + fvC = vertices[ face.c ]; - this.type = 'PlaneGeometry'; + if ( faceMaterial.morphTargets === true ) { - this.parameters = { - width: width, - height: height, - widthSegments: widthSegments, - heightSegments: heightSegments - }; + var morphTargets = geometry.morphTargets; + var morphInfluences = this.morphTargetInfluences; - this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); - this.mergeVertices(); + vA.set( 0, 0, 0 ); + vB.set( 0, 0, 0 ); + vC.set( 0, 0, 0 ); - } + for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { - PlaneGeometry.prototype = Object.create( Geometry.prototype ); - PlaneGeometry.prototype.constructor = PlaneGeometry; + var influence = morphInfluences[ t ]; - // PlaneBufferGeometry + if ( influence === 0 ) continue; - function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) { + var targets = morphTargets[ t ].vertices; - BufferGeometry.call( this ); + vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence ); + vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence ); + vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence ); - this.type = 'PlaneBufferGeometry'; + } - this.parameters = { - width: width, - height: height, - widthSegments: widthSegments, - heightSegments: heightSegments - }; + vA.add( fvA ); + vB.add( fvB ); + vC.add( fvC ); - var width_half = width / 2; - var height_half = height / 2; + fvA = vA; + fvB = vB; + fvC = vC; - var gridX = Math.floor( widthSegments ) || 1; - var gridY = Math.floor( heightSegments ) || 1; + } - var gridX1 = gridX + 1; - var gridY1 = gridY + 1; + intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint ); - var segment_width = width / gridX; - var segment_height = height / gridY; + if ( intersection ) { - var ix, iy; + if ( uvs && uvs[ f ] ) { - // buffers + var uvs_f = uvs[ f ]; + uvA.copy( uvs_f[ 0 ] ); + uvB.copy( uvs_f[ 1 ] ); + uvC.copy( uvs_f[ 2 ] ); - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC ); - // generate vertices, normals and uvs + } - for ( iy = 0; iy < gridY1; iy ++ ) { + intersection.face = face; + intersection.faceIndex = f; + intersects.push( intersection ); - var y = iy * segment_height - height_half; + } - for ( ix = 0; ix < gridX1; ix ++ ) { + } - var x = ix * segment_width - width_half; + } - vertices.push( x, - y, 0 ); + }; - normals.push( 0, 0, 1 ); + }() ), - uvs.push( ix / gridX ); - uvs.push( 1 - ( iy / gridY ) ); + clone: function () { - } + return new this.constructor( this.geometry, this.material ).copy( this ); } - // indices + } ); - for ( iy = 0; iy < gridY; iy ++ ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - for ( ix = 0; ix < gridX; ix ++ ) { + function WebGLBackground( renderer, state, geometries, premultipliedAlpha ) { - var a = ix + gridX1 * iy; - var b = ix + gridX1 * ( iy + 1 ); - var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); - var d = ( ix + 1 ) + gridX1 * iy; + var clearColor = new Color( 0x000000 ); + var clearAlpha = 0; - // faces + var planeCamera, planeMesh; + var boxMesh; - indices.push( a, b, d ); - indices.push( b, c, d ); + function render( renderList, scene, camera, forceClear ) { + + var background = scene.background; + + if ( background === null ) { + + setClear( clearColor, clearAlpha ); + + } else if ( background && background.isColor ) { + + setClear( background, 1 ); + forceClear = true; } - } + if ( renderer.autoClear || forceClear ) { - // build geometry + renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil ); - this.setIndex( indices ); - this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + } - } + if ( background && background.isCubeTexture ) { - PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry; + if ( boxMesh === undefined ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * shading: THREE.SmoothShading, - * depthTest: , - * depthWrite: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: - * } - */ + boxMesh = new Mesh( + new BoxBufferGeometry( 1, 1, 1 ), + new ShaderMaterial( { + uniforms: ShaderLib.cube.uniforms, + vertexShader: ShaderLib.cube.vertexShader, + fragmentShader: ShaderLib.cube.fragmentShader, + side: BackSide, + depthTest: true, + depthWrite: false, + fog: false + } ) + ); - function MeshBasicMaterial( parameters ) { + boxMesh.geometry.removeAttribute( 'normal' ); + boxMesh.geometry.removeAttribute( 'uv' ); - Material.call( this ); + boxMesh.onBeforeRender = function ( renderer, scene, camera ) { - this.type = 'MeshBasicMaterial'; + this.matrixWorld.copyPosition( camera.matrixWorld ); - this.color = new Color( 0xffffff ); // emissive + }; - this.map = null; + geometries.update( boxMesh.geometry ); - this.lightMap = null; - this.lightMapIntensity = 1.0; + } - this.aoMap = null; - this.aoMapIntensity = 1.0; + boxMesh.material.uniforms.tCube.value = background; - this.specularMap = null; + renderList.push( boxMesh, boxMesh.geometry, boxMesh.material, 0, null ); - this.alphaMap = null; + } else if ( background && background.isTexture ) { - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + if ( planeCamera === undefined ) { - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + planeCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); - this.skinning = false; - this.morphTargets = false; + planeMesh = new Mesh( + new PlaneBufferGeometry( 2, 2 ), + new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } ) + ); - this.lights = false; + geometries.update( planeMesh.geometry ); - this.setValues( parameters ); + } - } + planeMesh.material.map = background; - MeshBasicMaterial.prototype = Object.create( Material.prototype ); - MeshBasicMaterial.prototype.constructor = MeshBasicMaterial; + // TODO Push this to renderList - MeshBasicMaterial.prototype.isMeshBasicMaterial = true; + renderer.renderBufferDirect( planeCamera, null, planeMesh.geometry, planeMesh.material, planeMesh, null ); - MeshBasicMaterial.prototype.copy = function ( source ) { + } - Material.prototype.copy.call( this, source ); + } - this.color.copy( source.color ); + function setClear( color, alpha ) { - this.map = source.map; + state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha ); - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + } - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + return { - this.specularMap = source.specularMap; + getClearColor: function () { - this.alphaMap = source.alphaMap; + return clearColor; - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + }, + setClearColor: function ( color, alpha ) { - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + clearColor.set( color ); + clearAlpha = alpha !== undefined ? alpha : 1; + setClear( clearColor, clearAlpha ); - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; + }, + getClearAlpha: function () { - return this; + return clearAlpha; - }; + }, + setClearAlpha: function ( alpha ) { - /** - * @author bhouston / http://clara.io - */ + clearAlpha = alpha; + setClear( clearColor, clearAlpha ); - function Ray( origin, direction ) { + }, + render: render - this.origin = ( origin !== undefined ) ? origin : new Vector3(); - this.direction = ( direction !== undefined ) ? direction : new Vector3(); + }; } - Object.assign( Ray.prototype, { + /** + * @author mrdoob / http://mrdoob.com/ + */ - set: function ( origin, direction ) { + function WebGLBufferRenderer( gl, extensions, info ) { - this.origin.copy( origin ); - this.direction.copy( direction ); + var mode; - return this; + function setMode( value ) { - }, + mode = value; - clone: function () { + } - return new this.constructor().copy( this ); + function render( start, count ) { - }, + gl.drawArrays( mode, start, count ); - copy: function ( ray ) { + info.update( count, mode ); - this.origin.copy( ray.origin ); - this.direction.copy( ray.direction ); + } - return this; + function renderInstances( geometry, start, count ) { - }, + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - at: function ( t, optionalTarget ) { + if ( extension === null ) { - var result = optionalTarget || new Vector3(); + console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - return result.copy( this.direction ).multiplyScalar( t ).add( this.origin ); + } - }, + var position = geometry.attributes.position; - lookAt: function ( v ) { + if ( position.isInterleavedBufferAttribute ) { - this.direction.copy( v ).sub( this.origin ).normalize(); + count = position.data.count; - return this; + extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); - }, + } else { - recast: function () { + extension.drawArraysInstancedANGLE( mode, start, count, geometry.maxInstancedCount ); - var v1 = new Vector3(); + } - return function recast( t ) { + info.update( count, mode, geometry.maxInstancedCount ); - this.origin.copy( this.at( t, v1 ) ); + } - return this; + // - }; + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; - }(), + } - closestPointToPoint: function ( point, optionalTarget ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - var result = optionalTarget || new Vector3(); - result.subVectors( point, this.origin ); - var directionDistance = result.dot( this.direction ); + function WebGLCapabilities( gl, extensions, parameters ) { - if ( directionDistance < 0 ) { + var maxAnisotropy; - return result.copy( this.origin ); + function getMaxAnisotropy() { - } + if ( maxAnisotropy !== undefined ) return maxAnisotropy; - return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - }, + if ( extension !== null ) { - distanceToPoint: function ( point ) { + maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); - return Math.sqrt( this.distanceSqToPoint( point ) ); + } else { - }, + maxAnisotropy = 0; - distanceSqToPoint: function () { + } - var v1 = new Vector3(); + return maxAnisotropy; - return function distanceSqToPoint( point ) { + } - var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction ); + function getMaxPrecision( precision ) { - // point behind the ray + if ( precision === 'highp' ) { - if ( directionDistance < 0 ) { + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { - return this.origin.distanceToSquared( point ); + return 'highp'; } - v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); + precision = 'mediump'; - return v1.distanceToSquared( point ); + } - }; + if ( precision === 'mediump' ) { - }(), + if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && + gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { - distanceSqToSegment: function () { + return 'mediump'; - var segCenter = new Vector3(); - var segDir = new Vector3(); - var diff = new Vector3(); + } - return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { + } - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h - // It returns the min distance between the ray and the segment - // defined by v0 and v1 - // It can also set two optional targets : - // - The closest point on the ray - // - The closest point on the segment + return 'lowp'; - segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); - segDir.copy( v1 ).sub( v0 ).normalize(); - diff.copy( this.origin ).sub( segCenter ); + } - var segExtent = v0.distanceTo( v1 ) * 0.5; - var a01 = - this.direction.dot( segDir ); - var b0 = diff.dot( this.direction ); - var b1 = - diff.dot( segDir ); - var c = diff.lengthSq(); - var det = Math.abs( 1 - a01 * a01 ); - var s0, s1, sqrDist, extDet; + var precision = parameters.precision !== undefined ? parameters.precision : 'highp'; + var maxPrecision = getMaxPrecision( precision ); - if ( det > 0 ) { + if ( maxPrecision !== precision ) { - // The ray and segment are not parallel. + console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' ); + precision = maxPrecision; - s0 = a01 * b1 - b0; - s1 = a01 * b0 - b1; - extDet = segExtent * det; + } - if ( s0 >= 0 ) { + var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; - if ( s1 >= - extDet ) { + var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); + var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); + var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE ); + var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE ); - if ( s1 <= extDet ) { + var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); + var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS ); + var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS ); + var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS ); - // region 0 - // Minimum at interior points of ray and segment. + var vertexTextures = maxVertexTextures > 0; + var floatFragmentTextures = !! extensions.get( 'OES_texture_float' ); + var floatVertexTextures = vertexTextures && floatFragmentTextures; - var invDet = 1 / det; - s0 *= invDet; - s1 *= invDet; - sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; + return { - } else { + getMaxAnisotropy: getMaxAnisotropy, + getMaxPrecision: getMaxPrecision, - // region 1 + precision: precision, + logarithmicDepthBuffer: logarithmicDepthBuffer, - s1 = segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + maxTextures: maxTextures, + maxVertexTextures: maxVertexTextures, + maxTextureSize: maxTextureSize, + maxCubemapSize: maxCubemapSize, - } + maxAttributes: maxAttributes, + maxVertexUniforms: maxVertexUniforms, + maxVaryings: maxVaryings, + maxFragmentUniforms: maxFragmentUniforms, - } else { + vertexTextures: vertexTextures, + floatFragmentTextures: floatFragmentTextures, + floatVertexTextures: floatVertexTextures - // region 5 + }; - s1 = - segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + } - } + /** + * @author tschw + */ - } else { + function WebGLClipping() { - if ( s1 <= - extDet ) { + var scope = this, - // region 4 + globalState = null, + numGlobalPlanes = 0, + localClippingEnabled = false, + renderingShadows = false, - s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + plane = new Plane(), + viewNormalMatrix = new Matrix3(), - } else if ( s1 <= extDet ) { + uniform = { value: null, needsUpdate: false }; - // region 3 + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; - s0 = 0; - s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = s1 * ( s1 + 2 * b1 ) + c; + this.init = function ( planes, enableLocalClipping, camera ) { - } else { + var enabled = + planes.length !== 0 || + enableLocalClipping || + // enable state of previous frame - the clipping code has to + // run another frame in order to reset the state: + numGlobalPlanes !== 0 || + localClippingEnabled; - // region 2 + localClippingEnabled = enableLocalClipping; - s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); - s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + globalState = projectPlanes( planes, camera, 0 ); + numGlobalPlanes = planes.length; - } + return enabled; - } + }; - } else { + this.beginShadows = function () { - // Ray and segment are parallel. + renderingShadows = true; + projectPlanes( null ); - s1 = ( a01 > 0 ) ? - segExtent : segExtent; - s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); - sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; + }; - } + this.endShadows = function () { - if ( optionalPointOnRay ) { + renderingShadows = false; + resetGlobalState(); - optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); + }; - } + this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) { - if ( optionalPointOnSegment ) { + if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) { - optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter ); + // there's no local clipping - } + if ( renderingShadows ) { - return sqrDist; + // there's no global clipping - }; + projectPlanes( null ); - }(), + } else { - intersectSphere: function () { + resetGlobalState(); - var v1 = new Vector3(); + } - return function intersectSphere( sphere, optionalTarget ) { + } else { - v1.subVectors( sphere.center, this.origin ); - var tca = v1.dot( this.direction ); - var d2 = v1.dot( v1 ) - tca * tca; - var radius2 = sphere.radius * sphere.radius; + var nGlobal = renderingShadows ? 0 : numGlobalPlanes, + lGlobal = nGlobal * 4, - if ( d2 > radius2 ) return null; + dstArray = cache.clippingState || null; - var thc = Math.sqrt( radius2 - d2 ); + uniform.value = dstArray; // ensure unique state - // t0 = first intersect point - entrance on front of sphere - var t0 = tca - thc; + dstArray = projectPlanes( planes, camera, lGlobal, fromCache ); - // t1 = second intersect point - exit point on back of sphere - var t1 = tca + thc; + for ( var i = 0; i !== lGlobal; ++ i ) { - // test to see if both t0 and t1 are behind the ray - if so, return null - if ( t0 < 0 && t1 < 0 ) return null; + dstArray[ i ] = globalState[ i ]; - // test to see if t0 is behind the ray: - // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, - // in order to always return an intersect point that is in front of the ray. - if ( t0 < 0 ) return this.at( t1, optionalTarget ); + } - // else t0 is in front of the ray, so return the first collision point scaled by t0 - return this.at( t0, optionalTarget ); + cache.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; - }; + } - }(), - intersectsSphere: function ( sphere ) { + }; - return this.distanceToPoint( sphere.center ) <= sphere.radius; + function resetGlobalState() { - }, + if ( uniform.value !== globalState ) { - distanceToPlane: function ( plane ) { + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; - var denominator = plane.normal.dot( this.direction ); + } - if ( denominator === 0 ) { + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; - // line is coplanar, return origin - if ( plane.distanceToPoint( this.origin ) === 0 ) { + } - return 0; + function projectPlanes( planes, camera, dstOffset, skipTransform ) { - } + var nPlanes = planes !== null ? planes.length : 0, + dstArray = null; - // Null is preferable to undefined since undefined means.... it is undefined + if ( nPlanes !== 0 ) { - return null; + dstArray = uniform.value; - } + if ( skipTransform !== true || dstArray === null ) { - var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; + var flatSize = dstOffset + nPlanes * 4, + viewMatrix = camera.matrixWorldInverse; - // Return if the ray never intersects the plane + viewNormalMatrix.getNormalMatrix( viewMatrix ); - return t >= 0 ? t : null; + if ( dstArray === null || dstArray.length < flatSize ) { - }, + dstArray = new Float32Array( flatSize ); - intersectPlane: function ( plane, optionalTarget ) { + } - var t = this.distanceToPlane( plane ); + for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) { - if ( t === null ) { + plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix ); - return null; + plane.normal.toArray( dstArray, i4 ); + dstArray[ i4 + 3 ] = plane.constant; - } + } - return this.at( t, optionalTarget ); + } - }, + uniform.value = dstArray; + uniform.needsUpdate = true; - intersectsPlane: function ( plane ) { + } - // check if the ray lies on the plane first + scope.numPlanes = nPlanes; - var distToPoint = plane.distanceToPoint( this.origin ); + return dstArray; - if ( distToPoint === 0 ) { + } - return true; + } - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - var denominator = plane.normal.dot( this.direction ); + function WebGLExtensions( gl ) { - if ( denominator * distToPoint < 0 ) { + var extensions = {}; - return true; + return { - } + get: function ( name ) { - // ray origin is behind the plane (and is pointing behind it) + if ( extensions[ name ] !== undefined ) { - return false; + return extensions[ name ]; - }, + } - intersectBox: function ( box, optionalTarget ) { + var extension; - var tmin, tmax, tymin, tymax, tzmin, tzmax; + switch ( name ) { - var invdirx = 1 / this.direction.x, - invdiry = 1 / this.direction.y, - invdirz = 1 / this.direction.z; + case 'WEBGL_depth_texture': + extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); + break; - var origin = this.origin; + case 'EXT_texture_filter_anisotropic': + extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); + break; - if ( invdirx >= 0 ) { + case 'WEBGL_compressed_texture_s3tc': + extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); + break; - tmin = ( box.min.x - origin.x ) * invdirx; - tmax = ( box.max.x - origin.x ) * invdirx; - - } else { - - tmin = ( box.max.x - origin.x ) * invdirx; - tmax = ( box.min.x - origin.x ) * invdirx; - - } - - if ( invdiry >= 0 ) { - - tymin = ( box.min.y - origin.y ) * invdiry; - tymax = ( box.max.y - origin.y ) * invdiry; - - } else { - - tymin = ( box.max.y - origin.y ) * invdiry; - tymax = ( box.min.y - origin.y ) * invdiry; - - } + case 'WEBGL_compressed_texture_pvrtc': + extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); + break; - if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null; + case 'WEBGL_compressed_texture_etc1': + extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' ); + break; - // These lines also handle the case where tmin or tmax is NaN - // (result of 0 * Infinity). x !== x returns true if x is NaN + default: + extension = gl.getExtension( name ); - if ( tymin > tmin || tmin !== tmin ) tmin = tymin; + } - if ( tymax < tmax || tmax !== tmax ) tmax = tymax; + if ( extension === null ) { - if ( invdirz >= 0 ) { + console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); - tzmin = ( box.min.z - origin.z ) * invdirz; - tzmax = ( box.max.z - origin.z ) * invdirz; + } - } else { + extensions[ name ] = extension; - tzmin = ( box.max.z - origin.z ) * invdirz; - tzmax = ( box.min.z - origin.z ) * invdirz; + return extension; } - if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null; - - if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin; - - if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax; - - //return point closest to the ray (positive side) - - if ( tmax < 0 ) return null; + }; - return this.at( tmin >= 0 ? tmin : tmax, optionalTarget ); + } - }, + /** + * @author mrdoob / http://mrdoob.com/ + */ - intersectsBox: ( function () { + function WebGLGeometries( gl, attributes, info ) { - var v = new Vector3(); + var geometries = {}; + var wireframeAttributes = {}; - return function intersectsBox( box ) { + function onGeometryDispose( event ) { - return this.intersectBox( box, v ) !== null; + var geometry = event.target; + var buffergeometry = geometries[ geometry.id ]; - }; + if ( buffergeometry.index !== null ) { - } )(), + attributes.remove( buffergeometry.index ); - intersectTriangle: function () { + } - // Compute the offset origin, edges, and normal. - var diff = new Vector3(); - var edge1 = new Vector3(); - var edge2 = new Vector3(); - var normal = new Vector3(); + for ( var name in buffergeometry.attributes ) { - return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) { + attributes.remove( buffergeometry.attributes[ name ] ); - // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h + } - edge1.subVectors( b, a ); - edge2.subVectors( c, a ); - normal.crossVectors( edge1, edge2 ); + geometry.removeEventListener( 'dispose', onGeometryDispose ); - // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, - // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by - // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) - // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) - // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) - var DdN = this.direction.dot( normal ); - var sign; + delete geometries[ geometry.id ]; - if ( DdN > 0 ) { + // TODO Remove duplicate code - if ( backfaceCulling ) return null; - sign = 1; + var attribute = wireframeAttributes[ geometry.id ]; - } else if ( DdN < 0 ) { + if ( attribute ) { - sign = - 1; - DdN = - DdN; + attributes.remove( attribute ); + delete wireframeAttributes[ geometry.id ]; - } else { + } - return null; + attribute = wireframeAttributes[ buffergeometry.id ]; - } + if ( attribute ) { - diff.subVectors( this.origin, a ); - var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) ); + attributes.remove( attribute ); + delete wireframeAttributes[ buffergeometry.id ]; - // b1 < 0, no intersection - if ( DdQxE2 < 0 ) { + } - return null; + // - } + info.memory.geometries --; - var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) ); + } - // b2 < 0, no intersection - if ( DdE1xQ < 0 ) { + function get( object, geometry ) { - return null; + var buffergeometry = geometries[ geometry.id ]; - } + if ( buffergeometry ) return buffergeometry; - // b1+b2 > 1, no intersection - if ( DdQxE2 + DdE1xQ > DdN ) { + geometry.addEventListener( 'dispose', onGeometryDispose ); - return null; + if ( geometry.isBufferGeometry ) { - } + buffergeometry = geometry; - // Line intersects triangle, check if ray does. - var QdN = - sign * diff.dot( normal ); + } else if ( geometry.isGeometry ) { - // t < 0, no intersection - if ( QdN < 0 ) { + if ( geometry._bufferGeometry === undefined ) { - return null; + geometry._bufferGeometry = new BufferGeometry().setFromObject( object ); } - // Ray intersects triangle. - return this.at( QdN / DdN, optionalTarget ); + buffergeometry = geometry._bufferGeometry; - }; + } - }(), + geometries[ geometry.id ] = buffergeometry; - applyMatrix4: function ( matrix4 ) { + info.memory.geometries ++; - this.origin.applyMatrix4( matrix4 ); - this.direction.transformDirection( matrix4 ); + return buffergeometry; - return this; + } - }, + function update( geometry ) { - equals: function ( ray ) { + var index = geometry.index; + var geometryAttributes = geometry.attributes; - return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); + if ( index !== null ) { - } + attributes.update( index, gl.ELEMENT_ARRAY_BUFFER ); - } ); + } - /** - * @author bhouston / http://clara.io - */ + for ( var name in geometryAttributes ) { - function Line3( start, end ) { + attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER ); - this.start = ( start !== undefined ) ? start : new Vector3(); - this.end = ( end !== undefined ) ? end : new Vector3(); + } - } + // morph targets - Object.assign( Line3.prototype, { + var morphAttributes = geometry.morphAttributes; - set: function ( start, end ) { + for ( var name in morphAttributes ) { - this.start.copy( start ); - this.end.copy( end ); + var array = morphAttributes[ name ]; - return this; + for ( var i = 0, l = array.length; i < l; i ++ ) { - }, + attributes.update( array[ i ], gl.ARRAY_BUFFER ); - clone: function () { + } - return new this.constructor().copy( this ); + } - }, + } - copy: function ( line ) { + function getWireframeAttribute( geometry ) { - this.start.copy( line.start ); - this.end.copy( line.end ); + var attribute = wireframeAttributes[ geometry.id ]; - return this; + if ( attribute ) return attribute; - }, + var indices = []; - getCenter: function ( optionalTarget ) { + var geometryIndex = geometry.index; + var geometryAttributes = geometry.attributes; - var result = optionalTarget || new Vector3(); - return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); + // console.time( 'wireframe' ); - }, + if ( geometryIndex !== null ) { - delta: function ( optionalTarget ) { + var array = geometryIndex.array; - var result = optionalTarget || new Vector3(); - return result.subVectors( this.end, this.start ); + for ( var i = 0, l = array.length; i < l; i += 3 ) { - }, + var a = array[ i + 0 ]; + var b = array[ i + 1 ]; + var c = array[ i + 2 ]; - distanceSq: function () { + indices.push( a, b, b, c, c, a ); - return this.start.distanceToSquared( this.end ); + } - }, + } else { - distance: function () { + var array = geometryAttributes.position.array; - return this.start.distanceTo( this.end ); + for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { - }, + var a = i + 0; + var b = i + 1; + var c = i + 2; - at: function ( t, optionalTarget ) { + indices.push( a, b, b, c, c, a ); - var result = optionalTarget || new Vector3(); + } - return this.delta( result ).multiplyScalar( t ).add( this.start ); + } - }, + // console.timeEnd( 'wireframe' ); - closestPointToPointParameter: function () { + attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); - var startP = new Vector3(); - var startEnd = new Vector3(); + attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER ); - return function closestPointToPointParameter( point, clampToLine ) { + wireframeAttributes[ geometry.id ] = attribute; - startP.subVectors( point, this.start ); - startEnd.subVectors( this.end, this.start ); + return attribute; - var startEnd2 = startEnd.dot( startEnd ); - var startEnd_startP = startEnd.dot( startP ); + } - var t = startEnd_startP / startEnd2; + return { - if ( clampToLine ) { + get: get, + update: update, - t = _Math.clamp( t, 0, 1 ); + getWireframeAttribute: getWireframeAttribute - } + }; - return t; + } - }; + /** + * @author mrdoob / http://mrdoob.com/ + */ - }(), + function WebGLIndexedBufferRenderer( gl, extensions, info ) { - closestPointToPoint: function ( point, clampToLine, optionalTarget ) { + var mode; - var t = this.closestPointToPointParameter( point, clampToLine ); + function setMode( value ) { - var result = optionalTarget || new Vector3(); + mode = value; - return this.delta( result ).multiplyScalar( t ).add( this.start ); + } - }, + var type, bytesPerElement; - applyMatrix4: function ( matrix ) { + function setIndex( value ) { - this.start.applyMatrix4( matrix ); - this.end.applyMatrix4( matrix ); + type = value.type; + bytesPerElement = value.bytesPerElement; - return this; + } - }, + function render( start, count ) { - equals: function ( line ) { + gl.drawElements( mode, count, type, start * bytesPerElement ); - return line.start.equals( this.start ) && line.end.equals( this.end ); + info.update( count, mode ); } - } ); - - /** - * @author bhouston / http://clara.io - * @author mrdoob / http://mrdoob.com/ - */ + function renderInstances( geometry, start, count ) { - function Triangle( a, b, c ) { + var extension = extensions.get( 'ANGLE_instanced_arrays' ); - this.a = ( a !== undefined ) ? a : new Vector3(); - this.b = ( b !== undefined ) ? b : new Vector3(); - this.c = ( c !== undefined ) ? c : new Vector3(); + if ( extension === null ) { - } + console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - Object.assign( Triangle, { + } - normal: function () { + extension.drawElementsInstancedANGLE( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount ); - var v0 = new Vector3(); + info.update( count, mode, geometry.maxInstancedCount ); - return function normal( a, b, c, optionalTarget ) { + } - var result = optionalTarget || new Vector3(); + // - result.subVectors( c, b ); - v0.subVectors( a, b ); - result.cross( v0 ); + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; - var resultLengthSq = result.lengthSq(); - if ( resultLengthSq > 0 ) { + } - return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) ); + /** + * @author Mugen87 / https://github.com/Mugen87 + */ - } + function WebGLInfo( gl ) { - return result.set( 0, 0, 0 ); + var memory = { + geometries: 0, + textures: 0 + }; - }; + var render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; - }(), + function update( count, mode, instanceCount ) { - // static/instance method to calculate barycentric coordinates - // based on: http://www.blackpawn.com/texts/pointinpoly/default.html - barycoordFromPoint: function () { + instanceCount = instanceCount || 1; - var v0 = new Vector3(); - var v1 = new Vector3(); - var v2 = new Vector3(); + render.calls ++; - return function barycoordFromPoint( point, a, b, c, optionalTarget ) { + switch ( mode ) { - v0.subVectors( c, a ); - v1.subVectors( b, a ); - v2.subVectors( point, a ); + case gl.TRIANGLES: + render.triangles += instanceCount * ( count / 3 ); + break; - var dot00 = v0.dot( v0 ); - var dot01 = v0.dot( v1 ); - var dot02 = v0.dot( v2 ); - var dot11 = v1.dot( v1 ); - var dot12 = v1.dot( v2 ); + case gl.TRIANGLE_STRIP: + case gl.TRIANGLE_FAN: + render.triangles += instanceCount * ( count - 2 ); + break; - var denom = ( dot00 * dot11 - dot01 * dot01 ); + case gl.LINES: + render.lines += instanceCount * ( count / 2 ); + break; - var result = optionalTarget || new Vector3(); + case gl.LINE_STRIP: + render.lines += instanceCount * ( count - 1 ); + break; - // collinear or singular triangle - if ( denom === 0 ) { + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; - // arbitrary location outside of triangle? - // not sure if this is the best idea, maybe should be returning undefined - return result.set( - 2, - 1, - 1 ); + case gl.POINTS: + render.points += instanceCount * count; + break; - } + default: + console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode ); + break; - var invDenom = 1 / denom; - var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; - var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; + } - // barycentric coordinates must always sum to 1 - return result.set( 1 - u - v, v, u ); + } - }; + function reset() { - }(), + render.frame ++; + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; - containsPoint: function () { + } - var v1 = new Vector3(); + return { + memory: memory, + render: render, + programs: null, + autoReset: true, + reset: reset, + update: update + }; - return function containsPoint( point, a, b, c ) { + } - var result = Triangle.barycoordFromPoint( point, a, b, c, v1 ); + /** + * @author mrdoob / http://mrdoob.com/ + */ - return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 ); + function absNumericalSort( a, b ) { - }; + return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] ); - }() + } - } ); + function WebGLMorphtargets( gl ) { - Object.assign( Triangle.prototype, { + var influencesList = {}; + var morphInfluences = new Float32Array( 8 ); - set: function ( a, b, c ) { + function update( object, geometry, material, program ) { - this.a.copy( a ); - this.b.copy( b ); - this.c.copy( c ); + var objectInfluences = object.morphTargetInfluences; - return this; + var length = objectInfluences.length; - }, + var influences = influencesList[ geometry.id ]; - setFromPointsAndIndices: function ( points, i0, i1, i2 ) { + if ( influences === undefined ) { - this.a.copy( points[ i0 ] ); - this.b.copy( points[ i1 ] ); - this.c.copy( points[ i2 ] ); + // initialise list - return this; + influences = []; - }, + for ( var i = 0; i < length; i ++ ) { - clone: function () { + influences[ i ] = [ i, 0 ]; - return new this.constructor().copy( this ); + } - }, + influencesList[ geometry.id ] = influences; - copy: function ( triangle ) { + } - this.a.copy( triangle.a ); - this.b.copy( triangle.b ); - this.c.copy( triangle.c ); + var morphTargets = material.morphTargets && geometry.morphAttributes.position; + var morphNormals = material.morphNormals && geometry.morphAttributes.normal; - return this; + // Remove current morphAttributes - }, + for ( var i = 0; i < length; i ++ ) { - area: function () { + var influence = influences[ i ]; - var v0 = new Vector3(); - var v1 = new Vector3(); + if ( influence[ 1 ] !== 0 ) { - return function area() { + if ( morphTargets ) geometry.removeAttribute( 'morphTarget' + i ); + if ( morphNormals ) geometry.removeAttribute( 'morphNormal' + i ); - v0.subVectors( this.c, this.b ); - v1.subVectors( this.a, this.b ); + } - return v0.cross( v1 ).length() * 0.5; + } - }; + // Collect influences - }(), + for ( var i = 0; i < length; i ++ ) { - midpoint: function ( optionalTarget ) { + var influence = influences[ i ]; - var result = optionalTarget || new Vector3(); - return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); + influence[ 0 ] = i; + influence[ 1 ] = objectInfluences[ i ]; - }, + } - normal: function ( optionalTarget ) { + influences.sort( absNumericalSort ); - return Triangle.normal( this.a, this.b, this.c, optionalTarget ); + // Add morphAttributes - }, + for ( var i = 0; i < 8; i ++ ) { - plane: function ( optionalTarget ) { + var influence = influences[ i ]; - var result = optionalTarget || new Plane(); + if ( influence ) { - return result.setFromCoplanarPoints( this.a, this.b, this.c ); + var index = influence[ 0 ]; + var value = influence[ 1 ]; - }, + if ( value ) { - barycoordFromPoint: function ( point, optionalTarget ) { + if ( morphTargets ) geometry.addAttribute( 'morphTarget' + i, morphTargets[ index ] ); + if ( morphNormals ) geometry.addAttribute( 'morphNormal' + i, morphNormals[ index ] ); - return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget ); + morphInfluences[ i ] = value; + continue; - }, + } - containsPoint: function ( point ) { + } - return Triangle.containsPoint( point, this.a, this.b, this.c ); + morphInfluences[ i ] = 0; - }, + } - closestPointToPoint: function () { + program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences ); - var plane = new Plane(); - var edgeList = [ new Line3(), new Line3(), new Line3() ]; - var projectedPoint = new Vector3(); - var closestPoint = new Vector3(); + } - return function closestPointToPoint( point, optionalTarget ) { + return { - var result = optionalTarget || new Vector3(); - var minDistance = Infinity; + update: update - // project the point onto the plane of the triangle + }; - plane.setFromCoplanarPoints( this.a, this.b, this.c ); - plane.projectPoint( point, projectedPoint ); + } - // check if the projection lies within the triangle + /** + * @author mrdoob / http://mrdoob.com/ + */ - if( this.containsPoint( projectedPoint ) === true ) { + function WebGLObjects( geometries, info ) { - // if so, this is the closest point + var updateList = {}; - result.copy( projectedPoint ); + function update( object ) { - } else { + var frame = info.render.frame; - // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices + var geometry = object.geometry; + var buffergeometry = geometries.get( object, geometry ); - edgeList[ 0 ].set( this.a, this.b ); - edgeList[ 1 ].set( this.b, this.c ); - edgeList[ 2 ].set( this.c, this.a ); + // Update once per frame - for( var i = 0; i < edgeList.length; i ++ ) { + if ( updateList[ buffergeometry.id ] !== frame ) { - edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint ); + if ( geometry.isGeometry ) { - var distance = projectedPoint.distanceToSquared( closestPoint ); + buffergeometry.updateFromObject( object ); - if( distance < minDistance ) { + } - minDistance = distance; + geometries.update( buffergeometry ); - result.copy( closestPoint ); + updateList[ buffergeometry.id ] = frame; - } + } - } + return buffergeometry; - } + } - return result; + function dispose() { - }; + updateList = {}; - }(), + } - equals: function ( triangle ) { + return { - return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); + update: update, + dispose: dispose - } + }; - } ); + } /** * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author mikael emtinger / http://gomo.se/ - * @author jonobr1 / http://jonobr1.com/ */ - function Mesh( geometry, material ) { - - Object3D.call( this ); - - this.type = 'Mesh'; + function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { - this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); - this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } ); + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; - this.drawMode = TrianglesDrawMode; + Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - this.updateMorphTargets(); + this.flipY = false; } - Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { + CubeTexture.prototype = Object.create( Texture.prototype ); + CubeTexture.prototype.constructor = CubeTexture; - constructor: Mesh, + CubeTexture.prototype.isCubeTexture = true; - isMesh: true, + Object.defineProperty( CubeTexture.prototype, 'images', { - setDrawMode: function ( value ) { + get: function () { - this.drawMode = value; + return this.image; }, - copy: function ( source ) { + set: function ( value ) { - Object3D.prototype.copy.call( this, source ); + this.image = value; - this.drawMode = source.drawMode; + } - return this; - - }, + } ); - updateMorphTargets: function () { + /** + * @author tschw + * + * Uniforms of a program. + * Those form a tree structure with a special top-level container for the root, + * which you get by calling 'new WebGLUniforms( gl, program, renderer )'. + * + * + * Properties of inner nodes including the top-level container: + * + * .seq - array of nested uniforms + * .map - nested uniforms by name + * + * + * Methods of all nodes except the top-level container: + * + * .setValue( gl, value, [renderer] ) + * + * uploads a uniform value(s) + * the 'renderer' parameter is needed for sampler uniforms + * + * + * Static methods of the top-level container (renderer factorizations): + * + * .upload( gl, seq, values, renderer ) + * + * sets uniforms in 'seq' to 'values[id].value' + * + * .seqWithValue( seq, values ) : filteredSeq + * + * filters 'seq' entries with corresponding entry in values + * + * + * Methods of the top-level container (renderer factorizations): + * + * .setValue( gl, name, value ) + * + * sets uniform with name 'name' to 'value' + * + * .set( gl, obj, prop ) + * + * sets uniform from object and property with same name than uniform + * + * .setOptional( gl, obj, prop ) + * + * like .set for an optional property of the object + * + */ - var geometry = this.geometry; - var m, ml, name; + var emptyTexture = new Texture(); + var emptyCubeTexture = new CubeTexture(); - if ( geometry.isBufferGeometry ) { + // --- Base for inner nodes (including the root) --- - var morphAttributes = geometry.morphAttributes; - var keys = Object.keys( morphAttributes ); + function UniformContainer() { - if ( keys.length > 0 ) { + this.seq = []; + this.map = {}; - var morphAttribute = morphAttributes[ keys[ 0 ] ]; + } - if ( morphAttribute !== undefined ) { + // --- Utilities --- - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + // Array Caches (provide typed arrays for temporary by size) - for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) { + var arrayCacheF32 = []; + var arrayCacheI32 = []; - name = morphAttribute[ m ].name || String( m ); + // Float32Array caches used for uploading Matrix uniforms - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + var mat4array = new Float32Array( 16 ); + var mat3array = new Float32Array( 9 ); - } + // Flattening for arrays of vectors and matrices - } + function flatten( array, nBlocks, blockSize ) { - } + var firstElem = array[ 0 ]; - } else { + if ( firstElem <= 0 || firstElem > 0 ) return array; + // unoptimized: ! isNaN( firstElem ) + // see http://jacksondunstan.com/articles/983 - var morphTargets = geometry.morphTargets; + var n = nBlocks * blockSize, + r = arrayCacheF32[ n ]; - if ( morphTargets !== undefined && morphTargets.length > 0 ) { + if ( r === undefined ) { - this.morphTargetInfluences = []; - this.morphTargetDictionary = {}; + r = new Float32Array( n ); + arrayCacheF32[ n ] = r; - for ( m = 0, ml = morphTargets.length; m < ml; m ++ ) { + } - name = morphTargets[ m ].name || String( m ); + if ( nBlocks !== 0 ) { - this.morphTargetInfluences.push( 0 ); - this.morphTargetDictionary[ name ] = m; + firstElem.toArray( r, 0 ); - } + for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) { - } + offset += blockSize; + array[ i ].toArray( r, offset ); } - }, + } - raycast: ( function () { + return r; - var inverseMatrix = new Matrix4(); - var ray = new Ray(); - var sphere = new Sphere(); + } - var vA = new Vector3(); - var vB = new Vector3(); - var vC = new Vector3(); + // Texture unit allocation - var tempA = new Vector3(); - var tempB = new Vector3(); - var tempC = new Vector3(); + function allocTexUnits( renderer, n ) { - var uvA = new Vector2(); - var uvB = new Vector2(); - var uvC = new Vector2(); + var r = arrayCacheI32[ n ]; - var barycoord = new Vector3(); + if ( r === undefined ) { - var intersectionPoint = new Vector3(); - var intersectionPointWorld = new Vector3(); + r = new Int32Array( n ); + arrayCacheI32[ n ] = r; - function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) { + } - Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord ); + for ( var i = 0; i !== n; ++ i ) + r[ i ] = renderer.allocTextureUnit(); - uv1.multiplyScalar( barycoord.x ); - uv2.multiplyScalar( barycoord.y ); - uv3.multiplyScalar( barycoord.z ); + return r; - uv1.add( uv2 ).add( uv3 ); + } - return uv1.clone(); + // --- Setters --- - } + // Note: Defining these methods externally, because they come in a bunch + // and this way their names minify. - function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) { + // Single scalar - var intersect; - var material = object.material; + function setValue1f( gl, v ) { - if ( material.side === BackSide ) { + gl.uniform1f( this.addr, v ); - intersect = ray.intersectTriangle( pC, pB, pA, true, point ); + } - } else { + function setValue1i( gl, v ) { - intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point ); + gl.uniform1i( this.addr, v ); - } + } - if ( intersect === null ) return null; + // Single float vector (from flat array or THREE.VectorN) - intersectionPointWorld.copy( point ); - intersectionPointWorld.applyMatrix4( object.matrixWorld ); + function setValue2fv( gl, v ) { - var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld ); + if ( v.x === undefined ) { - if ( distance < raycaster.near || distance > raycaster.far ) return null; + gl.uniform2fv( this.addr, v ); - return { - distance: distance, - point: intersectionPointWorld.clone(), - object: object - }; + } else { - } + gl.uniform2f( this.addr, v.x, v.y ); - function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) { + } - vA.fromBufferAttribute( position, a ); - vB.fromBufferAttribute( position, b ); - vC.fromBufferAttribute( position, c ); + } - var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint ); + function setValue3fv( gl, v ) { - if ( intersection ) { + if ( v.x !== undefined ) { - if ( uv ) { + gl.uniform3f( this.addr, v.x, v.y, v.z ); - uvA.fromBufferAttribute( uv, a ); - uvB.fromBufferAttribute( uv, b ); - uvC.fromBufferAttribute( uv, c ); + } else if ( v.r !== undefined ) { - intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC ); + gl.uniform3f( this.addr, v.r, v.g, v.b ); - } + } else { - intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) ); - intersection.faceIndex = a; + gl.uniform3fv( this.addr, v ); - } + } - return intersection; + } - } + function setValue4fv( gl, v ) { - return function raycast( raycaster, intersects ) { + if ( v.x === undefined ) { - var geometry = this.geometry; - var material = this.material; - var matrixWorld = this.matrixWorld; + gl.uniform4fv( this.addr, v ); - if ( material === undefined ) return; + } else { - // Checking boundingSphere distance to ray + gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + } - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); + } - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + // Single matrix (from flat array or MatrixN) - // + function setValue2fm( gl, v ) { - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + gl.uniformMatrix2fv( this.addr, false, v.elements || v ); - // Check boundingBox before continuing + } - if ( geometry.boundingBox !== null ) { + function setValue3fm( gl, v ) { - if ( ray.intersectsBox( geometry.boundingBox ) === false ) return; + if ( v.elements === undefined ) { - } + gl.uniformMatrix3fv( this.addr, false, v ); - var intersection; + } else { - if ( geometry.isBufferGeometry ) { + mat3array.set( v.elements ); + gl.uniformMatrix3fv( this.addr, false, mat3array ); - var a, b, c; - var index = geometry.index; - var position = geometry.attributes.position; - var uv = geometry.attributes.uv; - var i, l; + } - if ( index !== null ) { + } - // indexed buffer geometry + function setValue4fm( gl, v ) { - for ( i = 0, l = index.count; i < l; i += 3 ) { + if ( v.elements === undefined ) { - a = index.getX( i ); - b = index.getX( i + 1 ); - c = index.getX( i + 2 ); + gl.uniformMatrix4fv( this.addr, false, v ); - intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c ); + } else { - if ( intersection ) { + mat4array.set( v.elements ); + gl.uniformMatrix4fv( this.addr, false, mat4array ); - intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics - intersects.push( intersection ); + } - } + } - } + // Single texture (2D / Cube) - } else { + function setValueT1( gl, v, renderer ) { - // non-indexed buffer geometry + var unit = renderer.allocTextureUnit(); + gl.uniform1i( this.addr, unit ); + renderer.setTexture2D( v || emptyTexture, unit ); - for ( i = 0, l = position.count; i < l; i += 3 ) { + } - a = i; - b = i + 1; - c = i + 2; + function setValueT6( gl, v, renderer ) { - intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c ); + var unit = renderer.allocTextureUnit(); + gl.uniform1i( this.addr, unit ); + renderer.setTextureCube( v || emptyCubeTexture, unit ); - if ( intersection ) { + } - intersection.index = a; // triangle number in positions buffer semantics - intersects.push( intersection ); + // Integer / Boolean vectors or arrays thereof (always flat arrays) - } + function setValue2iv( gl, v ) { - } + gl.uniform2iv( this.addr, v ); - } + } - } else if ( geometry.isGeometry ) { + function setValue3iv( gl, v ) { - var fvA, fvB, fvC; - var isMultiMaterial = Array.isArray( material ); + gl.uniform3iv( this.addr, v ); - var vertices = geometry.vertices; - var faces = geometry.faces; - var uvs; + } - var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; - if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs; + function setValue4iv( gl, v ) { - for ( var f = 0, fl = faces.length; f < fl; f ++ ) { + gl.uniform4iv( this.addr, v ); - var face = faces[ f ]; - var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material; + } - if ( faceMaterial === undefined ) continue; + // Helper to pick the right setter for the singular case - fvA = vertices[ face.a ]; - fvB = vertices[ face.b ]; - fvC = vertices[ face.c ]; + function getSingularSetter( type ) { - if ( faceMaterial.morphTargets === true ) { + switch ( type ) { - var morphTargets = geometry.morphTargets; - var morphInfluences = this.morphTargetInfluences; + case 0x1406: return setValue1f; // FLOAT + case 0x8b50: return setValue2fv; // _VEC2 + case 0x8b51: return setValue3fv; // _VEC3 + case 0x8b52: return setValue4fv; // _VEC4 - vA.set( 0, 0, 0 ); - vB.set( 0, 0, 0 ); - vC.set( 0, 0, 0 ); + case 0x8b5a: return setValue2fm; // _MAT2 + case 0x8b5b: return setValue3fm; // _MAT3 + case 0x8b5c: return setValue4fm; // _MAT4 - for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) { + case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES + case 0x8b60: return setValueT6; // SAMPLER_CUBE - var influence = morphInfluences[ t ]; + case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL + case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 + case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 + case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 - if ( influence === 0 ) continue; + } - var targets = morphTargets[ t ].vertices; + } - vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence ); - vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence ); - vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence ); + // Array of scalars - } + function setValue1fv( gl, v ) { - vA.add( fvA ); - vB.add( fvB ); - vC.add( fvC ); + gl.uniform1fv( this.addr, v ); - fvA = vA; - fvB = vB; - fvC = vC; + } + function setValue1iv( gl, v ) { - } + gl.uniform1iv( this.addr, v ); - intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint ); + } - if ( intersection ) { + // Array of vectors (flat or from THREE classes) - if ( uvs && uvs[ f ] ) { + function setValueV2a( gl, v ) { - var uvs_f = uvs[ f ]; - uvA.copy( uvs_f[ 0 ] ); - uvB.copy( uvs_f[ 1 ] ); - uvC.copy( uvs_f[ 2 ] ); + gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) ); - intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC ); + } - } + function setValueV3a( gl, v ) { - intersection.face = face; - intersection.faceIndex = f; - intersects.push( intersection ); + gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) ); - } + } - } + function setValueV4a( gl, v ) { - } + gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) ); - }; + } - }() ), + // Array of matrices (flat or from THREE clases) - clone: function () { + function setValueM2a( gl, v ) { - return new this.constructor( this.geometry, this.material ).copy( this ); + gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) ); - } + } - } ); + function setValueM3a( gl, v ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) ); - function WebGLBackground( renderer, state, objects, premultipliedAlpha ) { + } - var clearColor = new Color( 0x000000 ); - var clearAlpha = 0; + function setValueM4a( gl, v ) { - var planeCamera, planeMesh; - var boxCamera, boxMesh; + gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) ); - function render( scene, camera, forceClear ) { + } - var background = scene.background; + // Array of textures (2D / Cube) - if ( background === null ) { + function setValueT1a( gl, v, renderer ) { - setClear( clearColor, clearAlpha ); + var n = v.length, + units = allocTexUnits( renderer, n ); - } else if ( background && background.isColor ) { + gl.uniform1iv( this.addr, units ); - setClear( background, 1 ); - forceClear = true; + for ( var i = 0; i !== n; ++ i ) { - } + renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] ); - if ( renderer.autoClear || forceClear ) { + } - renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil ); + } - } + function setValueT6a( gl, v, renderer ) { - if ( background && background.isCubeTexture ) { + var n = v.length, + units = allocTexUnits( renderer, n ); - if ( boxCamera === undefined ) { + gl.uniform1iv( this.addr, units ); - boxCamera = new PerspectiveCamera(); + for ( var i = 0; i !== n; ++ i ) { - boxMesh = new Mesh( - new BoxBufferGeometry( 5, 5, 5 ), - new ShaderMaterial( { - uniforms: ShaderLib.cube.uniforms, - vertexShader: ShaderLib.cube.vertexShader, - fragmentShader: ShaderLib.cube.fragmentShader, - side: BackSide, - depthTest: false, - depthWrite: false, - fog: false - } ) - ); + renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); - } + } - boxCamera.projectionMatrix.copy( camera.projectionMatrix ); + } - boxCamera.matrixWorld.extractRotation( camera.matrixWorld ); - boxCamera.matrixWorldInverse.getInverse( boxCamera.matrixWorld ); + // Helper to pick the right setter for a pure (bottom-level) array - boxMesh.material.uniforms[ "tCube" ].value = background; - boxMesh.modelViewMatrix.multiplyMatrices( boxCamera.matrixWorldInverse, boxMesh.matrixWorld ); + function getPureArraySetter( type ) { - objects.update( boxMesh ); + switch ( type ) { - renderer.renderBufferDirect( boxCamera, null, boxMesh.geometry, boxMesh.material, boxMesh, null ); + case 0x1406: return setValue1fv; // FLOAT + case 0x8b50: return setValueV2a; // _VEC2 + case 0x8b51: return setValueV3a; // _VEC3 + case 0x8b52: return setValueV4a; // _VEC4 - } else if ( background && background.isTexture ) { + case 0x8b5a: return setValueM2a; // _MAT2 + case 0x8b5b: return setValueM3a; // _MAT3 + case 0x8b5c: return setValueM4a; // _MAT4 - if ( planeCamera === undefined ) { + case 0x8b5e: return setValueT1a; // SAMPLER_2D + case 0x8b60: return setValueT6a; // SAMPLER_CUBE - planeCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); + case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL + case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 + case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 + case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 - planeMesh = new Mesh( - new PlaneBufferGeometry( 2, 2 ), - new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } ) - ); + } - } + } - planeMesh.material.map = background; + // --- Uniform Classes --- - objects.update( planeMesh ); + function SingleUniform( id, activeInfo, addr ) { - renderer.renderBufferDirect( planeCamera, null, planeMesh.geometry, planeMesh.material, planeMesh, null ); + this.id = id; + this.addr = addr; + this.setValue = getSingularSetter( activeInfo.type ); - } + // this.path = activeInfo.name; // DEBUG - } + } - function setClear( color, alpha ) { + function PureArrayUniform( id, activeInfo, addr ) { - state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha ); + this.id = id; + this.addr = addr; + this.size = activeInfo.size; + this.setValue = getPureArraySetter( activeInfo.type ); - } + // this.path = activeInfo.name; // DEBUG - return { + } - getClearColor: function () { + function StructuredUniform( id ) { - return clearColor; + this.id = id; - }, - setClearColor: function ( color, alpha ) { + UniformContainer.call( this ); // mix-in - clearColor.set( color ); - clearAlpha = alpha !== undefined ? alpha : 1; - setClear( clearColor, clearAlpha ); + } - }, - getClearAlpha: function () { + StructuredUniform.prototype.setValue = function ( gl, value ) { - return clearAlpha; + // Note: Don't need an extra 'renderer' parameter, since samplers + // are not allowed in structured uniforms. - }, - setClearAlpha: function ( alpha ) { + var seq = this.seq; - clearAlpha = alpha; - setClear( clearColor, clearAlpha ); + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - }, - render: render + var u = seq[ i ]; + u.setValue( gl, value[ u.id ] ); - }; + } - } + }; - /** - * @author mrdoob / http://mrdoob.com/ - */ + // --- Top-level --- - function painterSortStable( a, b ) { + // Parser - builds up the property tree from the path strings - if ( a.renderOrder !== b.renderOrder ) { + var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; - return a.renderOrder - b.renderOrder; + // extracts + // - the identifier (member name or array index) + // - followed by an optional right bracket (found when array index) + // - followed by an optional left bracket or dot (type of subscript) + // + // Note: These portions can be read in a non-overlapping fashion and + // allow straightforward parsing of the hierarchy that WebGL encodes + // in the uniform names. - } else if ( a.program && b.program && a.program !== b.program ) { + function addUniform( container, uniformObject ) { - return a.program.id - b.program.id; + container.seq.push( uniformObject ); + container.map[ uniformObject.id ] = uniformObject; - } else if ( a.material.id !== b.material.id ) { + } - return a.material.id - b.material.id; + function parseUniform( activeInfo, addr, container ) { - } else if ( a.z !== b.z ) { + var path = activeInfo.name, + pathLength = path.length; - return a.z - b.z; + // reset RegExp object, because of the early exit of a previous run + RePathPart.lastIndex = 0; - } else { + for ( ; ; ) { - return a.id - b.id; + var match = RePathPart.exec( path ), + matchEnd = RePathPart.lastIndex, - } + id = match[ 1 ], + idIsIndex = match[ 2 ] === ']', + subscript = match[ 3 ]; - } + if ( idIsIndex ) id = id | 0; // convert to integer - function reversePainterSortStable( a, b ) { + if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { - if ( a.renderOrder !== b.renderOrder ) { + // bare name or "pure" bottom-level array "[0]" suffix - return a.renderOrder - b.renderOrder; + addUniform( container, subscript === undefined ? + new SingleUniform( id, activeInfo, addr ) : + new PureArrayUniform( id, activeInfo, addr ) ); - } if ( a.z !== b.z ) { + break; - return b.z - a.z; + } else { - } else { + // step into inner node / create it in case it doesn't exist - return a.id - b.id; + var map = container.map, next = map[ id ]; + + if ( next === undefined ) { + + next = new StructuredUniform( id ); + addUniform( container, next ); + + } + + container = next; + + } } } - function WebGLRenderList() { + // Root Container - var opaque = []; - var opaqueLastIndex = - 1; + function WebGLUniforms( gl, program, renderer ) { - var transparent = []; - var transparentLastIndex = - 1; + UniformContainer.call( this ); - function init() { + this.renderer = renderer; + + var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS ); + + for ( var i = 0; i < n; ++ i ) { + + var info = gl.getActiveUniform( program, i ), + path = info.name, + addr = gl.getUniformLocation( program, path ); - opaqueLastIndex = - 1; - transparentLastIndex = - 1; + parseUniform( info, addr, this ); } - function push( object, geometry, material, z, group ) { + } - var array, index; + WebGLUniforms.prototype.setValue = function ( gl, name, value ) { - // allocate the next position in the appropriate array + var u = this.map[ name ]; - if ( material.transparent ) { + if ( u !== undefined ) u.setValue( gl, value, this.renderer ); - array = transparent; - index = ++ transparentLastIndex; + }; - } else { + WebGLUniforms.prototype.setOptional = function ( gl, object, name ) { - array = opaque; - index = ++ opaqueLastIndex; + var v = object[ name ]; - } + if ( v !== undefined ) this.setValue( gl, name, v ); - // recycle existing render item or grow the array + }; - var renderItem = array[ index ]; - if ( renderItem ) { + // Static interface - renderItem.id = object.id; - renderItem.object = object; - renderItem.geometry = geometry; - renderItem.material = material; - renderItem.program = material.program; - renderItem.renderOrder = object.renderOrder; - renderItem.z = z; - renderItem.group = group; + WebGLUniforms.upload = function ( gl, seq, values, renderer ) { - } else { + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - renderItem = { - id: object.id, - object: object, - geometry: geometry, - material: material, - program: material.program, - renderOrder: object.renderOrder, - z: z, - group: group - }; + var u = seq[ i ], + v = values[ u.id ]; + + if ( v.needsUpdate !== false ) { - // assert( index === array.length ); - array.push( renderItem ); + // note: always updating when .needsUpdate is undefined + u.setValue( gl, v.value, renderer ); } } - function finish() { + }; - opaque.length = opaqueLastIndex + 1; - transparent.length = transparentLastIndex + 1; + WebGLUniforms.seqWithValue = function ( seq, values ) { - } + var r = []; - function sort() { + for ( var i = 0, n = seq.length; i !== n; ++ i ) { - opaque.sort( painterSortStable ); - transparent.sort( reversePainterSortStable ); + var u = seq[ i ]; + if ( u.id in values ) r.push( u ); } - return { - opaque: opaque, - transparent: transparent, + return r; - init: init, - push: push, - finish: finish, + }; - sort: sort - }; + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function addLineNumbers( string ) { - function WebGLRenderLists() { + var lines = string.split( '\n' ); - var lists = {}; + for ( var i = 0; i < lines.length; i ++ ) { - function get( scene, camera ) { + lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; - var hash = scene.id + ',' + camera.id; - var list = lists[ hash ]; + } - if ( list === undefined ) { + return lines.join( '\n' ); - // console.log( 'THREE.WebGLRenderLists:', hash ); + } - list = new WebGLRenderList(); - lists[ hash ] = list; + function WebGLShader( gl, type, string ) { - } + var shader = gl.createShader( type ); - return list; + gl.shaderSource( shader, string ); + gl.compileShader( shader ); + + if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { + + console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); } - function dispose() { + if ( gl.getShaderInfoLog( shader ) !== '' ) { - lists = {}; + console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) ); } - return { - get: get, - dispose: dispose - }; + // --enable-privileged-webgl-extension + // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); + + return shader; } @@ -16504,847 +16103,356 @@ * @author mrdoob / http://mrdoob.com/ */ - function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) { + var programIdCount = 0; - var mode; + function getEncodingComponents( encoding ) { - function setMode( value ) { + switch ( encoding ) { - mode = value; + case LinearEncoding: + return [ 'Linear', '( value )' ]; + case sRGBEncoding: + return [ 'sRGB', '( value )' ]; + case RGBEEncoding: + return [ 'RGBE', '( value )' ]; + case RGBM7Encoding: + return [ 'RGBM', '( value, 7.0 )' ]; + case RGBM16Encoding: + return [ 'RGBM', '( value, 16.0 )' ]; + case RGBDEncoding: + return [ 'RGBD', '( value, 256.0 )' ]; + case GammaEncoding: + return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ]; + default: + throw new Error( 'unsupported encoding: ' + encoding ); } - var type, bytesPerElement; - - function setIndex( value ) { - - type = value.type; - bytesPerElement = value.bytesPerElement; + } - } + function getTexelDecodingFunction( functionName, encoding ) { - function render( start, count ) { + var components = getEncodingComponents( encoding ); + return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }'; - gl.drawElements( mode, count, type, start * bytesPerElement ); + } - infoRender.calls ++; - infoRender.vertices += count; + function getTexelEncodingFunction( functionName, encoding ) { - if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3; + var components = getEncodingComponents( encoding ); + return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }'; - } + } - function renderInstances( geometry, start, count ) { + function getToneMappingFunction( functionName, toneMapping ) { - var extension = extensions.get( 'ANGLE_instanced_arrays' ); + var toneMappingName; - if ( extension === null ) { + switch ( toneMapping ) { - console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + case LinearToneMapping: + toneMappingName = 'Linear'; + break; - } + case ReinhardToneMapping: + toneMappingName = 'Reinhard'; + break; - extension.drawElementsInstancedANGLE( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount ); + case Uncharted2ToneMapping: + toneMappingName = 'Uncharted2'; + break; - infoRender.calls ++; - infoRender.vertices += count * geometry.maxInstancedCount; + case CineonToneMapping: + toneMappingName = 'OptimizedCineon'; + break; - if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3; + default: + throw new Error( 'unsupported toneMapping: ' + toneMapping ); } - // - - this.setMode = setMode; - this.setIndex = setIndex; - this.render = render; - this.renderInstances = renderInstances; + return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; } - /** - * @author mrdoob / http://mrdoob.com/ - */ + function generateExtensions( extensions, parameters, rendererExtensions ) { - function WebGLBufferRenderer( gl, extensions, infoRender ) { + extensions = extensions || {}; - var mode; + var chunks = [ + ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '', + ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '', + ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '', + ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '' + ]; - function setMode( value ) { + return chunks.filter( filterEmptyLine ).join( '\n' ); - mode = value; + } - } + function generateDefines( defines ) { - function render( start, count ) { + var chunks = []; - gl.drawArrays( mode, start, count ); + for ( var name in defines ) { + + var value = defines[ name ]; - infoRender.calls ++; - infoRender.vertices += count; + if ( value === false ) continue; - if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3; + chunks.push( '#define ' + name + ' ' + value ); } - function renderInstances( geometry, start, count ) { + return chunks.join( '\n' ); - var extension = extensions.get( 'ANGLE_instanced_arrays' ); + } - if ( extension === null ) { + function fetchAttributeLocations( gl, program ) { - console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + var attributes = {}; - } + var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); - var position = geometry.attributes.position; + for ( var i = 0; i < n; i ++ ) { - if ( position.isInterleavedBufferAttribute ) { + var info = gl.getActiveAttrib( program, i ); + var name = info.name; - count = position.data.count; + // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); - extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount ); + attributes[ name ] = gl.getAttribLocation( program, name ); - } else { + } - extension.drawArraysInstancedANGLE( mode, start, count, geometry.maxInstancedCount ); + return attributes; - } + } - infoRender.calls ++; - infoRender.vertices += count * geometry.maxInstancedCount; + function filterEmptyLine( string ) { - if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3; + return string !== ''; - } + } - // + function replaceLightNums( string, parameters ) { - this.setMode = setMode; - this.render = render; - this.renderInstances = renderInstances; + return string + .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) + .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) + .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) + .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) + .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ); } - /** - * @author mrdoob / http://mrdoob.com/ - */ - - function WebGLGeometries( gl, attributes, infoMemory ) { + function replaceClippingPlaneNums( string, parameters ) { - var geometries = {}; - var wireframeAttributes = {}; + return string + .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes ) + .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) ); - function onGeometryDispose( event ) { + } - var geometry = event.target; - var buffergeometry = geometries[ geometry.id ]; + function parseIncludes( string ) { - if ( buffergeometry.index !== null ) { + var pattern = /^[ \t]*#include +<([\w\d.]+)>/gm; - attributes.remove( buffergeometry.index ); + function replace( match, include ) { - } + var replace = ShaderChunk[ include ]; - for ( var name in buffergeometry.attributes ) { + if ( replace === undefined ) { - attributes.remove( buffergeometry.attributes[ name ] ); + throw new Error( 'Can not resolve #include <' + include + '>' ); } - geometry.removeEventListener( 'dispose', onGeometryDispose ); + return parseIncludes( replace ); - delete geometries[ geometry.id ]; + } - // TODO Remove duplicate code + return string.replace( pattern, replace ); - var attribute = wireframeAttributes[ geometry.id ]; + } - if ( attribute ) { + function unrollLoops( string ) { - attributes.remove( attribute ); - delete wireframeAttributes[ geometry.id ]; + var pattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; - } + function replace( match, start, end, snippet ) { - attribute = wireframeAttributes[ buffergeometry.id ]; + var unroll = ''; - if ( attribute ) { + for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) { - attributes.remove( attribute ); - delete wireframeAttributes[ buffergeometry.id ]; + unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' ); } - // - - infoMemory.geometries --; + return unroll; } - function get( object, geometry ) { - - var buffergeometry = geometries[ geometry.id ]; - - if ( buffergeometry ) return buffergeometry; - - geometry.addEventListener( 'dispose', onGeometryDispose ); - - if ( geometry.isBufferGeometry ) { + return string.replace( pattern, replace ); - buffergeometry = geometry; + } - } else if ( geometry.isGeometry ) { + function WebGLProgram( renderer, extensions, code, material, shader, parameters ) { - if ( geometry._bufferGeometry === undefined ) { + var gl = renderer.context; - geometry._bufferGeometry = new BufferGeometry().setFromObject( object ); + var defines = material.defines; - } + var vertexShader = shader.vertexShader; + var fragmentShader = shader.fragmentShader; - buffergeometry = geometry._bufferGeometry; + var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; - } + if ( parameters.shadowMapType === PCFShadowMap ) { - geometries[ geometry.id ] = buffergeometry; + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; - infoMemory.geometries ++; + } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { - return buffergeometry; + shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; } - function update( geometry ) { + var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; + var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - var index = geometry.index; - var geometryAttributes = geometry.attributes; + if ( parameters.envMap ) { - if ( index !== null ) { + switch ( material.envMap.mapping ) { - attributes.update( index, gl.ELEMENT_ARRAY_BUFFER ); + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; + break; - } + case CubeUVReflectionMapping: + case CubeUVRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; + break; - for ( var name in geometryAttributes ) { + case EquirectangularReflectionMapping: + case EquirectangularRefractionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; + break; - attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER ); + case SphericalReflectionMapping: + envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; + break; } - // morph targets + switch ( material.envMap.mapping ) { - var morphAttributes = geometry.morphAttributes; + case CubeRefractionMapping: + case EquirectangularRefractionMapping: + envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; + break; - for ( var name in morphAttributes ) { + } - var array = morphAttributes[ name ]; + switch ( material.combine ) { - for ( var i = 0, l = array.length; i < l; i ++ ) { + case MultiplyOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; + break; - attributes.update( array[ i ], gl.ARRAY_BUFFER ); + case MixOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; + break; - } + case AddOperation: + envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; + break; } } - function getWireframeAttribute( geometry ) { - - var attribute = wireframeAttributes[ geometry.id ]; + var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; - if ( attribute ) return attribute; + // console.log( 'building new program ' ); - var indices = []; + // - var geometryIndex = geometry.index; - var geometryAttributes = geometry.attributes; + var customExtensions = generateExtensions( material.extensions, parameters, extensions ); - // console.time( 'wireframe' ); + var customDefines = generateDefines( defines ); - if ( geometryIndex !== null ) { + // - var array = geometryIndex.array; + var program = gl.createProgram(); - for ( var i = 0, l = array.length; i < l; i += 3 ) { + var prefixVertex, prefixFragment; - var a = array[ i + 0 ]; - var b = array[ i + 1 ]; - var c = array[ i + 2 ]; + if ( material.isRawShaderMaterial ) { - indices.push( a, b, b, c, c, a ); + prefixVertex = [ - } + customDefines - } else { + ].filter( filterEmptyLine ).join( '\n' ); - var array = geometryAttributes.position.array; + if ( prefixVertex.length > 0 ) { - for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { + prefixVertex += '\n'; - var a = i + 0; - var b = i + 1; - var c = i + 2; + } - indices.push( a, b, b, c, c, a ); + prefixFragment = [ - } + customExtensions, + customDefines - } + ].filter( filterEmptyLine ).join( '\n' ); - // console.timeEnd( 'wireframe' ); + if ( prefixFragment.length > 0 ) { - attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); + prefixFragment += '\n'; - attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER ); + } - wireframeAttributes[ geometry.id ] = attribute; + } else { - return attribute; + prefixVertex = [ - } + 'precision ' + parameters.precision + ' float;', + 'precision ' + parameters.precision + ' int;', - return { + '#define SHADER_NAME ' + shader.name, - get: get, - update: update, + customDefines, - getWireframeAttribute: getWireframeAttribute + parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', - }; + '#define GAMMA_FACTOR ' + gammaFactorDefine, - } + '#define MAX_BONES ' + parameters.maxBones, + ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', + ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '', - /** - * @author mrdoob / http://mrdoob.com/ - */ + parameters.map ? '#define USE_MAP' : '', + parameters.envMap ? '#define USE_ENVMAP' : '', + parameters.envMap ? '#define ' + envMapModeDefine : '', + parameters.lightMap ? '#define USE_LIGHTMAP' : '', + parameters.aoMap ? '#define USE_AOMAP' : '', + parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', + parameters.bumpMap ? '#define USE_BUMPMAP' : '', + parameters.normalMap ? '#define USE_NORMALMAP' : '', + parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', + parameters.specularMap ? '#define USE_SPECULARMAP' : '', + parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', + parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', + parameters.alphaMap ? '#define USE_ALPHAMAP' : '', + parameters.vertexColors ? '#define USE_COLOR' : '', - function WebGLLights() { - - var lights = {}; - - return { - - get: function ( light ) { - - if ( lights[ light.id ] !== undefined ) { - - return lights[ light.id ]; - - } - - var uniforms; - - switch ( light.type ) { - - case 'DirectionalLight': - uniforms = { - direction: new Vector3(), - color: new Color(), - - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2() - }; - break; - - case 'SpotLight': - uniforms = { - position: new Vector3(), - direction: new Vector3(), - color: new Color(), - distance: 0, - coneCos: 0, - penumbraCos: 0, - decay: 0, - - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2() - }; - break; - - case 'PointLight': - uniforms = { - position: new Vector3(), - color: new Color(), - distance: 0, - decay: 0, - - shadow: false, - shadowBias: 0, - shadowRadius: 1, - shadowMapSize: new Vector2() - }; - break; - - case 'HemisphereLight': - uniforms = { - direction: new Vector3(), - skyColor: new Color(), - groundColor: new Color() - }; - break; - - case 'RectAreaLight': - uniforms = { - color: new Color(), - position: new Vector3(), - halfWidth: new Vector3(), - halfHeight: new Vector3() - // TODO (abelnation): set RectAreaLight shadow uniforms - }; - break; - - } - - lights[ light.id ] = uniforms; - - return uniforms; - - } - - }; - - } - - /** - * @author mrdoob / http://mrdoob.com/ - */ - - function WebGLObjects( gl, geometries, infoRender ) { - - var updateList = {}; - - function update( object ) { - - var frame = infoRender.frame; - - var geometry = object.geometry; - var buffergeometry = geometries.get( object, geometry ); - - // Update once per frame - - if ( updateList[ buffergeometry.id ] !== frame ) { - - if ( geometry.isGeometry ) { - - buffergeometry.updateFromObject( object ); - - } - - geometries.update( buffergeometry ); - - updateList[ buffergeometry.id ] = frame; - - } - - return buffergeometry; - - } - - function clear() { - - updateList = {}; - - } - - return { - - update: update, - clear: clear - - }; - - } - - /** - * @author mrdoob / http://mrdoob.com/ - */ - - function addLineNumbers( string ) { - - var lines = string.split( '\n' ); - - for ( var i = 0; i < lines.length; i ++ ) { - - lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; - - } - - return lines.join( '\n' ); - - } - - function WebGLShader( gl, type, string ) { - - var shader = gl.createShader( type ); - - gl.shaderSource( shader, string ); - gl.compileShader( shader ); - - if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) { - - console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' ); - - } - - if ( gl.getShaderInfoLog( shader ) !== '' ) { - - console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) ); - - } - - // --enable-privileged-webgl-extension - // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); - - return shader; - - } - - /** - * @author mrdoob / http://mrdoob.com/ - */ - - var programIdCount = 0; - - function getEncodingComponents( encoding ) { - - switch ( encoding ) { - - case LinearEncoding: - return [ 'Linear','( value )' ]; - case sRGBEncoding: - return [ 'sRGB','( value )' ]; - case RGBEEncoding: - return [ 'RGBE','( value )' ]; - case RGBM7Encoding: - return [ 'RGBM','( value, 7.0 )' ]; - case RGBM16Encoding: - return [ 'RGBM','( value, 16.0 )' ]; - case RGBDEncoding: - return [ 'RGBD','( value, 256.0 )' ]; - case GammaEncoding: - return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ]; - default: - throw new Error( 'unsupported encoding: ' + encoding ); - - } - - } - - function getTexelDecodingFunction( functionName, encoding ) { - - var components = getEncodingComponents( encoding ); - return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }"; - - } - - function getTexelEncodingFunction( functionName, encoding ) { - - var components = getEncodingComponents( encoding ); - return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }"; - - } - - function getToneMappingFunction( functionName, toneMapping ) { - - var toneMappingName; - - switch ( toneMapping ) { - - case LinearToneMapping: - toneMappingName = "Linear"; - break; - - case ReinhardToneMapping: - toneMappingName = "Reinhard"; - break; - - case Uncharted2ToneMapping: - toneMappingName = "Uncharted2"; - break; - - case CineonToneMapping: - toneMappingName = "OptimizedCineon"; - break; - - default: - throw new Error( 'unsupported toneMapping: ' + toneMapping ); - - } - - return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; - - } - - function generateExtensions( extensions, parameters, rendererExtensions ) { - - extensions = extensions || {}; - - var chunks = [ - ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '', - ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '', - ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '', - ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '' - ]; - - return chunks.filter( filterEmptyLine ).join( '\n' ); - - } - - function generateDefines( defines ) { - - var chunks = []; - - for ( var name in defines ) { - - var value = defines[ name ]; - - if ( value === false ) continue; - - chunks.push( '#define ' + name + ' ' + value ); - - } - - return chunks.join( '\n' ); - - } - - function fetchAttributeLocations( gl, program, identifiers ) { - - var attributes = {}; - - var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES ); - - for ( var i = 0; i < n; i ++ ) { - - var info = gl.getActiveAttrib( program, i ); - var name = info.name; - - // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i ); - - attributes[ name ] = gl.getAttribLocation( program, name ); - - } - - return attributes; - - } - - function filterEmptyLine( string ) { - - return string !== ''; - - } - - function replaceLightNums( string, parameters ) { - - return string - .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) - .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) - .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) - .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) - .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ); - - } - - function parseIncludes( string ) { - - var pattern = /^[ \t]*#include +<([\w\d.]+)>/gm; - - function replace( match, include ) { - - var replace = ShaderChunk[ include ]; - - if ( replace === undefined ) { - - throw new Error( 'Can not resolve #include <' + include + '>' ); - - } - - return parseIncludes( replace ); - - } - - return string.replace( pattern, replace ); - - } - - function unrollLoops( string ) { - - var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; - - function replace( match, start, end, snippet ) { - - var unroll = ''; - - for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) { - - unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' ); - - } - - return unroll; - - } - - return string.replace( pattern, replace ); - - } - - function WebGLProgram( renderer, code, material, shader, parameters ) { - - var gl = renderer.context; - - var extensions = material.extensions; - var defines = material.defines; - - var vertexShader = shader.vertexShader; - var fragmentShader = shader.fragmentShader; - - var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; - - if ( parameters.shadowMapType === PCFShadowMap ) { - - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; - - } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { - - shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; - - } - - var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; - var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - - if ( parameters.envMap ) { - - switch ( material.envMap.mapping ) { - - case CubeReflectionMapping: - case CubeRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; - break; - - case CubeUVReflectionMapping: - case CubeUVRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; - break; - - case EquirectangularReflectionMapping: - case EquirectangularRefractionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; - break; - - case SphericalReflectionMapping: - envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; - break; - - } - - switch ( material.envMap.mapping ) { - - case CubeRefractionMapping: - case EquirectangularRefractionMapping: - envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; - break; - - } - - switch ( material.combine ) { - - case MultiplyOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; - break; - - case MixOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; - break; - - case AddOperation: - envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; - break; - - } - - } - - var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; - - // console.log( 'building new program ' ); - - // - - var customExtensions = generateExtensions( extensions, parameters, renderer.extensions ); - - var customDefines = generateDefines( defines ); - - // - - var program = gl.createProgram(); - - var prefixVertex, prefixFragment; - - if ( material.isRawShaderMaterial ) { - - prefixVertex = [ - - customDefines, - - '\n' - - ].filter( filterEmptyLine ).join( '\n' ); - - prefixFragment = [ - - customExtensions, - customDefines, - - '\n' - - ].filter( filterEmptyLine ).join( '\n' ); - - } else { - - prefixVertex = [ - - 'precision ' + parameters.precision + ' float;', - 'precision ' + parameters.precision + ' int;', - - '#define SHADER_NAME ' + shader.name, - - customDefines, - - parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', - - '#define GAMMA_FACTOR ' + gammaFactorDefine, - - '#define MAX_BONES ' + parameters.maxBones, - ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', - ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '', - - parameters.map ? '#define USE_MAP' : '', - parameters.envMap ? '#define USE_ENVMAP' : '', - parameters.envMap ? '#define ' + envMapModeDefine : '', - parameters.lightMap ? '#define USE_LIGHTMAP' : '', - parameters.aoMap ? '#define USE_AOMAP' : '', - parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', - parameters.bumpMap ? '#define USE_BUMPMAP' : '', - parameters.normalMap ? '#define USE_NORMALMAP' : '', - parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', - parameters.specularMap ? '#define USE_SPECULARMAP' : '', - parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', - parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', - parameters.alphaMap ? '#define USE_ALPHAMAP' : '', - parameters.vertexColors ? '#define USE_COLOR' : '', - - parameters.flatShading ? '#define FLAT_SHADED' : '', + parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', @@ -17354,15 +16462,13 @@ parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', - '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', @@ -17458,27 +16564,24 @@ parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', - '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes, - '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection), - parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', - parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '', + parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', - parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '', + parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', - parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', + parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '', - parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '', + parameters.envMap && extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', - ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '', - ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below - ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '', + ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '', + ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below + ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '', parameters.dithering ? '#define DITHERING' : '', @@ -17486,9 +16589,9 @@ parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '', parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '', parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '', - parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '', + parameters.outputEncoding ? getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ) : '', - parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '', + parameters.depthPacking ? '#define DEPTH_PACKING ' + material.depthPacking : '', '\n' @@ -17498,16 +16601,14 @@ vertexShader = parseIncludes( vertexShader ); vertexShader = replaceLightNums( vertexShader, parameters ); + vertexShader = replaceClippingPlaneNums( vertexShader, parameters ); fragmentShader = parseIncludes( fragmentShader ); fragmentShader = replaceLightNums( fragmentShader, parameters ); + fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters ); - if ( ! material.isShaderMaterial ) { - - vertexShader = unrollLoops( vertexShader ); - fragmentShader = unrollLoops( fragmentShader ); - - } + vertexShader = unrollLoops( vertexShader ); + fragmentShader = unrollLoops( fragmentShader ); var vertexGlsl = prefixVertex + vertexShader; var fragmentGlsl = prefixFragment + fragmentShader; @@ -17536,9 +16637,9 @@ gl.linkProgram( program ); - var programLog = gl.getProgramInfoLog( program ); - var vertexLog = gl.getShaderInfoLog( glVertexShader ); - var fragmentLog = gl.getShaderInfoLog( glFragmentShader ); + var programLog = gl.getProgramInfoLog( program ).trim(); + var vertexLog = gl.getShaderInfoLog( glVertexShader ).trim(); + var fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim(); var runnable = true; var haveDiagnostics = true; @@ -17598,12 +16699,11 @@ var cachedUniforms; - this.getUniforms = function() { + this.getUniforms = function () { if ( cachedUniforms === undefined ) { - cachedUniforms = - new WebGLUniforms( gl, program, renderer ); + cachedUniforms = new WebGLUniforms( gl, program, renderer ); } @@ -17615,7 +16715,7 @@ var cachedAttributes; - this.getAttributes = function() { + this.getAttributes = function () { if ( cachedAttributes === undefined ) { @@ -17629,7 +16729,7 @@ // free resource - this.destroy = function() { + this.destroy = function () { gl.deleteProgram( program ); this.program = undefined; @@ -17641,7 +16741,7 @@ Object.defineProperties( this, { uniforms: { - get: function() { + get: function () { console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' ); return this.getUniforms(); @@ -17650,7 +16750,7 @@ }, attributes: { - get: function() { + get: function () { console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' ); return this.getAttributes(); @@ -17678,12 +16778,13 @@ * @author mrdoob / http://mrdoob.com/ */ - function WebGLPrograms( renderer, capabilities ) { + function WebGLPrograms( renderer, extensions, capabilities ) { var programs = []; var shaderIDs = { MeshDepthMaterial: 'depth', + MeshDistanceMaterial: 'distanceRGBA', MeshNormalMaterial: 'normal', MeshBasicMaterial: 'basic', MeshLambertMaterial: 'lambert', @@ -17693,7 +16794,8 @@ MeshPhysicalMaterial: 'physical', LineBasicMaterial: 'basic', LineDashedMaterial: 'dashed', - PointsMaterial: 'points' + PointsMaterial: 'points', + ShadowMaterial: 'shadow' }; var parameterNames = [ @@ -17776,7 +16878,7 @@ } - this.getParameters = function ( material, lights, fog, nClipPlanes, nClipIntersection, object ) { + this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) { var shaderID = shaderIDs[ material.type ]; @@ -17784,7 +16886,7 @@ // (not to blow over maxLights budget) var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0; - var precision = renderer.getPrecision(); + var precision = capabilities.precision; if ( material.precision !== null ) { @@ -17835,7 +16937,7 @@ useFog: material.fog, fogExp: ( fog && fog.isFogExp2 ), - flatShading: material.shading === FlatShading, + flatShading: material.flatShading, sizeAttenuation: material.sizeAttenuation, logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer, @@ -17860,7 +16962,7 @@ dithering: material.dithering, - shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0, + shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && shadows.length > 0, shadowMapType: renderer.shadowMap.type, toneMapping: renderer.toneMapping, @@ -17942,7 +17044,7 @@ if ( program === undefined ) { - program = new WebGLProgram( renderer, code, material, shader, parameters ); + program = new WebGLProgram( renderer, extensions, code, material, shader, parameters ); programs.push( program ); } @@ -17973,947 +17075,1715 @@ } /** - * @author mrdoob / http://mrdoob.com/ + * @author fordacious / fordacious.github.io */ - function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, infoMemory ) { + function WebGLProperties() { - var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext ); + var properties = new WeakMap(); - // + function get( object ) { - function clampToMaxSize( image, maxSize ) { + var map = properties.get( object ); - if ( image.width > maxSize || image.height > maxSize ) { - - // Warning: Scaling through the canvas will only work with images that use - // premultiplied alpha. - - var scale = maxSize / Math.max( image.width, image.height ); - - var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = Math.floor( image.width * scale ); - canvas.height = Math.floor( image.height * scale ); - - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height ); - - console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); + if ( map === undefined ) { - return canvas; + map = {}; + properties.set( object, map ); } - return image; + return map; } - function isPowerOfTwo( image ) { + function remove( object ) { - return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height ); + properties.delete( object ); } - function makePowerOfTwo( image ) { - - if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) { + function update( object, key, value ) { - var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - canvas.width = _Math.nearestPowerOfTwo( image.width ); - canvas.height = _Math.nearestPowerOfTwo( image.height ); + properties.get( object )[ key ] = value; - var context = canvas.getContext( '2d' ); - context.drawImage( image, 0, 0, canvas.width, canvas.height ); + } - console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); + function dispose() { - return canvas; + properties = new WeakMap(); - } + } - return image; + return { + get: get, + remove: remove, + update: update, + dispose: dispose + }; - } + } - function textureNeedsPowerOfTwo( texture ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || - ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); + function painterSortStable( a, b ) { - } + if ( a.renderOrder !== b.renderOrder ) { - function textureNeedsGenerateMipmaps( texture, isPowerOfTwo ) { + return a.renderOrder - b.renderOrder; - return texture.generateMipmaps && isPowerOfTwo && - texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; + } else if ( a.program && b.program && a.program !== b.program ) { - } + return a.program.id - b.program.id; - // Fallback filters for non-power-of-2 textures + } else if ( a.material.id !== b.material.id ) { - function filterFallback( f ) { + return a.material.id - b.material.id; - if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) { + } else if ( a.z !== b.z ) { - return _gl.NEAREST; + return a.z - b.z; - } + } else { - return _gl.LINEAR; + return a.id - b.id; } - // + } - function onTextureDispose( event ) { + function reversePainterSortStable( a, b ) { - var texture = event.target; + if ( a.renderOrder !== b.renderOrder ) { - texture.removeEventListener( 'dispose', onTextureDispose ); + return a.renderOrder - b.renderOrder; - deallocateTexture( texture ); + } if ( a.z !== b.z ) { + + return b.z - a.z; - infoMemory.textures --; + } else { + return a.id - b.id; } - function onRenderTargetDispose( event ) { - - var renderTarget = event.target; + } - renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); + function WebGLRenderList() { - deallocateRenderTarget( renderTarget ); + var renderItems = []; + var renderItemsIndex = 0; - infoMemory.textures --; + var opaque = []; + var transparent = []; - } + function init() { - // + renderItemsIndex = 0; - function deallocateTexture( texture ) { + opaque.length = 0; + transparent.length = 0; - var textureProperties = properties.get( texture ); + } - if ( texture.image && textureProperties.__image__webglTextureCube ) { + function push( object, geometry, material, z, group ) { - // cube texture + var renderItem = renderItems[ renderItemsIndex ]; - _gl.deleteTexture( textureProperties.__image__webglTextureCube ); + if ( renderItem === undefined ) { - } else { + renderItem = { + id: object.id, + object: object, + geometry: geometry, + material: material, + program: material.program, + renderOrder: object.renderOrder, + z: z, + group: group + }; - // 2D texture + renderItems[ renderItemsIndex ] = renderItem; - if ( textureProperties.__webglInit === undefined ) return; + } else { - _gl.deleteTexture( textureProperties.__webglTexture ); + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.program = material.program; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; } - // remove all webgl properties - properties.remove( texture ); + ( material.transparent === true ? transparent : opaque ).push( renderItem ); - } + renderItemsIndex ++; - function deallocateRenderTarget( renderTarget ) { + } - var renderTargetProperties = properties.get( renderTarget ); - var textureProperties = properties.get( renderTarget.texture ); + function sort() { - if ( ! renderTarget ) return; + if ( opaque.length > 1 ) opaque.sort( painterSortStable ); + if ( transparent.length > 1 ) transparent.sort( reversePainterSortStable ); - if ( textureProperties.__webglTexture !== undefined ) { + } - _gl.deleteTexture( textureProperties.__webglTexture ); + return { + opaque: opaque, + transparent: transparent, - } + init: init, + push: push, - if ( renderTarget.depthTexture ) { + sort: sort + }; - renderTarget.depthTexture.dispose(); + } - } + function WebGLRenderLists() { - if ( renderTarget.isWebGLRenderTargetCube ) { + var lists = {}; - for ( var i = 0; i < 6; i ++ ) { + function get( scene, camera ) { - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); - if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); + var hash = scene.id + ',' + camera.id; + var list = lists[ hash ]; - } + if ( list === undefined ) { - } else { + // console.log( 'THREE.WebGLRenderLists:', hash ); - _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); - if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); + list = new WebGLRenderList(); + lists[ hash ] = list; } - properties.remove( renderTarget.texture ); - properties.remove( renderTarget ); + return list; } - // - + function dispose() { + lists = {}; - function setTexture2D( texture, slot ) { + } - var textureProperties = properties.get( texture ); + return { + get: get, + dispose: dispose + }; - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + } - var image = texture.image; + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( image === undefined ) { + function UniformsCache() { - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture ); + var lights = {}; - } else if ( image.complete === false ) { + return { - console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture ); + get: function ( light ) { - } else { + if ( lights[ light.id ] !== undefined ) { - uploadTexture( textureProperties, texture, slot ); - return; + return lights[ light.id ]; } - } - - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - - } - - function setTextureCube( texture, slot ) { - - var textureProperties = properties.get( texture ); - - if ( texture.image.length === 6 ) { + var uniforms; - if ( texture.version > 0 && textureProperties.__version !== texture.version ) { + switch ( light.type ) { - if ( ! textureProperties.__image__webglTextureCube ) { + case 'DirectionalLight': + uniforms = { + direction: new Vector3(), + color: new Color(), - texture.addEventListener( 'dispose', onTextureDispose ); + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - textureProperties.__image__webglTextureCube = _gl.createTexture(); + case 'SpotLight': + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0, - infoMemory.textures ++; + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; - } + case 'PointLight': + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0, - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); + shadow: false, + shadowBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2(), + shadowCameraNear: 1, + shadowCameraFar: 1000 + }; + break; - _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + case 'HemisphereLight': + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; - var isCompressed = ( texture && texture.isCompressedTexture ); - var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); + case 'RectAreaLight': + uniforms = { + color: new Color(), + position: new Vector3(), + halfWidth: new Vector3(), + halfHeight: new Vector3() + // TODO (abelnation): set RectAreaLight shadow uniforms + }; + break; - var cubeImage = []; + } - for ( var i = 0; i < 6; i ++ ) { + lights[ light.id ] = uniforms; - if ( ! isCompressed && ! isDataTexture ) { + return uniforms; - cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize ); + } - } else { + }; - cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; + } - } + var count = 0; - } + function WebGLLights() { - var image = cubeImage[ 0 ], - isPowerOfTwoImage = isPowerOfTwo( image ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); + var cache = new UniformsCache(); - setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage ); + var state = { - for ( var i = 0; i < 6; i ++ ) { + id: count ++, - if ( ! isCompressed ) { + hash: '', - if ( isDataTexture ) { + ambient: [ 0, 0, 0 ], + directional: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotShadowMap: [], + spotShadowMatrix: [], + rectArea: [], + point: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [] - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); + }; - } else { + var vector3 = new Vector3(); + var matrix4 = new Matrix4(); + var matrix42 = new Matrix4(); - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); + function setup( lights, shadows, camera ) { - } + var r = 0, g = 0, b = 0; - } else { + var directionalLength = 0; + var pointLength = 0; + var spotLength = 0; + var rectAreaLength = 0; + var hemiLength = 0; - var mipmap, mipmaps = cubeImage[ i ].mipmaps; + var viewMatrix = camera.matrixWorldInverse; - for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { + for ( var i = 0, l = lights.length; i < l; i ++ ) { - mipmap = mipmaps[ j ]; + var light = lights[ i ]; - if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { + var color = light.color; + var intensity = light.intensity; + var distance = light.distance; - if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { + var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; - state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + if ( light.isAmbientLight ) { - } else { + r += color.r * intensity; + g += color.g * intensity; + b += color.b * intensity; - console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" ); + } else if ( light.isDirectionalLight ) { - } + var uniforms = cache.get( light ); - } else { + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); - state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + uniforms.shadow = light.castShadow; - } + if ( light.castShadow ) { - } + var shadow = light.shadow; - } + uniforms.shadowBias = shadow.bias; + uniforms.shadowRadius = shadow.radius; + uniforms.shadowMapSize = shadow.mapSize; } - if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) { + state.directionalShadowMap[ directionalLength ] = shadowMap; + state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; + state.directional[ directionalLength ] = uniforms; - _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); + directionalLength ++; - } + } else if ( light.isSpotLight ) { - textureProperties.__version = texture.version; + var uniforms = cache.get( light ); - if ( texture.onUpdate ) texture.onUpdate( texture ); + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); - } else { + uniforms.color.copy( color ).multiplyScalar( intensity ); + uniforms.distance = distance; - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + vector3.setFromMatrixPosition( light.target.matrixWorld ); + uniforms.direction.sub( vector3 ); + uniforms.direction.transformDirection( viewMatrix ); - } + uniforms.coneCos = Math.cos( light.angle ); + uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); + uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; - } + uniforms.shadow = light.castShadow; - } + if ( light.castShadow ) { - function setTextureCubeDynamic( texture, slot ) { + var shadow = light.shadow; - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture ); + uniforms.shadowBias = shadow.bias; + uniforms.shadowRadius = shadow.radius; + uniforms.shadowMapSize = shadow.mapSize; - } + } - function setTextureParameters( textureType, texture, isPowerOfTwoImage ) { + state.spotShadowMap[ spotLength ] = shadowMap; + state.spotShadowMatrix[ spotLength ] = light.shadow.matrix; + state.spot[ spotLength ] = uniforms; - var extension; + spotLength ++; - if ( isPowerOfTwoImage ) { + } else if ( light.isRectAreaLight ) { - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); + var uniforms = cache.get( light ); - _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); + // (a) intensity is the total visible light emitted + //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) ); - } else { + // (b) intensity is the brightness of the light + uniforms.color.copy( color ).multiplyScalar( intensity ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); - _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); - if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { + // extract local rotation of light to derive width/height half vectors + matrix42.identity(); + matrix4.copy( light.matrixWorld ); + matrix4.premultiply( viewMatrix ); + matrix42.extractRotation( matrix4 ); - console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture ); + uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); + uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); - } + uniforms.halfWidth.applyMatrix4( matrix42 ); + uniforms.halfHeight.applyMatrix4( matrix42 ); - _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); - _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); + // TODO (abelnation): RectAreaLight distance? + // uniforms.distance = distance; - if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { + state.rectArea[ rectAreaLength ] = uniforms; - console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture ); + rectAreaLength ++; - } + } else if ( light.isPointLight ) { - } + var uniforms = cache.get( light ); - extension = extensions.get( 'EXT_texture_filter_anisotropic' ); + uniforms.position.setFromMatrixPosition( light.matrixWorld ); + uniforms.position.applyMatrix4( viewMatrix ); - if ( extension ) { + uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); + uniforms.distance = light.distance; + uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; - if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return; - if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return; + uniforms.shadow = light.castShadow; - if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { + if ( light.castShadow ) { - _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); - properties.get( texture ).__currentAnisotropy = texture.anisotropy; + var shadow = light.shadow; - } + uniforms.shadowBias = shadow.bias; + uniforms.shadowRadius = shadow.radius; + uniforms.shadowMapSize = shadow.mapSize; + uniforms.shadowCameraNear = shadow.camera.near; + uniforms.shadowCameraFar = shadow.camera.far; - } + } - } + state.pointShadowMap[ pointLength ] = shadowMap; + state.pointShadowMatrix[ pointLength ] = light.shadow.matrix; + state.point[ pointLength ] = uniforms; - function uploadTexture( textureProperties, texture, slot ) { + pointLength ++; - if ( textureProperties.__webglInit === undefined ) { + } else if ( light.isHemisphereLight ) { - textureProperties.__webglInit = true; + var uniforms = cache.get( light ); - texture.addEventListener( 'dispose', onTextureDispose ); + uniforms.direction.setFromMatrixPosition( light.matrixWorld ); + uniforms.direction.transformDirection( viewMatrix ); + uniforms.direction.normalize(); - textureProperties.__webglTexture = _gl.createTexture(); + uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); + uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); - infoMemory.textures ++; + state.hemi[ hemiLength ] = uniforms; - } + hemiLength ++; - state.activeTexture( _gl.TEXTURE0 + slot ); - state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); + } - _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); - _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); + } - var image = clampToMaxSize( texture.image, capabilities.maxTextureSize ); + state.ambient[ 0 ] = r; + state.ambient[ 1 ] = g; + state.ambient[ 2 ] = b; - if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) { + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; - image = makePowerOfTwo( image ); + state.hash = state.id + ',' + directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + shadows.length; - } + } - var isPowerOfTwoImage = isPowerOfTwo( image ), - glFormat = paramThreeToGL( texture.format ), - glType = paramThreeToGL( texture.type ); + return { + setup: setup, + state: state + }; - setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage ); + } - var mipmap, mipmaps = texture.mipmaps; + /** + * @author Mugen87 / https://github.com/Mugen87 + */ - if ( texture.isDepthTexture ) { + function WebGLRenderState() { - // populate depth texture with dummy data + var lights = new WebGLLights(); - var internalFormat = _gl.DEPTH_COMPONENT; + var lightsArray = []; + var shadowsArray = []; + var spritesArray = []; - if ( texture.type === FloatType ) { + function init() { - if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0'); - internalFormat = _gl.DEPTH_COMPONENT32F; + lightsArray.length = 0; + shadowsArray.length = 0; + spritesArray.length = 0; - } else if ( _isWebGL2 ) { + } - // WebGL 2.0 requires signed internalformat for glTexImage2D - internalFormat = _gl.DEPTH_COMPONENT16; + function pushLight( light ) { - } + lightsArray.push( light ); - if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) { + } - // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are - // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { + function pushShadow( shadowLight ) { - console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); + shadowsArray.push( shadowLight ); - texture.type = UnsignedShortType; - glType = paramThreeToGL( texture.type ); + } - } + function pushSprite( shadowLight ) { - } + spritesArray.push( shadowLight ); - // Depth stencil textures need the DEPTH_STENCIL internal format - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - if ( texture.format === DepthStencilFormat ) { + } - internalFormat = _gl.DEPTH_STENCIL; + function setupLights( camera ) { - // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are - // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. - // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) - if ( texture.type !== UnsignedInt248Type ) { + lights.setup( lightsArray, shadowsArray, camera ); - console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); + } - texture.type = UnsignedInt248Type; - glType = paramThreeToGL( texture.type ); + var state = { + lightsArray: lightsArray, + shadowsArray: shadowsArray, + spritesArray: spritesArray, - } + lights: lights + }; - } + return { + init: init, + state: state, + setupLights: setupLights, - state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null ); + pushLight: pushLight, + pushShadow: pushShadow, + pushSprite: pushSprite + }; - } else if ( texture.isDataTexture ) { + } - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels + function WebGLRenderStates() { - if ( mipmaps.length > 0 && isPowerOfTwoImage ) { + var renderStates = {}; - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + function get( scene, camera ) { - mipmap = mipmaps[ i ]; - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + var hash = scene.id + ',' + camera.id; - } + var renderState = renderStates[ hash ]; - texture.generateMipmaps = false; + if ( renderState === undefined ) { - } else { + renderState = new WebGLRenderState(); + renderStates[ hash ] = renderState; - state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); + } - } + return renderState; - } else if ( texture.isCompressedTexture ) { + } - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + function dispose() { - mipmap = mipmaps[ i ]; + renderStates = {}; - if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { + } - if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { + return { + get: get, + dispose: dispose + }; - state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); + } - } else { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author bhouston / https://clara.io + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * + * opacity: , + * + * map: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * wireframe: , + * wireframeLinewidth: + * } + */ - console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" ); + function MeshDepthMaterial( parameters ) { - } + Material.call( this ); - } else { + this.type = 'MeshDepthMaterial'; - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); + this.depthPacking = BasicDepthPacking; - } + this.skinning = false; + this.morphTargets = false; - } + this.map = null; - } else { + this.alphaMap = null; - // regular Texture (image, video, canvas) + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - // use manually created mipmaps if available - // if there are no manual mipmaps - // set 0 level mipmap and then use GL to generate other mipmap levels + this.wireframe = false; + this.wireframeLinewidth = 1; - if ( mipmaps.length > 0 && isPowerOfTwoImage ) { + this.fog = false; + this.lights = false; - for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { + this.setValues( parameters ); - mipmap = mipmaps[ i ]; - state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); + } - } + MeshDepthMaterial.prototype = Object.create( Material.prototype ); + MeshDepthMaterial.prototype.constructor = MeshDepthMaterial; - texture.generateMipmaps = false; + MeshDepthMaterial.prototype.isMeshDepthMaterial = true; - } else { + MeshDepthMaterial.prototype.copy = function ( source ) { - state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image ); + Material.prototype.copy.call( this, source ); - } + this.depthPacking = source.depthPacking; - } + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) _gl.generateMipmap( _gl.TEXTURE_2D ); + this.map = source.map; - textureProperties.__version = texture.version; + this.alphaMap = source.alphaMap; - if ( texture.onUpdate ) texture.onUpdate( texture ); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - } + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; - // Render targets + return this; - // Setup storage for target texture and bind it to correct framebuffer - function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) { + }; - var glFormat = paramThreeToGL( renderTarget.texture.format ); - var glType = paramThreeToGL( renderTarget.texture.type ); - state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); + /** + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * + * referencePosition: , + * nearDistance: , + * farDistance: , + * + * skinning: , + * morphTargets: , + * + * map: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: + * + * } + */ - } + function MeshDistanceMaterial( parameters ) { - // Setup storage for internal depth/stencil buffers and bind to correct framebuffer - function setupRenderBufferStorage( renderbuffer, renderTarget ) { + Material.call( this ); - _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); + this.type = 'MeshDistanceMaterial'; - if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { + this.referencePosition = new Vector3(); + this.nearDistance = 1; + this.farDistance = 1000; - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + this.skinning = false; + this.morphTargets = false; - } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { + this.map = null; - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); - _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); + this.alphaMap = null; - } else { + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; - // FIXME: We don't support !depth !stencil - _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); + this.fog = false; + this.lights = false; - } + this.setValues( parameters ); - _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); + } - } + MeshDistanceMaterial.prototype = Object.create( Material.prototype ); + MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial; - // Setup resources for a Depth Texture for a FBO (needs an extension) - function setupDepthTexture( framebuffer, renderTarget ) { + MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true; - var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube ); - if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!'); + MeshDistanceMaterial.prototype.copy = function ( source ) { - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + Material.prototype.copy.call( this, source ); - if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { + this.referencePosition.copy( source.referencePosition ); + this.nearDistance = source.nearDistance; + this.farDistance = source.farDistance; - throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture'); + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; - } + this.map = source.map; - // upload an empty depth texture with framebuffer size - if ( !properties.get( renderTarget.depthTexture ).__webglTexture || - renderTarget.depthTexture.image.width !== renderTarget.width || - renderTarget.depthTexture.image.height !== renderTarget.height ) { - renderTarget.depthTexture.image.width = renderTarget.width; - renderTarget.depthTexture.image.height = renderTarget.height; - renderTarget.depthTexture.needsUpdate = true; - } + this.alphaMap = source.alphaMap; - setTexture2D( renderTarget.depthTexture, 0 ); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; - var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; + return this; - if ( renderTarget.depthTexture.format === DepthFormat ) { + }; - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + /** + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { + function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); + var _frustum = new Frustum(), + _projScreenMatrix = new Matrix4(), - } else { + _shadowMapSize = new Vector2(), + _maxShadowMapSize = new Vector2( maxTextureSize, maxTextureSize ), - throw new Error('Unknown depthTexture format') + _lookTarget = new Vector3(), + _lightPositionWorld = new Vector3(), - } + _MorphingFlag = 1, + _SkinningFlag = 2, - } + _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1, - // Setup GL resources for a non-texture depth buffer - function setupDepthRenderbuffer( renderTarget ) { + _depthMaterials = new Array( _NumberOfMaterialVariants ), + _distanceMaterials = new Array( _NumberOfMaterialVariants ), - var renderTargetProperties = properties.get( renderTarget ); + _materialCache = {}; - var isCube = ( renderTarget.isWebGLRenderTargetCube === true ); + var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide }; - if ( renderTarget.depthTexture ) { + var cubeDirections = [ + new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ), + new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 ) + ]; - if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets'); + var cubeUps = [ + new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), + new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 ) + ]; - setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); + var cube2DViewPorts = [ + new Vector4(), new Vector4(), new Vector4(), + new Vector4(), new Vector4(), new Vector4() + ]; - } else { + // init - if ( isCube ) { + for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) { - renderTargetProperties.__webglDepthbuffer = []; + var useMorphing = ( i & _MorphingFlag ) !== 0; + var useSkinning = ( i & _SkinningFlag ) !== 0; - for ( var i = 0; i < 6; i ++ ) { + var depthMaterial = new MeshDepthMaterial( { - _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); - renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget ); + depthPacking: RGBADepthPacking, - } + morphTargets: useMorphing, + skinning: useSkinning - } else { + } ); - _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); - renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); - setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget ); + _depthMaterials[ i ] = depthMaterial; - } + // - } + var distanceMaterial = new MeshDistanceMaterial( { - _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); + morphTargets: useMorphing, + skinning: useSkinning + + } ); + + _distanceMaterials[ i ] = distanceMaterial; } - // Set up GL resources for the render target - function setupRenderTarget( renderTarget ) { + // - var renderTargetProperties = properties.get( renderTarget ); - var textureProperties = properties.get( renderTarget.texture ); + var scope = this; - renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); + this.enabled = false; - textureProperties.__webglTexture = _gl.createTexture(); + this.autoUpdate = true; + this.needsUpdate = false; - infoMemory.textures ++; + this.type = PCFShadowMap; - var isCube = ( renderTarget.isWebGLRenderTargetCube === true ); - var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); + this.render = function ( lights, scene, camera ) { - // Setup framebuffer + if ( scope.enabled === false ) return; + if ( scope.autoUpdate === false && scope.needsUpdate === false ) return; - if ( isCube ) { + if ( lights.length === 0 ) return; - renderTargetProperties.__webglFramebuffer = []; + // TODO Clean up (needed in case of contextlost) + var _gl = _renderer.context; + var _state = _renderer.state; - for ( var i = 0; i < 6; i ++ ) { + // Set GL state for depth map. + _state.disable( _gl.BLEND ); + _state.buffers.color.setClear( 1, 1, 1, 1 ); + _state.buffers.depth.setTest( true ); + _state.setScissorTest( false ); - renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); + // render depth map - } + var faceCount; - } else { + for ( var i = 0, il = lights.length; i < il; i ++ ) { - renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + var light = lights[ i ]; + var shadow = light.shadow; + var isPointLight = light && light.isPointLight; - } + if ( shadow === undefined ) { - // Setup color buffer + console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); + continue; - if ( isCube ) { + } - state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); - setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo ); + var shadowCamera = shadow.camera; - for ( var i = 0; i < 6; i ++ ) { + _shadowMapSize.copy( shadow.mapSize ); + _shadowMapSize.min( _maxShadowMapSize ); - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); + if ( isPointLight ) { - } + var vpWidth = _shadowMapSize.x; + var vpHeight = _shadowMapSize.y; - if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); - state.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); + // These viewports map a cube-map onto a 2D texture with the + // following orientation: + // + // xzXZ + // y Y + // + // X - Positive x direction + // x - Negative x direction + // Y - Positive y direction + // y - Negative y direction + // Z - Positive z direction + // z - Negative z direction - } else { + // positive X + cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight ); + // negative X + cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight ); + // positive Z + cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight ); + // negative Z + cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight ); + // positive Y + cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight ); + // negative Y + cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight ); - state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo ); - setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D ); + _shadowMapSize.x *= 4.0; + _shadowMapSize.y *= 2.0; - if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_2D ); - state.bindTexture( _gl.TEXTURE_2D, null ); + } - } + if ( shadow.map === null ) { - // Setup depth and stencil buffers + var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; - if ( renderTarget.depthBuffer ) { + shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); + shadow.map.texture.name = light.name + ".shadowMap"; - setupDepthRenderbuffer( renderTarget ); + shadowCamera.updateProjectionMatrix(); - } + } - } + if ( shadow.isSpotLightShadow ) { - function updateRenderTargetMipmap( renderTarget ) { + shadow.update( light ); - var texture = renderTarget.texture; - var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); + } - if ( textureNeedsGenerateMipmaps( texture, isTargetPowerOfTwo ) ) { + var shadowMap = shadow.map; + var shadowMatrix = shadow.matrix; - var target = renderTarget.isWebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; - var webglTexture = properties.get( texture ).__webglTexture; + _lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); + shadowCamera.position.copy( _lightPositionWorld ); - state.bindTexture( target, webglTexture ); - _gl.generateMipmap( target ); - state.bindTexture( target, null ); + if ( isPointLight ) { - } + faceCount = 6; - } + // for point lights we set the shadow matrix to be a translation-only matrix + // equal to inverse of the light's position - this.setTexture2D = setTexture2D; - this.setTextureCube = setTextureCube; - this.setTextureCubeDynamic = setTextureCubeDynamic; - this.setupRenderTarget = setupRenderTarget; - this.updateRenderTargetMipmap = updateRenderTargetMipmap; + shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z ); - } + } else { - /** - * @author fordacious / fordacious.github.io - */ + faceCount = 1; - function WebGLProperties() { + _lookTarget.setFromMatrixPosition( light.target.matrixWorld ); + shadowCamera.lookAt( _lookTarget ); + shadowCamera.updateMatrixWorld(); - var properties = {}; + // compute shadow matrix - function get( object ) { + shadowMatrix.set( + 0.5, 0.0, 0.0, 0.5, + 0.0, 0.5, 0.0, 0.5, + 0.0, 0.0, 0.5, 0.5, + 0.0, 0.0, 0.0, 1.0 + ); - var uuid = object.uuid; - var map = properties[ uuid ]; + shadowMatrix.multiply( shadowCamera.projectionMatrix ); + shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); - if ( map === undefined ) { + } - map = {}; - properties[ uuid ] = map; + _renderer.setRenderTarget( shadowMap ); + _renderer.clear(); - } + // render shadow map for each cube face (if omni-directional) or + // run a single pass if not - return map; + for ( var face = 0; face < faceCount; face ++ ) { - } + if ( isPointLight ) { - function remove( object ) { + _lookTarget.copy( shadowCamera.position ); + _lookTarget.add( cubeDirections[ face ] ); + shadowCamera.up.copy( cubeUps[ face ] ); + shadowCamera.lookAt( _lookTarget ); + shadowCamera.updateMatrixWorld(); - delete properties[ object.uuid ]; + var vpDimensions = cube2DViewPorts[ face ]; + _state.viewport( vpDimensions ); - } + } - function clear() { + // update camera matrices and frustum - properties = {}; + _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - } + // set object matrices & frustum culling - return { - get: get, - remove: remove, - clear: clear - }; + renderObject( scene, camera, shadowCamera, isPointLight ); - } + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function WebGLState( gl, extensions, paramThreeToGL ) { + scope.needsUpdate = false; - function ColorBuffer() { + }; - var locked = false; + function getDepthMaterial( object, material, isPointLight, lightPositionWorld, shadowCameraNear, shadowCameraFar ) { - var color = new Vector4(); - var currentColorMask = null; - var currentColorClear = new Vector4(); + var geometry = object.geometry; - return { + var result = null; - setMask: function ( colorMask ) { + var materialVariants = _depthMaterials; + var customMaterial = object.customDepthMaterial; - if ( currentColorMask !== colorMask && ! locked ) { + if ( isPointLight ) { - gl.colorMask( colorMask, colorMask, colorMask, colorMask ); - currentColorMask = colorMask; + materialVariants = _distanceMaterials; + customMaterial = object.customDistanceMaterial; - } + } - }, + if ( ! customMaterial ) { - setLocked: function ( lock ) { + var useMorphing = false; - locked = lock; + if ( material.morphTargets ) { - }, + if ( geometry && geometry.isBufferGeometry ) { - setClear: function ( r, g, b, a, premultipliedAlpha ) { + useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; - if ( premultipliedAlpha === true ) { + } else if ( geometry && geometry.isGeometry ) { - r *= a; g *= a; b *= a; + useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; } - color.set( r, g, b, a ); + } - if ( currentColorClear.equals( color ) === false ) { + if ( object.isSkinnedMesh && material.skinning === false ) { - gl.clearColor( r, g, b, a ); - currentColorClear.copy( color ); + console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object ); - } + } - }, + var useSkinning = object.isSkinnedMesh && material.skinning; - reset: function () { + var variantIndex = 0; - locked = false; + if ( useMorphing ) variantIndex |= _MorphingFlag; + if ( useSkinning ) variantIndex |= _SkinningFlag; - currentColorMask = null; - currentColorClear.set( 0, 0, 0, 1 ); + result = materialVariants[ variantIndex ]; - } + } else { - }; + result = customMaterial; - } + } - function DepthBuffer() { + if ( _renderer.localClippingEnabled && + material.clipShadows === true && + material.clippingPlanes.length !== 0 ) { - var locked = false; + // in this case we need a unique material instance reflecting the + // appropriate state - var currentDepthMask = null; - var currentDepthFunc = null; - var currentDepthClear = null; + var keyA = result.uuid, keyB = material.uuid; - return { + var materialsForVariant = _materialCache[ keyA ]; - setTest: function ( depthTest ) { + if ( materialsForVariant === undefined ) { - if ( depthTest ) { + materialsForVariant = {}; + _materialCache[ keyA ] = materialsForVariant; - enable( gl.DEPTH_TEST ); + } - } else { + var cachedMaterial = materialsForVariant[ keyB ]; - disable( gl.DEPTH_TEST ); + if ( cachedMaterial === undefined ) { - } + cachedMaterial = result.clone(); + materialsForVariant[ keyB ] = cachedMaterial; - }, + } - setMask: function ( depthMask ) { + result = cachedMaterial; - if ( currentDepthMask !== depthMask && ! locked ) { + } - gl.depthMask( depthMask ); - currentDepthMask = depthMask; + result.visible = material.visible; + result.wireframe = material.wireframe; - } + result.side = ( material.shadowSide != null ) ? material.shadowSide : shadowSide[ material.side ]; - }, + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; - setFunc: function ( depthFunc ) { + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; - if ( currentDepthFunc !== depthFunc ) { + if ( isPointLight && result.isMeshDistanceMaterial ) { - if ( depthFunc ) { + result.referencePosition.copy( lightPositionWorld ); + result.nearDistance = shadowCameraNear; + result.farDistance = shadowCameraFar; - switch ( depthFunc ) { + } + + return result; + + } + + function renderObject( object, camera, shadowCamera, isPointLight ) { + + if ( object.visible === false ) return; + + var visible = object.layers.test( camera.layers ); + + if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) { + + if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) { + + object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); + + var geometry = _objects.update( object ); + var material = object.material; + + if ( Array.isArray( material ) ) { + + var groups = geometry.groups; + + for ( var k = 0, kl = groups.length; k < kl; k ++ ) { + + var group = groups[ k ]; + var groupMaterial = material[ group.materialIndex ]; + + if ( groupMaterial && groupMaterial.visible ) { + + var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far ); + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); + + } + + } + + } else if ( material.visible ) { + + var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far ); + _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); + + } + + } + + } + + var children = object.children; + + for ( var i = 0, l = children.length; i < l; i ++ ) { + + renderObject( children[ i ], camera, shadowCamera, isPointLight ); + + } + + } + + } + + /** + * @author mrdoob / http://mrdoob.com/ + */ + + function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + + Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + + this.needsUpdate = true; + + } + + CanvasTexture.prototype = Object.create( Texture.prototype ); + CanvasTexture.prototype.constructor = CanvasTexture; + + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + */ + + function WebGLSpriteRenderer( renderer, gl, state, textures, capabilities ) { + + var vertexBuffer, elementBuffer; + var program, attributes, uniforms; + + var texture; + + // decompose matrixWorld + + var spritePosition = new Vector3(); + var spriteRotation = new Quaternion(); + var spriteScale = new Vector3(); + + function init() { + + var vertices = new Float32Array( [ + - 0.5, - 0.5, 0, 0, + 0.5, - 0.5, 1, 0, + 0.5, 0.5, 1, 1, + - 0.5, 0.5, 0, 1 + ] ); + + var faces = new Uint16Array( [ + 0, 1, 2, + 0, 2, 3 + ] ); + + vertexBuffer = gl.createBuffer(); + elementBuffer = gl.createBuffer(); + + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW ); + + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW ); + + program = createProgram(); + + attributes = { + position: gl.getAttribLocation( program, 'position' ), + uv: gl.getAttribLocation( program, 'uv' ) + }; + + uniforms = { + uvOffset: gl.getUniformLocation( program, 'uvOffset' ), + uvScale: gl.getUniformLocation( program, 'uvScale' ), + + rotation: gl.getUniformLocation( program, 'rotation' ), + center: gl.getUniformLocation( program, 'center' ), + scale: gl.getUniformLocation( program, 'scale' ), + + color: gl.getUniformLocation( program, 'color' ), + map: gl.getUniformLocation( program, 'map' ), + opacity: gl.getUniformLocation( program, 'opacity' ), + + modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ), + projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ), + + fogType: gl.getUniformLocation( program, 'fogType' ), + fogDensity: gl.getUniformLocation( program, 'fogDensity' ), + fogNear: gl.getUniformLocation( program, 'fogNear' ), + fogFar: gl.getUniformLocation( program, 'fogFar' ), + fogColor: gl.getUniformLocation( program, 'fogColor' ), + fogDepth: gl.getUniformLocation( program, 'fogDepth' ), + + alphaTest: gl.getUniformLocation( program, 'alphaTest' ) + }; + + var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = 8; + canvas.height = 8; + + var context = canvas.getContext( '2d' ); + context.fillStyle = 'white'; + context.fillRect( 0, 0, 8, 8 ); + + texture = new CanvasTexture( canvas ); + + } + + this.render = function ( sprites, scene, camera ) { + + if ( sprites.length === 0 ) return; + + // setup gl + + if ( program === undefined ) { + + init(); + + } + + state.useProgram( program ); + + state.initAttributes(); + state.enableAttribute( attributes.position ); + state.enableAttribute( attributes.uv ); + state.disableUnusedAttributes(); + + state.disable( gl.CULL_FACE ); + state.enable( gl.BLEND ); + + gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer ); + gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 ); + gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 ); + + gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer ); + + gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); + + state.activeTexture( gl.TEXTURE0 ); + gl.uniform1i( uniforms.map, 0 ); + + var oldFogType = 0; + var sceneFogType = 0; + var fog = scene.fog; + + if ( fog ) { + + gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b ); + + if ( fog.isFog ) { + + gl.uniform1f( uniforms.fogNear, fog.near ); + gl.uniform1f( uniforms.fogFar, fog.far ); + + gl.uniform1i( uniforms.fogType, 1 ); + oldFogType = 1; + sceneFogType = 1; + + } else if ( fog.isFogExp2 ) { + + gl.uniform1f( uniforms.fogDensity, fog.density ); + + gl.uniform1i( uniforms.fogType, 2 ); + oldFogType = 2; + sceneFogType = 2; + + } + + } else { + + gl.uniform1i( uniforms.fogType, 0 ); + oldFogType = 0; + sceneFogType = 0; + + } + + + // update positions and sort + + for ( var i = 0, l = sprites.length; i < l; i ++ ) { + + var sprite = sprites[ i ]; + + sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld ); + sprite.z = - sprite.modelViewMatrix.elements[ 14 ]; + + } + + sprites.sort( painterSortStable ); + + // render all sprites + + var scale = []; + var center = []; + + for ( var i = 0, l = sprites.length; i < l; i ++ ) { + + var sprite = sprites[ i ]; + var material = sprite.material; + + if ( material.visible === false ) continue; + + sprite.onBeforeRender( renderer, scene, camera, undefined, material, undefined ); + + gl.uniform1f( uniforms.alphaTest, material.alphaTest ); + gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements ); + + sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale ); + + scale[ 0 ] = spriteScale.x; + scale[ 1 ] = spriteScale.y; + + center[ 0 ] = sprite.center.x - 0.5; + center[ 1 ] = sprite.center.y - 0.5; + + var fogType = 0; + + if ( scene.fog && material.fog ) { + + fogType = sceneFogType; + + } + + if ( oldFogType !== fogType ) { + + gl.uniform1i( uniforms.fogType, fogType ); + oldFogType = fogType; + + } + + if ( material.map !== null ) { + + gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y ); + gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y ); + + } else { + + gl.uniform2f( uniforms.uvOffset, 0, 0 ); + gl.uniform2f( uniforms.uvScale, 1, 1 ); + + } + + gl.uniform1f( uniforms.opacity, material.opacity ); + gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b ); + + gl.uniform1f( uniforms.rotation, material.rotation ); + gl.uniform2fv( uniforms.center, center ); + gl.uniform2fv( uniforms.scale, scale ); + + state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); + state.buffers.depth.setTest( material.depthTest ); + state.buffers.depth.setMask( material.depthWrite ); + state.buffers.color.setMask( material.colorWrite ); + + textures.setTexture2D( material.map || texture, 0 ); + + gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); + + sprite.onAfterRender( renderer, scene, camera, undefined, material, undefined ); + + } + + // restore gl + + state.enable( gl.CULL_FACE ); + + state.reset(); + + }; + + function createProgram() { + + var program = gl.createProgram(); + + var vertexShader = gl.createShader( gl.VERTEX_SHADER ); + var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER ); + + gl.shaderSource( vertexShader, [ + + 'precision ' + capabilities.precision + ' float;', + + '#define SHADER_NAME ' + 'SpriteMaterial', + + 'uniform mat4 modelViewMatrix;', + 'uniform mat4 projectionMatrix;', + 'uniform float rotation;', + 'uniform vec2 center;', + 'uniform vec2 scale;', + 'uniform vec2 uvOffset;', + 'uniform vec2 uvScale;', + + 'attribute vec2 position;', + 'attribute vec2 uv;', + + 'varying vec2 vUV;', + 'varying float fogDepth;', + + 'void main() {', + + ' vUV = uvOffset + uv * uvScale;', + + ' vec2 alignedPosition = ( position - center ) * scale;', + + ' vec2 rotatedPosition;', + ' rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;', + ' rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;', + + ' vec4 mvPosition;', + + ' mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );', + ' mvPosition.xy += rotatedPosition;', + + ' gl_Position = projectionMatrix * mvPosition;', + + ' fogDepth = - mvPosition.z;', + + '}' + + ].join( '\n' ) ); + + gl.shaderSource( fragmentShader, [ + + 'precision ' + capabilities.precision + ' float;', + + '#define SHADER_NAME ' + 'SpriteMaterial', + + 'uniform vec3 color;', + 'uniform sampler2D map;', + 'uniform float opacity;', + + 'uniform int fogType;', + 'uniform vec3 fogColor;', + 'uniform float fogDensity;', + 'uniform float fogNear;', + 'uniform float fogFar;', + 'uniform float alphaTest;', + + 'varying vec2 vUV;', + 'varying float fogDepth;', + + 'void main() {', + + ' vec4 texture = texture2D( map, vUV );', + + ' gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );', + + ' if ( gl_FragColor.a < alphaTest ) discard;', + + ' if ( fogType > 0 ) {', + + ' float fogFactor = 0.0;', + + ' if ( fogType == 1 ) {', + + ' fogFactor = smoothstep( fogNear, fogFar, fogDepth );', + + ' } else {', + + ' const float LOG2 = 1.442695;', + ' fogFactor = exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 );', + ' fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );', + + ' }', + + ' gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );', + + ' }', + + '}' + + ].join( '\n' ) ); + + gl.compileShader( vertexShader ); + gl.compileShader( fragmentShader ); + + gl.attachShader( program, vertexShader ); + gl.attachShader( program, fragmentShader ); + + gl.linkProgram( program ); + + return program; + + } + + function painterSortStable( a, b ) { + + if ( a.renderOrder !== b.renderOrder ) { + + return a.renderOrder - b.renderOrder; + + } else if ( a.z !== b.z ) { + + return b.z - a.z; + + } else { + + return b.id - a.id; + + } + + } + + } + + /** + * @author mrdoob / http://mrdoob.com/ + */ + + function WebGLState( gl, extensions, utils ) { + + function ColorBuffer() { + + var locked = false; + + var color = new Vector4(); + var currentColorMask = null; + var currentColorClear = new Vector4( 0, 0, 0, 0 ); + + return { + + setMask: function ( colorMask ) { + + if ( currentColorMask !== colorMask && ! locked ) { + + gl.colorMask( colorMask, colorMask, colorMask, colorMask ); + currentColorMask = colorMask; + + } + + }, + + setLocked: function ( lock ) { + + locked = lock; + + }, + + setClear: function ( r, g, b, a, premultipliedAlpha ) { + + if ( premultipliedAlpha === true ) { + + r *= a; g *= a; b *= a; + + } + + color.set( r, g, b, a ); + + if ( currentColorClear.equals( color ) === false ) { + + gl.clearColor( r, g, b, a ); + currentColorClear.copy( color ); + + } + + }, + + reset: function () { + + locked = false; + + currentColorMask = null; + currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state + + } + + }; + + } + + function DepthBuffer() { + + var locked = false; + + var currentDepthMask = null; + var currentDepthFunc = null; + var currentDepthClear = null; + + return { + + setTest: function ( depthTest ) { + + if ( depthTest ) { + + enable( gl.DEPTH_TEST ); + + } else { + + disable( gl.DEPTH_TEST ); + + } + + }, + + setMask: function ( depthMask ) { + + if ( currentDepthMask !== depthMask && ! locked ) { + + gl.depthMask( depthMask ); + currentDepthMask = depthMask; + + } + + }, + + setFunc: function ( depthFunc ) { + + if ( currentDepthFunc !== depthFunc ) { + + if ( depthFunc ) { + + switch ( depthFunc ) { case NeverDepth: @@ -19127,6 +18997,8 @@ var compressedTextureFormats = null; + var currentProgram = null; + var currentBlending = null; var currentBlendEquation = null; var currentBlendSrc = null; @@ -19144,12 +19016,23 @@ var currentPolygonOffsetFactor = null; var currentPolygonOffsetUnits = null; - var currentScissorTest = null; - var maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS ); - var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] ); - var lineWidthAvailable = parseFloat( version ) >= 1.0; + var lineWidthAvailable = false; + var version = 0; + var glVersion = gl.getParameter( gl.VERSION ); + + if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) { + + version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 1.0 ); + + } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) { + + version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] ); + lineWidthAvailable = ( version >= 2.0 ); + + } var currentTextureSlot = null; var currentBoundTextures = {}; @@ -19180,25 +19063,23 @@ emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 ); emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 ); - // - - function init() { + // init - colorBuffer.setClear( 0, 0, 0, 1 ); - depthBuffer.setClear( 1 ); - stencilBuffer.setClear( 0 ); + colorBuffer.setClear( 0, 0, 0, 1 ); + depthBuffer.setClear( 1 ); + stencilBuffer.setClear( 0 ); - enable( gl.DEPTH_TEST ); - depthBuffer.setFunc( LessEqualDepth ); + enable( gl.DEPTH_TEST ); + depthBuffer.setFunc( LessEqualDepth ); - setFlipSided( false ); - setCullFace( CullFaceBack ); - enable( gl.CULL_FACE ); + setFlipSided( false ); + setCullFace( CullFaceBack ); + enable( gl.CULL_FACE ); - enable( gl.BLEND ); - setBlending( NormalBlending ); + enable( gl.BLEND ); + setBlending( NormalBlending ); - } + // function initAttributes() { @@ -19299,7 +19180,8 @@ if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || extensions.get( 'WEBGL_compressed_texture_s3tc' ) || - extensions.get( 'WEBGL_compressed_texture_etc1' ) ) { + extensions.get( 'WEBGL_compressed_texture_etc1' ) || + extensions.get( 'WEBGL_compressed_texture_astc' ) ) { var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS ); @@ -19317,9 +19199,25 @@ } - function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { + function useProgram( program ) { - if ( blending !== NoBlending ) { + if ( currentProgram !== program ) { + + gl.useProgram( program ); + + currentProgram = program; + + return true; + + } + + return false; + + } + + function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { + + if ( blending !== NoBlending ) { enable( gl.BLEND ); @@ -19329,72 +19227,83 @@ } - if ( ( blending !== CustomBlending ) && ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) ) { + if ( blending !== CustomBlending ) { - if ( blending === AdditiveBlending ) { + if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { - if ( premultipliedAlpha ) { + switch ( blending ) { - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE ); + case AdditiveBlending: - } else { + if ( premultipliedAlpha ) { - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE ); - } + } else { - } else if ( blending === SubtractiveBlending ) { + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); - if ( premultipliedAlpha ) { + } + break; - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA ); + case SubtractiveBlending: - } else { + if ( premultipliedAlpha ) { - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA ); - } + } else { - } else if ( blending === MultiplyBlending ) { + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR ); - if ( premultipliedAlpha ) { + } + break; - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); + case MultiplyBlending: - } else { + if ( premultipliedAlpha ) { - gl.blendEquation( gl.FUNC_ADD ); - gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA ); - } + } else { - } else { + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc( gl.ZERO, gl.SRC_COLOR ); - if ( premultipliedAlpha ) { + } + break; - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + default: - } else { + if ( premultipliedAlpha ) { - gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); - gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + + } else { + + gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD ); + gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); + + } } } - currentBlending = blending; - currentPremultipledAlpha = premultipliedAlpha; - - } + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; - if ( blending === CustomBlending ) { + } else { blendEquationAlpha = blendEquationAlpha || blendEquation; blendSrcAlpha = blendSrcAlpha || blendSrc; @@ -19402,7 +19311,7 @@ if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { - gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) ); + gl.blendEquationSeparate( utils.convert( blendEquation ), utils.convert( blendEquationAlpha ) ); currentBlendEquation = blendEquation; currentBlendEquationAlpha = blendEquationAlpha; @@ -19411,7 +19320,7 @@ if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { - gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) ); + gl.blendFuncSeparate( utils.convert( blendSrc ), utils.convert( blendDst ), utils.convert( blendSrcAlpha ), utils.convert( blendDstAlpha ) ); currentBlendSrc = blendSrc; currentBlendDst = blendDst; @@ -19420,26 +19329,23 @@ } - } else { - - currentBlendEquation = null; - currentBlendSrc = null; - currentBlendDst = null; - currentBlendEquationAlpha = null; - currentBlendSrcAlpha = null; - currentBlendDstAlpha = null; - } + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + } - function setMaterial( material ) { + function setMaterial( material, frontFaceCW ) { material.side === DoubleSide ? disable( gl.CULL_FACE ) : enable( gl.CULL_FACE ); - setFlipSided( material.side === BackSide ); + var flipSided = ( material.side === BackSide ); + if ( frontFaceCW ) flipSided = ! flipSided; + + setFlipSided( flipSided ); material.transparent === true ? setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ) @@ -19545,16 +19451,8 @@ } - function getScissorTest() { - - return currentScissorTest; - - } - function setScissorTest( scissorTest ) { - currentScissorTest = scissorTest; - if ( scissorTest ) { enable( gl.SCISSOR_TEST ); @@ -19684,6 +19582,8 @@ currentTextureSlot = null; currentBoundTextures = {}; + currentProgram = null; + currentBlending = null; currentFlipSided = null; @@ -19703,7 +19603,6 @@ stencil: stencilBuffer }, - init: init, initAttributes: initAttributes, enableAttribute: enableAttribute, enableAttributeAndDivisor: enableAttributeAndDivisor, @@ -19712,6 +19611,8 @@ disable: disable, getCompressedTextureFormats: getCompressedTextureFormats, + useProgram: useProgram, + setBlending: setBlending, setMaterial: setMaterial, @@ -19721,7 +19622,6 @@ setLineWidth: setLineWidth, setPolygonOffset: setPolygonOffset, - getScissorTest: getScissorTest, setScissorTest: setScissorTest, activeTexture: activeTexture, @@ -19742,4126 +19642,4028 @@ * @author mrdoob / http://mrdoob.com/ */ - function WebGLCapabilities( gl, extensions, parameters ) { - - var maxAnisotropy; - - function getMaxAnisotropy() { - - if ( maxAnisotropy !== undefined ) return maxAnisotropy; - - var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - - if ( extension !== null ) { - - maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); - - } else { - - maxAnisotropy = 0; - - } + function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { - return maxAnisotropy; + var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext ); /* global WebGL2RenderingContext */ + var _videoTextures = {}; + var _canvas; - } + // - function getMaxPrecision( precision ) { + function clampToMaxSize( image, maxSize ) { - if ( precision === 'highp' ) { + if ( image.width > maxSize || image.height > maxSize ) { - if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && - gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { + if ( 'data' in image ) { - return 'highp'; + console.warn( 'THREE.WebGLRenderer: image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); + return; } - precision = 'mediump'; + // Warning: Scaling through the canvas will only work with images that use + // premultiplied alpha. - } + var scale = maxSize / Math.max( image.width, image.height ); - if ( precision === 'mediump' ) { + var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); + canvas.width = Math.floor( image.width * scale ); + canvas.height = Math.floor( image.height * scale ); - if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && - gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { + var context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height ); - return 'mediump'; + console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image ); - } + return canvas; } - return 'lowp'; + return image; } - var precision = parameters.precision !== undefined ? parameters.precision : 'highp'; - var maxPrecision = getMaxPrecision( precision ); - - if ( maxPrecision !== precision ) { + function isPowerOfTwo( image ) { - console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' ); - precision = maxPrecision; + return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height ); } - var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' ); - - var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS ); - var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); - var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE ); - var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE ); + function makePowerOfTwo( image ) { - var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS ); - var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS ); - var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS ); - var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS ); + if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof ImageBitmap ) { - var vertexTextures = maxVertexTextures > 0; - var floatFragmentTextures = !! extensions.get( 'OES_texture_float' ); - var floatVertexTextures = vertexTextures && floatFragmentTextures; + if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); - return { + _canvas.width = _Math.floorPowerOfTwo( image.width ); + _canvas.height = _Math.floorPowerOfTwo( image.height ); - getMaxAnisotropy: getMaxAnisotropy, - getMaxPrecision: getMaxPrecision, + var context = _canvas.getContext( '2d' ); + context.drawImage( image, 0, 0, _canvas.width, _canvas.height ); - precision: precision, - logarithmicDepthBuffer: logarithmicDepthBuffer, + console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + _canvas.width + 'x' + _canvas.height, image ); - maxTextures: maxTextures, - maxVertexTextures: maxVertexTextures, - maxTextureSize: maxTextureSize, - maxCubemapSize: maxCubemapSize, + return _canvas; - maxAttributes: maxAttributes, - maxVertexUniforms: maxVertexUniforms, - maxVaryings: maxVaryings, - maxFragmentUniforms: maxFragmentUniforms, + } - vertexTextures: vertexTextures, - floatFragmentTextures: floatFragmentTextures, - floatVertexTextures: floatVertexTextures + return image; - }; + } - } + function textureNeedsPowerOfTwo( texture ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || + ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); - function ArrayCamera( array ) { + } - PerspectiveCamera.call( this ); + function textureNeedsGenerateMipmaps( texture, isPowerOfTwo ) { - this.cameras = array || []; + return texture.generateMipmaps && isPowerOfTwo && + texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; - } + } - ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), { + function generateMipmap( target, texture, width, height ) { - constructor: ArrayCamera, + _gl.generateMipmap( target ); - isArrayCamera: true + var textureProperties = properties.get( texture ); + textureProperties.__maxMipLevel = Math.log2( Math.max( width, height ) ); - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + // Fallback filters for non-power-of-2 textures - function WebVRManager( renderer ) { + function filterFallback( f ) { - var scope = this; + if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) { - var device = null; - var frameData = null; + return _gl.NEAREST; - if ( 'VRFrameData' in window ) { + } - frameData = new window.VRFrameData(); + return _gl.LINEAR; } - var matrixWorldInverse = new Matrix4(); + // - var standingMatrix = new Matrix4(); - var standingMatrixInverse = new Matrix4(); + function onTextureDispose( event ) { - var cameraL = new PerspectiveCamera(); - cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 ); - cameraL.layers.enable( 1 ); + var texture = event.target; - var cameraR = new PerspectiveCamera(); - cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 ); - cameraR.layers.enable( 2 ); + texture.removeEventListener( 'dispose', onTextureDispose ); - var cameraVR = new ArrayCamera( [ cameraL, cameraR ] ); - cameraVR.layers.enable( 1 ); - cameraVR.layers.enable( 2 ); + deallocateTexture( texture ); - // + if ( texture.isVideoTexture ) { - var currentSize, currentPixelRatio; + delete _videoTextures[ texture.id ]; - function onVRDisplayPresentChange() { + } - if ( device.isPresenting ) { + info.memory.textures --; - var eyeParameters = device.getEyeParameters( 'left' ); - var renderWidth = eyeParameters.renderWidth; - var renderHeight = eyeParameters.renderHeight; + } - currentPixelRatio = renderer.getPixelRatio(); - currentSize = renderer.getSize(); + function onRenderTargetDispose( event ) { - renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 ); + var renderTarget = event.target; - } else if ( scope.enabled ) { + renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); - renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio ); + deallocateRenderTarget( renderTarget ); - } + info.memory.textures --; } - window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false ); - // - this.enabled = false; - this.standing = false; + function deallocateTexture( texture ) { - this.getDevice = function () { + var textureProperties = properties.get( texture ); - return device; + if ( texture.image && textureProperties.__image__webglTextureCube ) { - }; + // cube texture - this.setDevice = function ( value ) { + _gl.deleteTexture( textureProperties.__image__webglTextureCube ); - if ( value !== undefined ) device = value; + } else { - }; + // 2D texture - this.getCamera = function ( camera ) { + if ( textureProperties.__webglInit === undefined ) return; - if ( device === null ) return camera; + _gl.deleteTexture( textureProperties.__webglTexture ); - device.depthNear = camera.near; - device.depthFar = camera.far; + } - device.getFrameData( frameData ); + // remove all webgl properties + properties.remove( texture ); - // + } - var pose = frameData.pose; + function deallocateRenderTarget( renderTarget ) { - if ( pose.position !== null ) { + var renderTargetProperties = properties.get( renderTarget ); + var textureProperties = properties.get( renderTarget.texture ); - camera.position.fromArray( pose.position ); + if ( ! renderTarget ) return; - } else { + if ( textureProperties.__webglTexture !== undefined ) { - camera.position.set( 0, 0, 0 ); + _gl.deleteTexture( textureProperties.__webglTexture ); } - if ( pose.orientation !== null ) { + if ( renderTarget.depthTexture ) { - camera.quaternion.fromArray( pose.orientation ); + renderTarget.depthTexture.dispose(); } - camera.updateMatrixWorld(); + if ( renderTarget.isWebGLRenderTargetCube ) { - var stageParameters = device.stageParameters; + for ( var i = 0; i < 6; i ++ ) { - if ( this.standing && stageParameters ) { + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); - standingMatrix.fromArray( stageParameters.sittingToStandingTransform ); - standingMatrixInverse.getInverse( standingMatrix ); + } - camera.matrixWorld.multiply( standingMatrix ); - camera.matrixWorldInverse.multiply( standingMatrixInverse ); + } else { + + _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); + if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); } - if ( device.isPresenting === false ) return camera; + properties.remove( renderTarget.texture ); + properties.remove( renderTarget ); - // + } - cameraVR.matrixWorld.copy( camera.matrixWorld ); - cameraVR.matrixWorldInverse.copy( camera.matrixWorldInverse ); + // - cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix ); - cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix ); - if ( this.standing && stageParameters ) { - cameraL.matrixWorldInverse.multiply( standingMatrixInverse ); - cameraR.matrixWorldInverse.multiply( standingMatrixInverse ); + function setTexture2D( texture, slot ) { - } + var textureProperties = properties.get( texture ); - var parent = camera.parent; + if ( texture.isVideoTexture ) updateVideoTexture( texture ); - if ( parent !== null ) { + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - matrixWorldInverse.getInverse( parent.matrixWorld ); + var image = texture.image; - cameraL.matrixWorldInverse.multiply( matrixWorldInverse ); - cameraR.matrixWorldInverse.multiply( matrixWorldInverse ); + if ( image === undefined ) { - } + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture ); - // envMap and Mirror needs camera.matrixWorld + } else if ( image.complete === false ) { - cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse ); - cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse ); + console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture ); - cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix ); - cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix ); + } else { - // HACK @mrdoob - // https://github.com/w3c/webvr/issues/203 + uploadTexture( textureProperties, texture, slot ); + return; - cameraVR.projectionMatrix.copy( cameraL.projectionMatrix ); + } - // + } - var layers = device.getLayers(); + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - if ( layers.length ) { + } - var layer = layers[ 0 ]; + function setTextureCube( texture, slot ) { - if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) { + var textureProperties = properties.get( texture ); - cameraL.bounds.fromArray( layer.leftBounds ); + if ( texture.image.length === 6 ) { - } + if ( texture.version > 0 && textureProperties.__version !== texture.version ) { - if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) { + if ( ! textureProperties.__image__webglTextureCube ) { - cameraR.bounds.fromArray( layer.rightBounds ); + texture.addEventListener( 'dispose', onTextureDispose ); - } + textureProperties.__image__webglTextureCube = _gl.createTexture(); - } + info.memory.textures ++; - return cameraVR; + } - }; + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); - this.getStandingMatrix = function () { + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); - return standingMatrix; + var isCompressed = ( texture && texture.isCompressedTexture ); + var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); - }; + var cubeImage = []; - this.submitFrame = function () { + for ( var i = 0; i < 6; i ++ ) { - if ( device && device.isPresenting ) device.submitFrame(); + if ( ! isCompressed && ! isDataTexture ) { - }; + cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize ); - } + } else { - /** - * @author mrdoob / http://mrdoob.com/ - */ + cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; - function WebGLExtensions( gl ) { + } - var extensions = {}; + } - return { + var image = cubeImage[ 0 ], + isPowerOfTwoImage = isPowerOfTwo( image ), + glFormat = utils.convert( texture.format ), + glType = utils.convert( texture.type ); - get: function ( name ) { + setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage ); - if ( extensions[ name ] !== undefined ) { + for ( var i = 0; i < 6; i ++ ) { - return extensions[ name ]; + if ( ! isCompressed ) { - } + if ( isDataTexture ) { - var extension; + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); - switch ( name ) { + } else { - case 'WEBGL_depth_texture': - extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); - break; + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); - case 'EXT_texture_filter_anisotropic': - extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); - break; + } - case 'WEBGL_compressed_texture_s3tc': - extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); - break; + } else { - case 'WEBGL_compressed_texture_pvrtc': - extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); - break; + var mipmap, mipmaps = cubeImage[ i ].mipmaps; - case 'WEBGL_compressed_texture_etc1': - extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' ); - break; + for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { - default: - extension = gl.getExtension( name ); + mipmap = mipmaps[ j ]; - } + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { - if ( extension === null ) { + if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { - console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); + state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - } + } else { - extensions[ name ] = extension; + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); - return extension; + } - } + } else { - }; + state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - } + } - /** - * @author tschw - */ + } - function WebGLClipping() { + } - var scope = this, + } - globalState = null, - numGlobalPlanes = 0, - localClippingEnabled = false, - renderingShadows = false, + if ( ! isCompressed ) { - plane = new Plane(), - viewNormalMatrix = new Matrix3(), + textureProperties.__maxMipLevel = 0; - uniform = { value: null, needsUpdate: false }; + } else { - this.uniform = uniform; - this.numPlanes = 0; - this.numIntersection = 0; + textureProperties.__maxMipLevel = mipmaps.length - 1; - this.init = function( planes, enableLocalClipping, camera ) { + } - var enabled = - planes.length !== 0 || - enableLocalClipping || - // enable state of previous frame - the clipping code has to - // run another frame in order to reset the state: - numGlobalPlanes !== 0 || - localClippingEnabled; + if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) { - localClippingEnabled = enableLocalClipping; + // We assume images for cube map have the same size. + generateMipmap( _gl.TEXTURE_CUBE_MAP, texture, image.width, image.height ); - globalState = projectPlanes( planes, camera, 0 ); - numGlobalPlanes = planes.length; + } - return enabled; + textureProperties.__version = texture.version; - }; + if ( texture.onUpdate ) texture.onUpdate( texture ); - this.beginShadows = function() { + } else { - renderingShadows = true; - projectPlanes( null ); + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube ); - }; + } - this.endShadows = function() { + } - renderingShadows = false; - resetGlobalState(); + } - }; + function setTextureCubeDynamic( texture, slot ) { - this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) { + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture ); - if ( ! localClippingEnabled || - planes === null || planes.length === 0 || - renderingShadows && ! clipShadows ) { - // there's no local clipping + } - if ( renderingShadows ) { - // there's no global clipping + function setTextureParameters( textureType, texture, isPowerOfTwoImage ) { - projectPlanes( null ); + var extension; - } else { + if ( isPowerOfTwoImage ) { - resetGlobalState(); - } + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, utils.convert( texture.wrapS ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, utils.convert( texture.wrapT ) ); + + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, utils.convert( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, utils.convert( texture.minFilter ) ); } else { - var nGlobal = renderingShadows ? 0 : numGlobalPlanes, - lGlobal = nGlobal * 4, + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); + _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); - dstArray = cache.clippingState || null; + if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { - uniform.value = dstArray; // ensure unique state + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture ); - dstArray = projectPlanes( planes, camera, lGlobal, fromCache ); + } - for ( var i = 0; i !== lGlobal; ++ i ) { + _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); + _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); - dstArray[ i ] = globalState[ i ]; + if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { - } + console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture ); - cache.clippingState = dstArray; - this.numIntersection = clipIntersection ? this.numPlanes : 0; - this.numPlanes += nGlobal; + } } + extension = extensions.get( 'EXT_texture_filter_anisotropic' ); - }; + if ( extension ) { - function resetGlobalState() { + if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return; + if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return; - if ( uniform.value !== globalState ) { + if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { - uniform.value = globalState; - uniform.needsUpdate = numGlobalPlanes > 0; + _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); + properties.get( texture ).__currentAnisotropy = texture.anisotropy; - } + } - scope.numPlanes = numGlobalPlanes; - scope.numIntersection = 0; + } } - function projectPlanes( planes, camera, dstOffset, skipTransform ) { - - var nPlanes = planes !== null ? planes.length : 0, - dstArray = null; + function uploadTexture( textureProperties, texture, slot ) { - if ( nPlanes !== 0 ) { + if ( textureProperties.__webglInit === undefined ) { - dstArray = uniform.value; + textureProperties.__webglInit = true; - if ( skipTransform !== true || dstArray === null ) { + texture.addEventListener( 'dispose', onTextureDispose ); - var flatSize = dstOffset + nPlanes * 4, - viewMatrix = camera.matrixWorldInverse; + textureProperties.__webglTexture = _gl.createTexture(); - viewNormalMatrix.getNormalMatrix( viewMatrix ); + info.memory.textures ++; - if ( dstArray === null || dstArray.length < flatSize ) { + } - dstArray = new Float32Array( flatSize ); + state.activeTexture( _gl.TEXTURE0 + slot ); + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); - } + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); - for ( var i = 0, i4 = dstOffset; - i !== nPlanes; ++ i, i4 += 4 ) { + var image = clampToMaxSize( texture.image, capabilities.maxTextureSize ); - plane.copy( planes[ i ] ). - applyMatrix4( viewMatrix, viewNormalMatrix ); + if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) { - plane.normal.toArray( dstArray, i4 ); - dstArray[ i4 + 3 ] = plane.constant; + image = makePowerOfTwo( image ); - } + } - } + var isPowerOfTwoImage = isPowerOfTwo( image ), + glFormat = utils.convert( texture.format ), + glType = utils.convert( texture.type ); - uniform.value = dstArray; - uniform.needsUpdate = true; + setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage ); - } + var mipmap, mipmaps = texture.mipmaps; - scope.numPlanes = nPlanes; - - return dstArray; + if ( texture.isDepthTexture ) { - } + // populate depth texture with dummy data - } + var internalFormat = _gl.DEPTH_COMPONENT; - // import { Sphere } from '../math/Sphere'; - /** - * @author supereggbert / http://www.paulbrunt.co.uk/ - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * @author szimek / https://github.com/szimek/ - * @author tschw - */ + if ( texture.type === FloatType ) { - function WebGLRenderer( parameters ) { + if ( ! _isWebGL2 ) throw new Error( 'Float Depth Texture only supported in WebGL2.0' ); + internalFormat = _gl.DEPTH_COMPONENT32F; - console.log( 'THREE.WebGLRenderer', REVISION ); + } else if ( _isWebGL2 ) { - parameters = parameters || {}; + // WebGL 2.0 requires signed internalformat for glTexImage2D + internalFormat = _gl.DEPTH_COMPONENT16; - var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), - _context = parameters.context !== undefined ? parameters.context : null, + } - _alpha = parameters.alpha !== undefined ? parameters.alpha : false, - _depth = parameters.depth !== undefined ? parameters.depth : true, - _stencil = parameters.stencil !== undefined ? parameters.stencil : true, - _antialias = parameters.antialias !== undefined ? parameters.antialias : false, - _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, - _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false; + if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) { - var lights = []; + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { - var currentRenderList = null; + console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); - var morphInfluences = new Float32Array( 8 ); + texture.type = UnsignedShortType; + glType = utils.convert( texture.type ); - var sprites = []; - var lensFlares = []; + } - // public properties + } - this.domElement = _canvas; - this.context = null; + // Depth stencil textures need the DEPTH_STENCIL internal format + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.format === DepthStencilFormat ) { - // clearing + internalFormat = _gl.DEPTH_STENCIL; - this.autoClear = true; - this.autoClearColor = true; - this.autoClearDepth = true; - this.autoClearStencil = true; + // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are + // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. + // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) + if ( texture.type !== UnsignedInt248Type ) { - // scene graph + console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); - this.sortObjects = true; + texture.type = UnsignedInt248Type; + glType = utils.convert( texture.type ); - // user-defined clipping + } - this.clippingPlanes = []; - this.localClippingEnabled = false; + } - // physically based shading + state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null ); - this.gammaFactor = 2.0; // for backwards compatibility - this.gammaInput = false; - this.gammaOutput = false; + } else if ( texture.isDataTexture ) { - // physical lights + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels - this.physicallyCorrectLights = false; + if ( mipmaps.length > 0 && isPowerOfTwoImage ) { - // tone mapping + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - this.toneMapping = LinearToneMapping; - this.toneMappingExposure = 1.0; - this.toneMappingWhitePoint = 1.0; + mipmap = mipmaps[ i ]; + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - // morphs + } - this.maxMorphTargets = 8; - this.maxMorphNormals = 4; + texture.generateMipmaps = false; + textureProperties.__maxMipLevel = mipmaps.length - 1; - // internal properties + } else { - var _this = this, + state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); + textureProperties.__maxMipLevel = 0; - // internal state cache + } - _currentProgram = null, - _currentRenderTarget = null, - _currentFramebuffer = null, - _currentMaterialId = - 1, - _currentGeometryProgram = '', + } else if ( texture.isCompressedTexture ) { - _currentCamera = null, - _currentArrayCamera = null, + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - _currentScissor = new Vector4(), - _currentScissorTest = null, + mipmap = mipmaps[ i ]; - _currentViewport = new Vector4(), + if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { - // + if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) { - _usedTextureUnits = 0, + state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); - // + } else { - _width = _canvas.width, - _height = _canvas.height, + console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); - _pixelRatio = 1, + } - _scissor = new Vector4( 0, 0, _width, _height ), - _scissorTest = false, + } else { - _viewport = new Vector4( 0, 0, _width, _height ), + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); - // frustum + } - _frustum = new Frustum(), + } - // clipping + textureProperties.__maxMipLevel = mipmaps.length - 1; - _clipping = new WebGLClipping(), - _clippingEnabled = false, - _localClippingEnabled = false, + } else { - // camera matrices cache + // regular Texture (image, video, canvas) - _projScreenMatrix = new Matrix4(), + // use manually created mipmaps if available + // if there are no manual mipmaps + // set 0 level mipmap and then use GL to generate other mipmap levels - _vector3 = new Vector3(), - _matrix4 = new Matrix4(), - _matrix42 = new Matrix4(), + if ( mipmaps.length > 0 && isPowerOfTwoImage ) { - // light arrays cache + for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { - _lights = { + mipmap = mipmaps[ i ]; + state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); - hash: '', + } - ambient: [ 0, 0, 0 ], - directional: [], - directionalShadowMap: [], - directionalShadowMatrix: [], - spot: [], - spotShadowMap: [], - spotShadowMatrix: [], - rectArea: [], - point: [], - pointShadowMap: [], - pointShadowMatrix: [], - hemi: [], + texture.generateMipmaps = false; + textureProperties.__maxMipLevel = mipmaps.length - 1; - shadows: [] + } else { - }, + state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image ); + textureProperties.__maxMipLevel = 0; - // info + } - _infoMemory = { - geometries: 0, - textures: 0 - }, + } - _infoRender = { + if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) { - frame: 0, - calls: 0, - vertices: 0, - faces: 0, - points: 0 + generateMipmap( _gl.TEXTURE_2D, texture, image.width, image.height ); - }; + } - this.info = { + textureProperties.__version = texture.version; - render: _infoRender, - memory: _infoMemory, - programs: null + if ( texture.onUpdate ) texture.onUpdate( texture ); - }; + } + // Render targets - // initialize + // Setup storage for target texture and bind it to correct framebuffer + function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) { - var _gl; + var glFormat = utils.convert( renderTarget.texture.format ); + var glType = utils.convert( renderTarget.texture.type ); + state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 ); + _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); - try { + } - var contextAttributes = { - alpha: _alpha, - depth: _depth, - stencil: _stencil, - antialias: _antialias, - premultipliedAlpha: _premultipliedAlpha, - preserveDrawingBuffer: _preserveDrawingBuffer - }; + // Setup storage for internal depth/stencil buffers and bind to correct framebuffer + function setupRenderBufferStorage( renderbuffer, renderTarget ) { - _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes ); + _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); - if ( _gl === null ) { + if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { - if ( _canvas.getContext( 'webgl' ) !== null ) { + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - throw 'Error creating WebGL context with your selected attributes.'; + } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { - } else { + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); + _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); - throw 'Error creating WebGL context.'; + } else { - } + // FIXME: We don't support !depth !stencil + _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); } - // Some experimental-webgl implementations do not have getShaderPrecisionFormat + _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); - if ( _gl.getShaderPrecisionFormat === undefined ) { + } - _gl.getShaderPrecisionFormat = function () { + // Setup resources for a Depth Texture for a FBO (needs an extension) + function setupDepthTexture( framebuffer, renderTarget ) { - return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; + var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube ); + if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' ); - }; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - } + if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { - _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' ); - } catch ( error ) { + } - console.error( 'THREE.WebGLRenderer: ' + error ); + // upload an empty depth texture with framebuffer size + if ( ! properties.get( renderTarget.depthTexture ).__webglTexture || + renderTarget.depthTexture.image.width !== renderTarget.width || + renderTarget.depthTexture.image.height !== renderTarget.height ) { - } + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + + } - var extensions = new WebGLExtensions( _gl ); + setTexture2D( renderTarget.depthTexture, 0 ); - extensions.get( 'WEBGL_depth_texture' ); - extensions.get( 'OES_texture_float' ); - extensions.get( 'OES_texture_float_linear' ); - extensions.get( 'OES_texture_half_float' ); - extensions.get( 'OES_texture_half_float_linear' ); - extensions.get( 'OES_standard_derivatives' ); - extensions.get( 'ANGLE_instanced_arrays' ); + var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; - if ( extensions.get( 'OES_element_index_uint' ) ) { + if ( renderTarget.depthTexture.format === DepthFormat ) { - BufferGeometry.MaxIndex = 4294967296; + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); - } + } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { - var capabilities = new WebGLCapabilities( _gl, extensions, parameters ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); - var state = new WebGLState( _gl, extensions, paramThreeToGL ); + } else { - var properties = new WebGLProperties(); - var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, _infoMemory ); - var attributes = new WebGLAttributes( _gl ); - var geometries = new WebGLGeometries( _gl, attributes, _infoMemory ); - var objects = new WebGLObjects( _gl, geometries, _infoRender ); - var programCache = new WebGLPrograms( this, capabilities ); - var lightCache = new WebGLLights(); - var renderLists = new WebGLRenderLists(); + throw new Error( 'Unknown depthTexture format' ); - var background = new WebGLBackground( this, state, objects, _premultipliedAlpha ); - var vr = new WebVRManager( this ); + } - this.info.programs = programCache.programs; + } - var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender ); - var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ); + // Setup GL resources for a non-texture depth buffer + function setupDepthRenderbuffer( renderTarget ) { - // + var renderTargetProperties = properties.get( renderTarget ); - function getTargetPixelRatio() { + var isCube = ( renderTarget.isWebGLRenderTargetCube === true ); - return _currentRenderTarget === null ? _pixelRatio : 1; + if ( renderTarget.depthTexture ) { - } + if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' ); - function setDefaultGLState() { + setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); - state.init(); + } else { - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); + if ( isCube ) { - } + renderTargetProperties.__webglDepthbuffer = []; - function resetGLState() { + for ( var i = 0; i < 6; i ++ ) { - _currentProgram = null; - _currentCamera = null; + _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); + renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget ); - _currentGeometryProgram = ''; - _currentMaterialId = - 1; + } - state.reset(); + } else { - } + _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget ); - setDefaultGLState(); + } - this.context = _gl; - this.capabilities = capabilities; - this.extensions = extensions; - this.properties = properties; - this.renderLists = renderLists; - this.state = state; - this.vr = vr; + } - // shadow map + _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); - var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities ); + } - this.shadowMap = shadowMap; + // Set up GL resources for the render target + function setupRenderTarget( renderTarget ) { + var renderTargetProperties = properties.get( renderTarget ); + var textureProperties = properties.get( renderTarget.texture ); - // Plugins + renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); - var spritePlugin = new SpritePlugin( this, sprites ); - var lensFlarePlugin = new LensFlarePlugin( this, lensFlares ); + textureProperties.__webglTexture = _gl.createTexture(); - // API + info.memory.textures ++; - this.getContext = function () { + var isCube = ( renderTarget.isWebGLRenderTargetCube === true ); + var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); - return _gl; + // Setup framebuffer - }; + if ( isCube ) { - this.getContextAttributes = function () { + renderTargetProperties.__webglFramebuffer = []; - return _gl.getContextAttributes(); + for ( var i = 0; i < 6; i ++ ) { - }; + renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); - this.forceContextLoss = function () { + } - var extension = extensions.get( 'WEBGL_lose_context' ); - if ( extension ) extension.loseContext(); + } else { - }; + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); - this.getMaxAnisotropy = function () { + } - return capabilities.getMaxAnisotropy(); + // Setup color buffer - }; + if ( isCube ) { - this.getPrecision = function () { + state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo ); - return capabilities.precision; + for ( var i = 0; i < 6; i ++ ) { - }; + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); - this.getPixelRatio = function () { + } - return _pixelRatio; + if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) { - }; + generateMipmap( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, renderTarget.width, renderTarget.height ); - this.setPixelRatio = function ( value ) { + } - if ( value === undefined ) return; + state.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); - _pixelRatio = value; + } else { - this.setSize( _width, _height, false ); + state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); + setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo ); + setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D ); - }; + if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) { - this.getSize = function () { + generateMipmap( _gl.TEXTURE_2D, renderTarget.texture, renderTarget.width, renderTarget.height ); - return { - width: _width, - height: _height - }; + } - }; + state.bindTexture( _gl.TEXTURE_2D, null ); - this.setSize = function ( width, height, updateStyle ) { + } - var device = vr.getDevice(); + // Setup depth and stencil buffers - if ( device && device.isPresenting ) { + if ( renderTarget.depthBuffer ) { - console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); - return; + setupDepthRenderbuffer( renderTarget ); } - _width = width; - _height = height; + } - _canvas.width = width * _pixelRatio; - _canvas.height = height * _pixelRatio; + function updateRenderTargetMipmap( renderTarget ) { - if ( updateStyle !== false ) { + var texture = renderTarget.texture; + var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); - _canvas.style.width = width + 'px'; - _canvas.style.height = height + 'px'; + if ( textureNeedsGenerateMipmaps( texture, isTargetPowerOfTwo ) ) { + + var target = renderTarget.isWebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; + var webglTexture = properties.get( texture ).__webglTexture; + + state.bindTexture( target, webglTexture ); + generateMipmap( target, texture, renderTarget.width, renderTarget.height ); + state.bindTexture( target, null ); } - this.setViewport( 0, 0, width, height ); + } - }; + function updateVideoTexture( texture ) { - this.getDrawingBufferSize = function () { + var id = texture.id; + var frame = info.render.frame; - return { - width: _width * _pixelRatio, - height: _height * _pixelRatio - }; + // Check the last frame we updated the VideoTexture - }; + if ( _videoTextures[ id ] !== frame ) { - this.setDrawingBufferSize = function ( width, height, pixelRatio ) { + _videoTextures[ id ] = frame; + texture.update(); - _width = width; - _height = height; + } - _pixelRatio = pixelRatio; + } - _canvas.width = width * pixelRatio; - _canvas.height = height * pixelRatio; + this.setTexture2D = setTexture2D; + this.setTextureCube = setTextureCube; + this.setTextureCubeDynamic = setTextureCubeDynamic; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; - this.setViewport( 0, 0, width, height ); + } - }; + /** + * @author thespite / http://www.twitter.com/thespite + */ - this.setViewport = function ( x, y, width, height ) { + function WebGLUtils( gl, extensions ) { - _viewport.set( x, _height - y - height, width, height ); - state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); + function convert( p ) { - }; + var extension; - this.setScissor = function ( x, y, width, height ) { + if ( p === RepeatWrapping ) return gl.REPEAT; + if ( p === ClampToEdgeWrapping ) return gl.CLAMP_TO_EDGE; + if ( p === MirroredRepeatWrapping ) return gl.MIRRORED_REPEAT; - _scissor.set( x, _height - y - height, width, height ); - state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); + if ( p === NearestFilter ) return gl.NEAREST; + if ( p === NearestMipMapNearestFilter ) return gl.NEAREST_MIPMAP_NEAREST; + if ( p === NearestMipMapLinearFilter ) return gl.NEAREST_MIPMAP_LINEAR; - }; + if ( p === LinearFilter ) return gl.LINEAR; + if ( p === LinearMipMapNearestFilter ) return gl.LINEAR_MIPMAP_NEAREST; + if ( p === LinearMipMapLinearFilter ) return gl.LINEAR_MIPMAP_LINEAR; - this.setScissorTest = function ( boolean ) { + if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE; + if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4; + if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1; + if ( p === UnsignedShort565Type ) return gl.UNSIGNED_SHORT_5_6_5; - state.setScissorTest( _scissorTest = boolean ); + if ( p === ByteType ) return gl.BYTE; + if ( p === ShortType ) return gl.SHORT; + if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT; + if ( p === IntType ) return gl.INT; + if ( p === UnsignedIntType ) return gl.UNSIGNED_INT; + if ( p === FloatType ) return gl.FLOAT; - }; + if ( p === HalfFloatType ) { - // Clearing + extension = extensions.get( 'OES_texture_half_float' ); - this.getClearColor = background.getClearColor; - this.setClearColor = background.setClearColor; - this.getClearAlpha = background.getClearAlpha; - this.setClearAlpha = background.setClearAlpha; + if ( extension !== null ) return extension.HALF_FLOAT_OES; - this.clear = function ( color, depth, stencil ) { + } - var bits = 0; + if ( p === AlphaFormat ) return gl.ALPHA; + if ( p === RGBFormat ) return gl.RGB; + if ( p === RGBAFormat ) return gl.RGBA; + if ( p === LuminanceFormat ) return gl.LUMINANCE; + if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA; + if ( p === DepthFormat ) return gl.DEPTH_COMPONENT; + if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL; - if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; - if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; - if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; + if ( p === AddEquation ) return gl.FUNC_ADD; + if ( p === SubtractEquation ) return gl.FUNC_SUBTRACT; + if ( p === ReverseSubtractEquation ) return gl.FUNC_REVERSE_SUBTRACT; - _gl.clear( bits ); + if ( p === ZeroFactor ) return gl.ZERO; + if ( p === OneFactor ) return gl.ONE; + if ( p === SrcColorFactor ) return gl.SRC_COLOR; + if ( p === OneMinusSrcColorFactor ) return gl.ONE_MINUS_SRC_COLOR; + if ( p === SrcAlphaFactor ) return gl.SRC_ALPHA; + if ( p === OneMinusSrcAlphaFactor ) return gl.ONE_MINUS_SRC_ALPHA; + if ( p === DstAlphaFactor ) return gl.DST_ALPHA; + if ( p === OneMinusDstAlphaFactor ) return gl.ONE_MINUS_DST_ALPHA; - }; + if ( p === DstColorFactor ) return gl.DST_COLOR; + if ( p === OneMinusDstColorFactor ) return gl.ONE_MINUS_DST_COLOR; + if ( p === SrcAlphaSaturateFactor ) return gl.SRC_ALPHA_SATURATE; - this.clearColor = function () { + if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || + p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { - this.clear( true, false, false ); + extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); - }; + if ( extension !== null ) { - this.clearDepth = function () { + if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; - this.clear( false, true, false ); + } - }; + } - this.clearStencil = function () { + if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || + p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { - this.clear( false, false, true ); + extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); - }; + if ( extension !== null ) { - this.clearTarget = function ( renderTarget, color, depth, stencil ) { + if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; - this.setRenderTarget( renderTarget ); - this.clear( color, depth, stencil ); + } - }; + } - // Reset + if ( p === RGB_ETC1_Format ) { - this.resetGLState = resetGLState; + extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); - this.dispose = function () { + if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL; - _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + } - renderLists.dispose(); + if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || + p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || + p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || + p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || + p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) { - }; + extension = extensions.get( 'WEBGL_compressed_texture_astc' ); - // Events + if ( extension !== null ) { - function onContextLost( event ) { + return p; - event.preventDefault(); + } - resetGLState(); - setDefaultGLState(); + } - properties.clear(); - objects.clear(); + if ( p === MinEquation || p === MaxEquation ) { - } + extension = extensions.get( 'EXT_blend_minmax' ); - function onMaterialDispose( event ) { + if ( extension !== null ) { - var material = event.target; + if ( p === MinEquation ) return extension.MIN_EXT; + if ( p === MaxEquation ) return extension.MAX_EXT; - material.removeEventListener( 'dispose', onMaterialDispose ); + } - deallocateMaterial( material ); + } - } + if ( p === UnsignedInt248Type ) { - // Buffer deallocation + extension = extensions.get( 'WEBGL_depth_texture' ); - function deallocateMaterial( material ) { + if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL; - releaseMaterialProgramReference( material ); + } - properties.remove( material ); + return 0; } + return { convert: convert }; - function releaseMaterialProgramReference( material ) { + } - var programInfo = properties.get( material ).program; + /** + * @author mrdoob / http://mrdoob.com/ + * @author greggman / http://games.greggman.com/ + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author tschw + */ - material.program = undefined; + function PerspectiveCamera( fov, aspect, near, far ) { - if ( programInfo !== undefined ) { + Camera.call( this ); - programCache.releaseProgram( programInfo ); + this.type = 'PerspectiveCamera'; - } + this.fov = fov !== undefined ? fov : 50; + this.zoom = 1; - } + this.near = near !== undefined ? near : 0.1; + this.far = far !== undefined ? far : 2000; + this.focus = 10; - // Buffer rendering + this.aspect = aspect !== undefined ? aspect : 1; + this.view = null; - function renderObjectImmediate( object, program, material ) { + this.filmGauge = 35; // width of the film (default in millimeters) + this.filmOffset = 0; // horizontal film offset (same unit as gauge) - object.render( function ( object ) { + this.updateProjectionMatrix(); - _this.renderBufferImmediate( object, program, material ); + } - } ); + PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { - } + constructor: PerspectiveCamera, - this.renderBufferImmediate = function ( object, program, material ) { + isPerspectiveCamera: true, - state.initAttributes(); + copy: function ( source, recursive ) { - var buffers = properties.get( object ); + Camera.prototype.copy.call( this, source, recursive ); - if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer(); - if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer(); - if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer(); - if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer(); + this.fov = source.fov; + this.zoom = source.zoom; - var programAttributes = program.getAttributes(); + this.near = source.near; + this.far = source.far; + this.focus = source.focus; - if ( object.hasPositions ) { + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign( {}, source.view ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; - state.enableAttribute( programAttributes.position ); - _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 ); + return this; - } + }, - if ( object.hasNormals ) { + /** + * Sets the FOV by focal length in respect to the current .filmGauge. + * + * The default film gauge is 35, so that the focal length can be specified for + * a 35mm (full frame) camera. + * + * Values for focal length and film gauge must have the same unit. + */ + setFocalLength: function ( focalLength ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); + // see http://www.bobatkins.com/photography/technical/field_of_view.html + var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; - if ( ! material.isMeshPhongMaterial && - ! material.isMeshStandardMaterial && - ! material.isMeshNormalMaterial && - material.shading === FlatShading ) { + this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope ); + this.updateProjectionMatrix(); - for ( var i = 0, l = object.count * 3; i < l; i += 9 ) { + }, - var array = object.normalArray; + /** + * Calculates the focal length from the current .fov and .filmGauge. + */ + getFocalLength: function () { - var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3; - var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3; - var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3; + var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov ); - array[ i + 0 ] = nx; - array[ i + 1 ] = ny; - array[ i + 2 ] = nz; + return 0.5 * this.getFilmHeight() / vExtentSlope; - array[ i + 3 ] = nx; - array[ i + 4 ] = ny; - array[ i + 5 ] = nz; + }, - array[ i + 6 ] = nx; - array[ i + 7 ] = ny; - array[ i + 8 ] = nz; + getEffectiveFOV: function () { - } + return _Math.RAD2DEG * 2 * Math.atan( + Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom ); - } + }, - _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); + getFilmWidth: function () { - state.enableAttribute( programAttributes.normal ); + // film not completely covered in portrait format (aspect < 1) + return this.filmGauge * Math.min( this.aspect, 1 ); - _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 ); + }, - } + getFilmHeight: function () { - if ( object.hasUvs && material.map ) { + // film not completely covered in landscape format (aspect > 1) + return this.filmGauge / Math.max( this.aspect, 1 ); - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); + }, - state.enableAttribute( programAttributes.uv ); + /** + * Sets an offset in a larger frustum. This is useful for multi-window or + * multi-monitor/multi-machine setups. + * + * For example, if you have 3x2 monitors and each monitor is 1920x1080 and + * the monitors are in grid like this + * + * +---+---+---+ + * | A | B | C | + * +---+---+---+ + * | D | E | F | + * +---+---+---+ + * + * then for each monitor you would call it like this + * + * var w = 1920; + * var h = 1080; + * var fullWidth = w * 3; + * var fullHeight = h * 2; + * + * --A-- + * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * --B-- + * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * --C-- + * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * --D-- + * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * --E-- + * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * --F-- + * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); + * + * Note there is no reason monitors have to be the same size or in a grid. + */ + setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { + + this.aspect = fullWidth / fullHeight; + + if ( this.view === null ) { - _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; } - if ( object.hasColors && material.vertexColors !== NoColors ) { + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); - _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); + this.updateProjectionMatrix(); - state.enableAttribute( programAttributes.color ); + }, - _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 ); + clearViewOffset: function () { + + if ( this.view !== null ) { + + this.view.enabled = false; } - state.disableUnusedAttributes(); + this.updateProjectionMatrix(); - _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); + }, - object.count = 0; + updateProjectionMatrix: function () { - }; + var near = this.near, + top = near * Math.tan( + _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom, + height = 2 * top, + width = this.aspect * height, + left = - 0.5 * width, + view = this.view; - function absNumericalSort( a, b ) { + if ( this.view !== null && this.view.enabled ) { - return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] ); + var fullWidth = view.fullWidth, + fullHeight = view.fullHeight; - } + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; - this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) { + } - state.setMaterial( material ); + var skew = this.filmOffset; + if ( skew !== 0 ) left += near * skew / this.getFilmWidth(); - var program = setProgram( camera, fog, material, object ); - var geometryProgram = geometry.id + '_' + program.id + '_' + ( material.wireframe === true ); + this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far ); - var updateBuffers = false; + }, - if ( geometryProgram !== _currentGeometryProgram ) { + toJSON: function ( meta ) { - _currentGeometryProgram = geometryProgram; - updateBuffers = true; + var data = Object3D.prototype.toJSON.call( this, meta ); - } + data.object.fov = this.fov; + data.object.zoom = this.zoom; - // morph targets + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; - var morphTargetInfluences = object.morphTargetInfluences; + data.object.aspect = this.aspect; - if ( morphTargetInfluences !== undefined ) { + if ( this.view !== null ) data.object.view = Object.assign( {}, this.view ); - // TODO Remove allocations + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; - var activeInfluences = []; + return data; - for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) { + } - var influence = morphTargetInfluences[ i ]; - activeInfluences.push( [ influence, i ] ); + } ); - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - activeInfluences.sort( absNumericalSort ); + function ArrayCamera( array ) { - if ( activeInfluences.length > 8 ) { + PerspectiveCamera.call( this ); - activeInfluences.length = 8; + this.cameras = array || []; - } + } - var morphAttributes = geometry.morphAttributes; + ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), { - for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) { + constructor: ArrayCamera, - var influence = activeInfluences[ i ]; - morphInfluences[ i ] = influence[ 0 ]; + isArrayCamera: true - if ( influence[ 0 ] !== 0 ) { + } ); - var index = influence[ 1 ]; + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] ); - if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] ); + function WebVRManager( renderer ) { - } else { + var scope = this; - if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i ); - if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i ); + var device = null; + var frameData = null; - } + var poseTarget = null; - } + var standingMatrix = new Matrix4(); + var standingMatrixInverse = new Matrix4(); - for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) { + if ( typeof window !== 'undefined' && 'VRFrameData' in window ) { - morphInfluences[ i ] = 0.0; + frameData = new window.VRFrameData(); - } + } - program.getUniforms().setValue( _gl, 'morphTargetInfluences', morphInfluences ); + var matrixWorldInverse = new Matrix4(); + var tempQuaternion = new Quaternion(); + var tempPosition = new Vector3(); - updateBuffers = true; + var cameraL = new PerspectiveCamera(); + cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 ); + cameraL.layers.enable( 1 ); - } + var cameraR = new PerspectiveCamera(); + cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 ); + cameraR.layers.enable( 2 ); - // + var cameraVR = new ArrayCamera( [ cameraL, cameraR ] ); + cameraVR.layers.enable( 1 ); + cameraVR.layers.enable( 2 ); - var index = geometry.index; - var position = geometry.attributes.position; - var rangeFactor = 1; + // - if ( material.wireframe === true ) { + var currentSize, currentPixelRatio; - index = geometries.getWireframeAttribute( geometry ); - rangeFactor = 2; + function onVRDisplayPresentChange() { - } + if ( device !== null && device.isPresenting ) { - var attribute; - var renderer = bufferRenderer; + var eyeParameters = device.getEyeParameters( 'left' ); + var renderWidth = eyeParameters.renderWidth; + var renderHeight = eyeParameters.renderHeight; - if ( index !== null ) { + currentPixelRatio = renderer.getPixelRatio(); + currentSize = renderer.getSize(); - attribute = attributes.get( index ); + renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 ); - renderer = indexedBufferRenderer; - renderer.setIndex( attribute ); + } else if ( scope.enabled ) { + + renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio ); } - if ( updateBuffers ) { + } - setupVertexAttributes( material, program, geometry ); + if ( typeof window !== 'undefined' ) { - if ( index !== null ) { + window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false ); - _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer ); + } - } + // - } + this.enabled = false; + this.userHeight = 1.6; - // + this.getDevice = function () { - var dataCount = 0; + return device; - if ( index !== null ) { + }; - dataCount = index.count; + this.setDevice = function ( value ) { - } else if ( position !== undefined ) { + if ( value !== undefined ) device = value; - dataCount = position.count; + }; - } + this.setPoseTarget = function ( object ) { - var rangeStart = geometry.drawRange.start * rangeFactor; - var rangeCount = geometry.drawRange.count * rangeFactor; + if ( object !== undefined ) poseTarget = object; - var groupStart = group !== null ? group.start * rangeFactor : 0; - var groupCount = group !== null ? group.count * rangeFactor : Infinity; + }; - var drawStart = Math.max( rangeStart, groupStart ); - var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; + this.getCamera = function ( camera ) { - var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); + if ( device === null ) return camera; - if ( drawCount === 0 ) return; + device.depthNear = camera.near; + device.depthFar = camera.far; + + device.getFrameData( frameData ); // - if ( object.isMesh ) { + var stageParameters = device.stageParameters; - if ( material.wireframe === true ) { + if ( stageParameters ) { - state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); - renderer.setMode( _gl.LINES ); + standingMatrix.fromArray( stageParameters.sittingToStandingTransform ); - } else { + } else { - switch ( object.drawMode ) { + standingMatrix.makeTranslation( 0, scope.userHeight, 0 ); - case TrianglesDrawMode: - renderer.setMode( _gl.TRIANGLES ); - break; + } - case TriangleStripDrawMode: - renderer.setMode( _gl.TRIANGLE_STRIP ); - break; - case TriangleFanDrawMode: - renderer.setMode( _gl.TRIANGLE_FAN ); - break; + var pose = frameData.pose; + var poseObject = poseTarget !== null ? poseTarget : camera; - } + // We want to manipulate poseObject by its position and quaternion components since users may rely on them. + poseObject.matrix.copy( standingMatrix ); + poseObject.matrix.decompose( poseObject.position, poseObject.quaternion, poseObject.scale ); - } + if ( pose.orientation !== null ) { + tempQuaternion.fromArray( pose.orientation ); + poseObject.quaternion.multiply( tempQuaternion ); - } else if ( object.isLine ) { + } - var lineWidth = material.linewidth; + if ( pose.position !== null ) { - if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material + tempQuaternion.setFromRotationMatrix( standingMatrix ); + tempPosition.fromArray( pose.position ); + tempPosition.applyQuaternion( tempQuaternion ); + poseObject.position.add( tempPosition ); - state.setLineWidth( lineWidth * getTargetPixelRatio() ); + } - if ( object.isLineSegments ) { + poseObject.updateMatrixWorld(); - renderer.setMode( _gl.LINES ); + if ( device.isPresenting === false ) return camera; - } else if ( object.isLineLoop ) { + // - renderer.setMode( _gl.LINE_LOOP ); + cameraL.near = camera.near; + cameraR.near = camera.near; - } else { + cameraL.far = camera.far; + cameraR.far = camera.far; - renderer.setMode( _gl.LINE_STRIP ); + cameraVR.matrixWorld.copy( camera.matrixWorld ); + cameraVR.matrixWorldInverse.copy( camera.matrixWorldInverse ); - } + cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix ); + cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix ); - } else if ( object.isPoints ) { + // TODO (mrdoob) Double check this code - renderer.setMode( _gl.POINTS ); + standingMatrixInverse.getInverse( standingMatrix ); - } + cameraL.matrixWorldInverse.multiply( standingMatrixInverse ); + cameraR.matrixWorldInverse.multiply( standingMatrixInverse ); - if ( geometry && geometry.isInstancedBufferGeometry ) { + var parent = poseObject.parent; - if ( geometry.maxInstancedCount > 0 ) { + if ( parent !== null ) { - renderer.renderInstances( geometry, drawStart, drawCount ); + matrixWorldInverse.getInverse( parent.matrixWorld ); - } + cameraL.matrixWorldInverse.multiply( matrixWorldInverse ); + cameraR.matrixWorldInverse.multiply( matrixWorldInverse ); - } else { + } - renderer.render( drawStart, drawCount ); + // envMap and Mirror needs camera.matrixWorld - } + cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse ); + cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse ); - }; + cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix ); + cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix ); - function setupVertexAttributes( material, program, geometry, startIndex ) { + // HACK (mrdoob) + // https://github.com/w3c/webvr/issues/203 - if ( geometry && geometry.isInstancedBufferGeometry ) { + cameraVR.projectionMatrix.copy( cameraL.projectionMatrix ); - if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) { + // - console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); - return; + var layers = device.getLayers(); - } + if ( layers.length ) { - } + var layer = layers[ 0 ]; - if ( startIndex === undefined ) startIndex = 0; + if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) { - state.initAttributes(); + cameraL.bounds.fromArray( layer.leftBounds ); - var geometryAttributes = geometry.attributes; + } - var programAttributes = program.getAttributes(); + if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) { - var materialDefaultAttributeValues = material.defaultAttributeValues; + cameraR.bounds.fromArray( layer.rightBounds ); - for ( var name in programAttributes ) { + } - var programAttribute = programAttributes[ name ]; + } - if ( programAttribute >= 0 ) { + return cameraVR; - var geometryAttribute = geometryAttributes[ name ]; + }; - if ( geometryAttribute !== undefined ) { + this.getStandingMatrix = function () { - var normalized = geometryAttribute.normalized; - var size = geometryAttribute.itemSize; + return standingMatrix; - var attribute = attributes.get( geometryAttribute ); + }; - var buffer = attribute.buffer; - var type = attribute.type; - var bytesPerElement = attribute.bytesPerElement; + this.submitFrame = function () { - if ( geometryAttribute.isInterleavedBufferAttribute ) { + if ( device && device.isPresenting ) device.submitFrame(); - var data = geometryAttribute.data; - var stride = data.stride; - var offset = geometryAttribute.offset; + }; - if ( data && data.isInstancedInterleavedBuffer ) { + this.dispose = function () { - state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute ); + if ( typeof window !== 'undefined' ) { - if ( geometry.maxInstancedCount === undefined ) { + window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange ); - geometry.maxInstancedCount = data.meshPerAttribute * data.count; + } - } + }; - } else { + } - state.enableAttribute( programAttribute ); + /** + * @author supereggbert / http://www.paulbrunt.co.uk/ + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * @author szimek / https://github.com/szimek/ + * @author tschw + */ - } + function WebGLRenderer( parameters ) { - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); - _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement ); + console.log( 'THREE.WebGLRenderer', REVISION ); - } else { + parameters = parameters || {}; - if ( geometryAttribute.isInstancedBufferAttribute ) { + var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), + _context = parameters.context !== undefined ? parameters.context : null, - state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute ); + _alpha = parameters.alpha !== undefined ? parameters.alpha : false, + _depth = parameters.depth !== undefined ? parameters.depth : true, + _stencil = parameters.stencil !== undefined ? parameters.stencil : true, + _antialias = parameters.antialias !== undefined ? parameters.antialias : false, + _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, + _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, + _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default'; - if ( geometry.maxInstancedCount === undefined ) { + var currentRenderList = null; + var currentRenderState = null; - geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + // public properties - } + this.domElement = _canvas; + this.context = null; - } else { + // clearing - state.enableAttribute( programAttribute ); + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; - } + // scene graph - _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); - _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement ); + this.sortObjects = true; - } + // user-defined clipping - } else if ( materialDefaultAttributeValues !== undefined ) { + this.clippingPlanes = []; + this.localClippingEnabled = false; - var value = materialDefaultAttributeValues[ name ]; + // physically based shading - if ( value !== undefined ) { + this.gammaFactor = 2.0; // for backwards compatibility + this.gammaInput = false; + this.gammaOutput = false; - switch ( value.length ) { + // physical lights - case 2: - _gl.vertexAttrib2fv( programAttribute, value ); - break; + this.physicallyCorrectLights = false; - case 3: - _gl.vertexAttrib3fv( programAttribute, value ); - break; + // tone mapping - case 4: - _gl.vertexAttrib4fv( programAttribute, value ); - break; + this.toneMapping = LinearToneMapping; + this.toneMappingExposure = 1.0; + this.toneMappingWhitePoint = 1.0; - default: - _gl.vertexAttrib1fv( programAttribute, value ); + // morphs - } + this.maxMorphTargets = 8; + this.maxMorphNormals = 4; - } + // internal properties - } + var _this = this, - } + _isContextLost = false, - } + // internal state cache - state.disableUnusedAttributes(); + _currentRenderTarget = null, + _currentFramebuffer = null, + _currentMaterialId = - 1, + _currentGeometryProgram = '', - } + _currentCamera = null, + _currentArrayCamera = null, - // Compile + _currentViewport = new Vector4(), + _currentScissor = new Vector4(), + _currentScissorTest = null, - this.compile = function ( scene, camera ) { + // - lights = []; + _usedTextureUnits = 0, - scene.traverse( function ( object ) { + // - if ( object.isLight ) { + _width = _canvas.width, + _height = _canvas.height, - lights.push( object ); + _pixelRatio = 1, - } + _viewport = new Vector4( 0, 0, _width, _height ), + _scissor = new Vector4( 0, 0, _width, _height ), + _scissorTest = false, - } ); + // frustum - setupLights( lights, camera ); + _frustum = new Frustum(), - scene.traverse( function ( object ) { + // clipping - if ( object.material ) { + _clipping = new WebGLClipping(), + _clippingEnabled = false, + _localClippingEnabled = false, - if ( Array.isArray( object.material ) ) { + // camera matrices cache - for ( var i = 0; i < object.material.length; i ++ ) { + _projScreenMatrix = new Matrix4(), - initMaterial( object.material[ i ], scene.fog, object ); + _vector3 = new Vector3(); - } + function getTargetPixelRatio() { - } else { + return _currentRenderTarget === null ? _pixelRatio : 1; - initMaterial( object.material, scene.fog, object ); + } - } + // initialize - } + var _gl; - } ); + try { - }; + var contextAttributes = { + alpha: _alpha, + depth: _depth, + stencil: _stencil, + antialias: _antialias, + premultipliedAlpha: _premultipliedAlpha, + preserveDrawingBuffer: _preserveDrawingBuffer, + powerPreference: _powerPreference + }; - // Rendering + // event listeners must be registered before WebGL context is created, see #12753 - this.animate = function ( callback ) { + _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); + _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); + + _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes ); + + if ( _gl === null ) { + + if ( _canvas.getContext( 'webgl' ) !== null ) { + + throw new Error( 'Error creating WebGL context with your selected attributes.' ); - function onFrame() { + } else { - callback(); + throw new Error( 'Error creating WebGL context.' ); - ( vr.getDevice() || window ).requestAnimationFrame( onFrame ); + } } - ( vr.getDevice() || window ).requestAnimationFrame( onFrame ); + // Some experimental-webgl implementations do not have getShaderPrecisionFormat - }; + if ( _gl.getShaderPrecisionFormat === undefined ) { - this.render = function ( scene, camera, renderTarget, forceClear ) { + _gl.getShaderPrecisionFormat = function () { - if ( ! ( camera && camera.isCamera ) ) { + return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; - console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); - return; + }; } - // reset caching for this frame + } catch ( error ) { - _currentGeometryProgram = ''; - _currentMaterialId = - 1; - _currentCamera = null; + console.error( 'THREE.WebGLRenderer: ' + error.message ); - // update scene graph + } - if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); + var extensions, capabilities, state, info; + var properties, textures, attributes, geometries, objects; + var programCache, renderLists, renderStates; - // update camera matrices and frustum + var background, morphtargets, bufferRenderer, indexedBufferRenderer; + var spriteRenderer; - if ( camera.parent === null ) camera.updateMatrixWorld(); + var utils; - if ( vr.enabled ) { + function initGLContext() { - camera = vr.getCamera( camera ); + extensions = new WebGLExtensions( _gl ); + extensions.get( 'WEBGL_depth_texture' ); + extensions.get( 'OES_texture_float' ); + extensions.get( 'OES_texture_float_linear' ); + extensions.get( 'OES_texture_half_float' ); + extensions.get( 'OES_texture_half_float_linear' ); + extensions.get( 'OES_standard_derivatives' ); + extensions.get( 'OES_element_index_uint' ); + extensions.get( 'ANGLE_instanced_arrays' ); - } + utils = new WebGLUtils( _gl, extensions ); - _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); - _frustum.setFromMatrix( _projScreenMatrix ); + capabilities = new WebGLCapabilities( _gl, extensions, parameters ); - lights.length = 0; - sprites.length = 0; - lensFlares.length = 0; + state = new WebGLState( _gl, extensions, utils ); + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); - _localClippingEnabled = this.localClippingEnabled; - _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); + info = new WebGLInfo( _gl ); + properties = new WebGLProperties(); + textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); + attributes = new WebGLAttributes( _gl ); + geometries = new WebGLGeometries( _gl, attributes, info ); + objects = new WebGLObjects( geometries, info ); + morphtargets = new WebGLMorphtargets( _gl ); + programCache = new WebGLPrograms( _this, extensions, capabilities ); + renderLists = new WebGLRenderLists(); + renderStates = new WebGLRenderStates(); - currentRenderList = renderLists.get( scene, camera ); - currentRenderList.init(); + background = new WebGLBackground( _this, state, geometries, _premultipliedAlpha ); - projectObject( scene, camera, _this.sortObjects ); + bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info ); + indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info ); - currentRenderList.finish(); + spriteRenderer = new WebGLSpriteRenderer( _this, _gl, state, textures, capabilities ); - if ( _this.sortObjects === true ) { + info.programs = programCache.programs; - currentRenderList.sort(); + _this.context = _gl; + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.state = state; + _this.info = info; - } + } - // + initGLContext(); - if ( _clippingEnabled ) _clipping.beginShadows(); + // vr - setupShadows( lights ); + var vr = new WebVRManager( _this ); - shadowMap.render( scene, camera ); + this.vr = vr; - setupLights( lights, camera ); + // shadow map - if ( _clippingEnabled ) _clipping.endShadows(); + var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize ); - // + this.shadowMap = shadowMap; - _infoRender.frame ++; - _infoRender.calls = 0; - _infoRender.vertices = 0; - _infoRender.faces = 0; - _infoRender.points = 0; + // API - if ( renderTarget === undefined ) { + this.getContext = function () { - renderTarget = null; + return _gl; - } + }; - this.setRenderTarget( renderTarget ); + this.getContextAttributes = function () { - // + return _gl.getContextAttributes(); - background.render( scene, camera, forceClear ); + }; - // render scene + this.forceContextLoss = function () { - var opaqueObjects = currentRenderList.opaque; - var transparentObjects = currentRenderList.transparent; + var extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.loseContext(); - if ( scene.overrideMaterial ) { + }; - var overrideMaterial = scene.overrideMaterial; + this.forceContextRestore = function () { - if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial ); - if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial ); + var extension = extensions.get( 'WEBGL_lose_context' ); + if ( extension ) extension.restoreContext(); - } else { + }; - // opaque pass (front-to-back order) + this.getPixelRatio = function () { - if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera ); + return _pixelRatio; - // transparent pass (back-to-front order) + }; - if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera ); + this.setPixelRatio = function ( value ) { - } + if ( value === undefined ) return; - // custom render plugins (post pass) + _pixelRatio = value; - spritePlugin.render( scene, camera ); - lensFlarePlugin.render( scene, camera, _currentViewport ); + this.setSize( _width, _height, false ); - // Generate mipmap if we're using any kind of mipmap filtering + }; - if ( renderTarget ) { + this.getSize = function () { - textures.updateRenderTargetMipmap( renderTarget ); + return { + width: _width, + height: _height + }; - } + }; - // Ensure depth buffer writing is enabled so it can be cleared on next render + this.setSize = function ( width, height, updateStyle ) { - state.buffers.depth.setTest( true ); - state.buffers.depth.setMask( true ); - state.buffers.color.setMask( true ); + var device = vr.getDevice(); - if ( camera.isArrayCamera ) { + if ( device && device.isPresenting ) { - _this.setScissorTest( false ); + console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); + return; } - if ( vr.enabled ) { + _width = width; + _height = height; - vr.submitFrame(); + _canvas.width = width * _pixelRatio; + _canvas.height = height * _pixelRatio; + + if ( updateStyle !== false ) { + + _canvas.style.width = width + 'px'; + _canvas.style.height = height + 'px'; } - // _gl.finish(); + this.setViewport( 0, 0, width, height ); }; - /* - // TODO Duplicated code (Frustum) + this.getDrawingBufferSize = function () { - var _sphere = new Sphere(); + return { + width: _width * _pixelRatio, + height: _height * _pixelRatio + }; - function isObjectViewable( object ) { + }; - var geometry = object.geometry; + this.setDrawingBufferSize = function ( width, height, pixelRatio ) { - if ( geometry.boundingSphere === null ) - geometry.computeBoundingSphere(); + _width = width; + _height = height; - _sphere.copy( geometry.boundingSphere ). - applyMatrix4( object.matrixWorld ); + _pixelRatio = pixelRatio; - return isSphereViewable( _sphere ); + _canvas.width = width * pixelRatio; + _canvas.height = height * pixelRatio; - } + this.setViewport( 0, 0, width, height ); - function isSpriteViewable( sprite ) { + }; - _sphere.center.set( 0, 0, 0 ); - _sphere.radius = 0.7071067811865476; - _sphere.applyMatrix4( sprite.matrixWorld ); + this.getCurrentViewport = function () { - return isSphereViewable( _sphere ); + return _currentViewport; - } + }; - function isSphereViewable( sphere ) { + this.setViewport = function ( x, y, width, height ) { - if ( ! _frustum.intersectsSphere( sphere ) ) return false; + _viewport.set( x, _height - y - height, width, height ); + state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) ); - var numPlanes = _clipping.numPlanes; + }; - if ( numPlanes === 0 ) return true; + this.setScissor = function ( x, y, width, height ) { - var planes = _this.clippingPlanes, + _scissor.set( x, _height - y - height, width, height ); + state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) ); - center = sphere.center, - negRad = - sphere.radius, - i = 0; + }; - do { + this.setScissorTest = function ( boolean ) { - // out when deeper than radius in the negative halfspace - if ( planes[ i ].distanceToPoint( center ) < negRad ) return false; + state.setScissorTest( _scissorTest = boolean ); - } while ( ++ i !== numPlanes ); + }; - return true; + // Clearing - } - */ + this.getClearColor = function () { - function projectObject( object, camera, sortObjects ) { + return background.getClearColor(); - if ( ! object.visible ) return; + }; - var visible = object.layers.test( camera.layers ); + this.setClearColor = function () { - if ( visible ) { + background.setClearColor.apply( background, arguments ); - if ( object.isLight ) { + }; - lights.push( object ); + this.getClearAlpha = function () { - } else if ( object.isSprite ) { + return background.getClearAlpha(); - if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { + }; - sprites.push( object ); + this.setClearAlpha = function () { - } + background.setClearAlpha.apply( background, arguments ); - } else if ( object.isLensFlare ) { + }; - lensFlares.push( object ); + this.clear = function ( color, depth, stencil ) { - } else if ( object.isImmediateRenderObject ) { + var bits = 0; - if ( sortObjects ) { + if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; + if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; + if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; - _vector3.setFromMatrixPosition( object.matrixWorld ) - .applyMatrix4( _projScreenMatrix ); + _gl.clear( bits ); - } + }; - currentRenderList.push( object, null, object.material, _vector3.z, null ); + this.clearColor = function () { - } else if ( object.isMesh || object.isLine || object.isPoints ) { + this.clear( true, false, false ); - if ( object.isSkinnedMesh ) { + }; - object.skeleton.update(); + this.clearDepth = function () { - } + this.clear( false, true, false ); - if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { + }; - if ( sortObjects ) { + this.clearStencil = function () { - _vector3.setFromMatrixPosition( object.matrixWorld ) - .applyMatrix4( _projScreenMatrix ); + this.clear( false, false, true ); - } + }; - var geometry = objects.update( object ); - var material = object.material; + this.clearTarget = function ( renderTarget, color, depth, stencil ) { - if ( Array.isArray( material ) ) { + this.setRenderTarget( renderTarget ); + this.clear( color, depth, stencil ); - var groups = geometry.groups; + }; - for ( var i = 0, l = groups.length; i < l; i ++ ) { + // - var group = groups[ i ]; - var groupMaterial = material[ group.materialIndex ]; + this.dispose = function () { - if ( groupMaterial && groupMaterial.visible ) { + _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); + _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); - currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group ); + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + objects.dispose(); - } + vr.dispose(); - } + stopAnimation(); - } else if ( material.visible ) { + }; - currentRenderList.push( object, geometry, material, _vector3.z, null ); + // Events - } + function onContextLost( event ) { - } + event.preventDefault(); - } + console.log( 'THREE.WebGLRenderer: Context Lost.' ); - } + _isContextLost = true; - var children = object.children; + } - for ( var i = 0, l = children.length; i < l; i ++ ) { + function onContextRestore( /* event */ ) { - projectObject( children[ i ], camera, sortObjects ); + console.log( 'THREE.WebGLRenderer: Context Restored.' ); - } + _isContextLost = false; + + initGLContext(); } - function renderObjects( renderList, scene, camera, overrideMaterial ) { + function onMaterialDispose( event ) { - for ( var i = 0, l = renderList.length; i < l; i ++ ) { + var material = event.target; - var renderItem = renderList[ i ]; + material.removeEventListener( 'dispose', onMaterialDispose ); - var object = renderItem.object; - var geometry = renderItem.geometry; - var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial; - var group = renderItem.group; + deallocateMaterial( material ); - if ( camera.isArrayCamera ) { + } - _currentArrayCamera = camera; + // Buffer deallocation - var cameras = camera.cameras; + function deallocateMaterial( material ) { - for ( var j = 0, jl = cameras.length; j < jl; j ++ ) { + releaseMaterialProgramReference( material ); - var camera2 = cameras[ j ]; + properties.remove( material ); - if ( object.layers.test( camera2.layers ) ) { + } - var bounds = camera2.bounds; - var x = bounds.x * _width; - var y = bounds.y * _height; - var width = bounds.z * _width; - var height = bounds.w * _height; + function releaseMaterialProgramReference( material ) { - _this.setViewport( x, y, width, height ); - _this.setScissor( x, y, width, height ); - _this.setScissorTest( true ); + var programInfo = properties.get( material ).program; - renderObject( object, scene, camera2, geometry, material, group ); + material.program = undefined; - } + if ( programInfo !== undefined ) { - } + programCache.releaseProgram( programInfo ); - } else { + } - _currentArrayCamera = null; + } - renderObject( object, scene, camera, geometry, material, group ); + // Buffer rendering - } + function renderObjectImmediate( object, program, material ) { - } + object.render( function ( object ) { - } + _this.renderBufferImmediate( object, program, material ); - function renderObject( object, scene, camera, geometry, material, group ) { + } ); - object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); - object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); + } - object.onBeforeRender( _this, scene, camera, geometry, material, group ); + this.renderBufferImmediate = function ( object, program, material ) { - if ( object.isImmediateRenderObject ) { + state.initAttributes(); - state.setMaterial( material ); + var buffers = properties.get( object ); - var program = setProgram( camera, scene.fog, material, object ); + if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer(); + if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer(); + if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer(); + if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer(); - _currentGeometryProgram = ''; + var programAttributes = program.getAttributes(); - renderObjectImmediate( object, program, material ); + if ( object.hasPositions ) { - } else { + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); - _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group ); + state.enableAttribute( programAttributes.position ); + _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 ); } - object.onAfterRender( _this, scene, camera, geometry, material, group ); - - } + if ( object.hasNormals ) { - function initMaterial( material, fog, object ) { + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal ); - var materialProperties = properties.get( material ); + if ( ! material.isMeshPhongMaterial && + ! material.isMeshStandardMaterial && + ! material.isMeshNormalMaterial && + material.flatShading === true ) { - var parameters = programCache.getParameters( - material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object ); + for ( var i = 0, l = object.count * 3; i < l; i += 9 ) { - var code = programCache.getProgramCode( material, parameters ); + var array = object.normalArray; - var program = materialProperties.program; - var programChange = true; + var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3; + var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3; + var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3; - if ( program === undefined ) { + array[ i + 0 ] = nx; + array[ i + 1 ] = ny; + array[ i + 2 ] = nz; - // new material - material.addEventListener( 'dispose', onMaterialDispose ); + array[ i + 3 ] = nx; + array[ i + 4 ] = ny; + array[ i + 5 ] = nz; - } else if ( program.code !== code ) { + array[ i + 6 ] = nx; + array[ i + 7 ] = ny; + array[ i + 8 ] = nz; - // changed glsl or parameters - releaseMaterialProgramReference( material ); + } - } else if ( parameters.shaderID !== undefined ) { + } - // same glsl and uniform list - return; + _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); - } else { + state.enableAttribute( programAttributes.normal ); - // only rebuild uniform list - programChange = false; + _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 ); } - if ( programChange ) { - - if ( parameters.shaderID ) { + if ( object.hasUvs && material.map ) { - var shader = ShaderLib[ parameters.shaderID ]; + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); - materialProperties.shader = { - name: material.type, - uniforms: UniformsUtils.clone( shader.uniforms ), - vertexShader: shader.vertexShader, - fragmentShader: shader.fragmentShader - }; + state.enableAttribute( programAttributes.uv ); - } else { + _gl.vertexAttribPointer( programAttributes.uv, 2, _gl.FLOAT, false, 0, 0 ); - materialProperties.shader = { - name: material.type, - uniforms: material.uniforms, - vertexShader: material.vertexShader, - fragmentShader: material.fragmentShader - }; + } - } + if ( object.hasColors && material.vertexColors !== NoColors ) { - material.onBeforeCompile( materialProperties.shader ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color ); + _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); - program = programCache.acquireProgram( material, materialProperties.shader, parameters, code ); + state.enableAttribute( programAttributes.color ); - materialProperties.program = program; - material.program = program; + _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 ); } - var programAttributes = program.getAttributes(); + state.disableUnusedAttributes(); - if ( material.morphTargets ) { + _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); - material.numSupportedMorphTargets = 0; + object.count = 0; - for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { + }; - if ( programAttributes[ 'morphTarget' + i ] >= 0 ) { + this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) { - material.numSupportedMorphTargets ++; + var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 ); - } + state.setMaterial( material, frontFaceCW ); - } + var program = setProgram( camera, fog, material, object ); + var geometryProgram = geometry.id + '_' + program.id + '_' + ( material.wireframe === true ); - } + var updateBuffers = false; - if ( material.morphNormals ) { + if ( geometryProgram !== _currentGeometryProgram ) { - material.numSupportedMorphNormals = 0; - - for ( var i = 0; i < _this.maxMorphNormals; i ++ ) { - - if ( programAttributes[ 'morphNormal' + i ] >= 0 ) { - - material.numSupportedMorphNormals ++; - - } - - } + _currentGeometryProgram = geometryProgram; + updateBuffers = true; } - var uniforms = materialProperties.shader.uniforms; + if ( object.morphTargetInfluences ) { - if ( ! material.isShaderMaterial && - ! material.isRawShaderMaterial || - material.clipping === true ) { + morphtargets.update( object, geometry, material, program ); - materialProperties.numClippingPlanes = _clipping.numPlanes; - materialProperties.numIntersection = _clipping.numIntersection; - uniforms.clippingPlanes = _clipping.uniform; + updateBuffers = true; } - materialProperties.fog = fog; - - // store the light setup it was created for - - materialProperties.lightsHash = _lights.hash; + // - if ( material.lights ) { + var index = geometry.index; + var position = geometry.attributes.position; + var rangeFactor = 1; - // wire up the material to this renderer's lighting state + if ( material.wireframe === true ) { - uniforms.ambientLightColor.value = _lights.ambient; - uniforms.directionalLights.value = _lights.directional; - uniforms.spotLights.value = _lights.spot; - uniforms.rectAreaLights.value = _lights.rectArea; - uniforms.pointLights.value = _lights.point; - uniforms.hemisphereLights.value = _lights.hemi; - - uniforms.directionalShadowMap.value = _lights.directionalShadowMap; - uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix; - uniforms.spotShadowMap.value = _lights.spotShadowMap; - uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix; - uniforms.pointShadowMap.value = _lights.pointShadowMap; - uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix; - // TODO (abelnation): add area lights shadow info to uniforms + index = geometries.getWireframeAttribute( geometry ); + rangeFactor = 2; } - var progUniforms = materialProperties.program.getUniforms(), - uniformsList = - WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); - - materialProperties.uniformsList = uniformsList; + var attribute; + var renderer = bufferRenderer; - } + if ( index !== null ) { - function setProgram( camera, fog, material, object ) { + attribute = attributes.get( index ); - _usedTextureUnits = 0; + renderer = indexedBufferRenderer; + renderer.setIndex( attribute ); - var materialProperties = properties.get( material ); + } - if ( _clippingEnabled ) { + if ( updateBuffers ) { - if ( _localClippingEnabled || camera !== _currentCamera ) { + setupVertexAttributes( material, program, geometry ); - var useCache = - camera === _currentCamera && - material.id === _currentMaterialId; + if ( index !== null ) { - // we might want to call this function with some ClippingGroup - // object instead of the material, once it becomes feasible - // (#8465, #8379) - _clipping.setState( - material.clippingPlanes, material.clipIntersection, material.clipShadows, - camera, materialProperties, useCache ); + _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer ); } } - if ( material.needsUpdate === false ) { + // - if ( materialProperties.program === undefined ) { + var dataCount = Infinity; - material.needsUpdate = true; + if ( index !== null ) { - } else if ( material.fog && materialProperties.fog !== fog ) { + dataCount = index.count; - material.needsUpdate = true; + } else if ( position !== undefined ) { - } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) { + dataCount = position.count; - material.needsUpdate = true; + } - } else if ( materialProperties.numClippingPlanes !== undefined && - ( materialProperties.numClippingPlanes !== _clipping.numPlanes || - materialProperties.numIntersection !== _clipping.numIntersection ) ) { + var rangeStart = geometry.drawRange.start * rangeFactor; + var rangeCount = geometry.drawRange.count * rangeFactor; - material.needsUpdate = true; + var groupStart = group !== null ? group.start * rangeFactor : 0; + var groupCount = group !== null ? group.count * rangeFactor : Infinity; - } + var drawStart = Math.max( rangeStart, groupStart ); + var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; - } + var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); - if ( material.needsUpdate ) { + if ( drawCount === 0 ) return; - initMaterial( material, fog, object ); - material.needsUpdate = false; + // - } + if ( object.isMesh ) { - var refreshProgram = false; - var refreshMaterial = false; - var refreshLights = false; + if ( material.wireframe === true ) { - var program = materialProperties.program, - p_uniforms = program.getUniforms(), - m_uniforms = materialProperties.shader.uniforms; + state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); + renderer.setMode( _gl.LINES ); - if ( program.id !== _currentProgram ) { + } else { - _gl.useProgram( program.program ); - _currentProgram = program.id; + switch ( object.drawMode ) { - refreshProgram = true; - refreshMaterial = true; - refreshLights = true; + case TrianglesDrawMode: + renderer.setMode( _gl.TRIANGLES ); + break; - } + case TriangleStripDrawMode: + renderer.setMode( _gl.TRIANGLE_STRIP ); + break; - if ( material.id !== _currentMaterialId ) { + case TriangleFanDrawMode: + renderer.setMode( _gl.TRIANGLE_FAN ); + break; - _currentMaterialId = material.id; + } - refreshMaterial = true; + } - } - if ( refreshProgram || camera !== _currentCamera ) { + } else if ( object.isLine ) { - p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); + var lineWidth = material.linewidth; - if ( capabilities.logarithmicDepthBuffer ) { + if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material - p_uniforms.setValue( _gl, 'logDepthBufFC', - 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); + state.setLineWidth( lineWidth * getTargetPixelRatio() ); - } + if ( object.isLineSegments ) { - // Avoid unneeded uniform updates per ArrayCamera's sub-camera + renderer.setMode( _gl.LINES ); - if ( _currentCamera !== ( _currentArrayCamera || camera ) ) { + } else if ( object.isLineLoop ) { - _currentCamera = ( _currentArrayCamera || camera ); + renderer.setMode( _gl.LINE_LOOP ); - // lighting uniforms depend on the camera so enforce an update - // now, in case this material supports lights - or later, when - // the next material that does gets activated: + } else { - refreshMaterial = true; // set to true on material change - refreshLights = true; // remains set until update done + renderer.setMode( _gl.LINE_STRIP ); } - // load material specific uniforms - // (shader material also gets them for the sake of genericity) + } else if ( object.isPoints ) { - if ( material.isShaderMaterial || - material.isMeshPhongMaterial || - material.isMeshStandardMaterial || - material.envMap ) { + renderer.setMode( _gl.POINTS ); - var uCamPos = p_uniforms.map.cameraPosition; + } - if ( uCamPos !== undefined ) { + if ( geometry && geometry.isInstancedBufferGeometry ) { - uCamPos.setValue( _gl, - _vector3.setFromMatrixPosition( camera.matrixWorld ) ); + if ( geometry.maxInstancedCount > 0 ) { - } + renderer.renderInstances( geometry, drawStart, drawCount ); } - if ( material.isMeshPhongMaterial || - material.isMeshLambertMaterial || - material.isMeshBasicMaterial || - material.isMeshStandardMaterial || - material.isShaderMaterial || - material.skinning ) { - - p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); + } else { - } + renderer.render( drawStart, drawCount ); } - // skinning uniforms must be set even if material didn't change - // auto-setting of texture unit for bone texture must go before other textures - // not sure why, but otherwise weird things happen - - if ( material.skinning ) { + }; - p_uniforms.setOptional( _gl, object, 'bindMatrix' ); - p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); + function setupVertexAttributes( material, program, geometry, startIndex ) { - var skeleton = object.skeleton; + if ( geometry && geometry.isInstancedBufferGeometry ) { - if ( skeleton ) { + if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) { - var bones = skeleton.bones; + console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); + return; - if ( capabilities.floatVertexTextures ) { + } - if ( skeleton.boneTexture === undefined ) { + } - // layout (1 matrix = 4 pixels) - // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) - // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) - // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) - // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) - // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) + if ( startIndex === undefined ) startIndex = 0; + state.initAttributes(); - var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix - size = _Math.nextPowerOfTwo( Math.ceil( size ) ); - size = Math.max( size, 4 ); + var geometryAttributes = geometry.attributes; - var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel - boneMatrices.set( skeleton.boneMatrices ); // copy current values + var programAttributes = program.getAttributes(); - var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType ); + var materialDefaultAttributeValues = material.defaultAttributeValues; - skeleton.boneMatrices = boneMatrices; - skeleton.boneTexture = boneTexture; - skeleton.boneTextureSize = size; + for ( var name in programAttributes ) { - } + var programAttribute = programAttributes[ name ]; - p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture ); - p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize ); + if ( programAttribute >= 0 ) { - } else { + var geometryAttribute = geometryAttributes[ name ]; - p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); + if ( geometryAttribute !== undefined ) { - } + var normalized = geometryAttribute.normalized; + var size = geometryAttribute.itemSize; - } + var attribute = attributes.get( geometryAttribute ); - } + // TODO Attribute may not be available on context restore - if ( refreshMaterial ) { + if ( attribute === undefined ) continue; - p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); - p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint ); + var buffer = attribute.buffer; + var type = attribute.type; + var bytesPerElement = attribute.bytesPerElement; - if ( material.lights ) { + if ( geometryAttribute.isInterleavedBufferAttribute ) { - // the current material requires lighting info + var data = geometryAttribute.data; + var stride = data.stride; + var offset = geometryAttribute.offset; - // note: all lighting uniforms are always set correctly - // they simply reference the renderer's state for their - // values - // - // use the current material's .needsUpdate flags to set - // the GL state when required + if ( data && data.isInstancedInterleavedBuffer ) { - markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); + state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute ); - } + if ( geometry.maxInstancedCount === undefined ) { - // refresh uniforms common to several materials + geometry.maxInstancedCount = data.meshPerAttribute * data.count; - if ( fog && material.fog ) { + } - refreshUniformsFog( m_uniforms, fog ); + } else { - } + state.enableAttribute( programAttribute ); - if ( material.isMeshBasicMaterial || - material.isMeshLambertMaterial || - material.isMeshPhongMaterial || - material.isMeshStandardMaterial || - material.isMeshNormalMaterial || - material.isMeshDepthMaterial ) { + } - refreshUniformsCommon( m_uniforms, material ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); + _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement ); - } + } else { - // refresh single material specific uniforms + if ( geometryAttribute.isInstancedBufferAttribute ) { - if ( material.isLineBasicMaterial ) { + state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute ); - refreshUniformsLine( m_uniforms, material ); + if ( geometry.maxInstancedCount === undefined ) { - } else if ( material.isLineDashedMaterial ) { + geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; - refreshUniformsLine( m_uniforms, material ); - refreshUniformsDash( m_uniforms, material ); + } - } else if ( material.isPointsMaterial ) { + } else { - refreshUniformsPoints( m_uniforms, material ); + state.enableAttribute( programAttribute ); - } else if ( material.isMeshLambertMaterial ) { + } - refreshUniformsLambert( m_uniforms, material ); + _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer ); + _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement ); - } else if ( material.isMeshToonMaterial ) { + } - refreshUniformsToon( m_uniforms, material ); + } else if ( materialDefaultAttributeValues !== undefined ) { - } else if ( material.isMeshPhongMaterial ) { + var value = materialDefaultAttributeValues[ name ]; - refreshUniformsPhong( m_uniforms, material ); + if ( value !== undefined ) { - } else if ( material.isMeshPhysicalMaterial ) { + switch ( value.length ) { - refreshUniformsPhysical( m_uniforms, material ); + case 2: + _gl.vertexAttrib2fv( programAttribute, value ); + break; - } else if ( material.isMeshStandardMaterial ) { + case 3: + _gl.vertexAttrib3fv( programAttribute, value ); + break; - refreshUniformsStandard( m_uniforms, material ); + case 4: + _gl.vertexAttrib4fv( programAttribute, value ); + break; - } else if ( material.isMeshDepthMaterial ) { + default: + _gl.vertexAttrib1fv( programAttribute, value ); - if ( material.displacementMap ) { + } - m_uniforms.displacementMap.value = material.displacementMap; - m_uniforms.displacementScale.value = material.displacementScale; - m_uniforms.displacementBias.value = material.displacementBias; + } } - } else if ( material.isMeshNormalMaterial ) { - - refreshUniformsNormal( m_uniforms, material ); - } - // RectAreaLight Texture - // TODO (mrdoob): Find a nicer implementation + } - if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = UniformsLib.LTC_MAT_TEXTURE; - if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = UniformsLib.LTC_MAG_TEXTURE; + state.disableUnusedAttributes(); - WebGLUniforms.upload( - _gl, materialProperties.uniformsList, m_uniforms, _this ); + } - } + // Compile + this.compile = function ( scene, camera ) { - // common matrices + currentRenderState = renderStates.get( scene, camera ); + currentRenderState.init(); - p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); - p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); - p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); + scene.traverse( function ( object ) { - return program; + if ( object.isLight ) { - } + currentRenderState.pushLight( object ); - // Uniforms (refresh uniforms objects) + if ( object.castShadow ) { - function refreshUniformsCommon( uniforms, material ) { + currentRenderState.pushShadow( object ); - uniforms.opacity.value = material.opacity; + } - uniforms.diffuse.value = material.color; + } - if ( material.emissive ) { + } ); - uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); + currentRenderState.setupLights( camera ); - } + scene.traverse( function ( object ) { - uniforms.map.value = material.map; - uniforms.specularMap.value = material.specularMap; - uniforms.alphaMap.value = material.alphaMap; + if ( object.material ) { - if ( material.lightMap ) { + if ( Array.isArray( object.material ) ) { - uniforms.lightMap.value = material.lightMap; - uniforms.lightMapIntensity.value = material.lightMapIntensity; + for ( var i = 0; i < object.material.length; i ++ ) { - } + initMaterial( object.material[ i ], scene.fog, object ); - if ( material.aoMap ) { + } - uniforms.aoMap.value = material.aoMap; - uniforms.aoMapIntensity.value = material.aoMapIntensity; + } else { - } + initMaterial( object.material, scene.fog, object ); - // uv repeat and offset setting priorities - // 1. color map - // 2. specular map - // 3. normal map - // 4. bump map - // 5. alpha map - // 6. emissive map + } - var uvScaleMap; + } - if ( material.map ) { + } ); - uvScaleMap = material.map; + }; - } else if ( material.specularMap ) { + // Animation Loop - uvScaleMap = material.specularMap; + var isAnimating = false; + var onAnimationFrame = null; - } else if ( material.displacementMap ) { + function startAnimation() { - uvScaleMap = material.displacementMap; + if ( isAnimating ) return; - } else if ( material.normalMap ) { + requestAnimationLoopFrame(); - uvScaleMap = material.normalMap; + isAnimating = true; - } else if ( material.bumpMap ) { + } - uvScaleMap = material.bumpMap; + function stopAnimation() { - } else if ( material.roughnessMap ) { + isAnimating = false; - uvScaleMap = material.roughnessMap; + } - } else if ( material.metalnessMap ) { + function requestAnimationLoopFrame() { - uvScaleMap = material.metalnessMap; + var device = vr.getDevice(); - } else if ( material.alphaMap ) { + if ( device && device.isPresenting ) { - uvScaleMap = material.alphaMap; + device.requestAnimationFrame( animationLoop ); - } else if ( material.emissiveMap ) { + } else { - uvScaleMap = material.emissiveMap; + window.requestAnimationFrame( animationLoop ); } - if ( uvScaleMap !== undefined ) { + } - // backwards compatibility - if ( uvScaleMap.isWebGLRenderTarget ) { + function animationLoop( time ) { - uvScaleMap = uvScaleMap.texture; + if ( isAnimating === false ) return; - } + onAnimationFrame( time ); - var offset = uvScaleMap.offset; - var repeat = uvScaleMap.repeat; + requestAnimationLoopFrame(); - uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); + } - } + this.animate = function ( callback ) { - uniforms.envMap.value = material.envMap; + onAnimationFrame = callback; + onAnimationFrame !== null ? startAnimation() : stopAnimation(); - // don't flip CubeTexture envMaps, flip everything else: - // WebGLRenderTargetCube will be flipped for backwards compatibility - // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture - // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future - uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1; + }; - uniforms.reflectivity.value = material.reflectivity; - uniforms.refractionRatio.value = material.refractionRatio; + // Rendering - } + this.render = function ( scene, camera, renderTarget, forceClear ) { - function refreshUniformsLine( uniforms, material ) { + if ( ! ( camera && camera.isCamera ) ) { - uniforms.diffuse.value = material.color; - uniforms.opacity.value = material.opacity; + console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); + return; - } + } - function refreshUniformsDash( uniforms, material ) { + if ( _isContextLost ) return; - uniforms.dashSize.value = material.dashSize; - uniforms.totalSize.value = material.dashSize + material.gapSize; - uniforms.scale.value = material.scale; + // reset caching for this frame - } + _currentGeometryProgram = ''; + _currentMaterialId = - 1; + _currentCamera = null; - function refreshUniformsPoints( uniforms, material ) { + // update scene graph - uniforms.diffuse.value = material.color; - uniforms.opacity.value = material.opacity; - uniforms.size.value = material.size * _pixelRatio; - uniforms.scale.value = _height * 0.5; + if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); - uniforms.map.value = material.map; + // update camera matrices and frustum - if ( material.map !== null ) { + if ( camera.parent === null ) camera.updateMatrixWorld(); - var offset = material.map.offset; - var repeat = material.map.repeat; + if ( vr.enabled ) { - uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); + camera = vr.getCamera( camera ); } - } + // - function refreshUniformsFog( uniforms, fog ) { + currentRenderState = renderStates.get( scene, camera ); + currentRenderState.init(); - uniforms.fogColor.value = fog.color; + scene.onBeforeRender( _this, scene, camera, renderTarget ); - if ( fog.isFog ) { + _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); + _frustum.setFromMatrix( _projScreenMatrix ); - uniforms.fogNear.value = fog.near; - uniforms.fogFar.value = fog.far; + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); - } else if ( fog.isFogExp2 ) { + currentRenderList = renderLists.get( scene, camera ); + currentRenderList.init(); - uniforms.fogDensity.value = fog.density; + projectObject( scene, camera, _this.sortObjects ); + + if ( _this.sortObjects === true ) { + + currentRenderList.sort(); } - } + // - function refreshUniformsLambert( uniforms, material ) { + if ( _clippingEnabled ) _clipping.beginShadows(); - if ( material.emissiveMap ) { + var shadowsArray = currentRenderState.state.shadowsArray; - uniforms.emissiveMap.value = material.emissiveMap; + shadowMap.render( shadowsArray, scene, camera ); - } + currentRenderState.setupLights( camera ); - } + if ( _clippingEnabled ) _clipping.endShadows(); - function refreshUniformsPhong( uniforms, material ) { + // - uniforms.specular.value = material.specular; - uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) + if ( this.info.autoReset ) this.info.reset(); - if ( material.emissiveMap ) { + if ( renderTarget === undefined ) { - uniforms.emissiveMap.value = material.emissiveMap; + renderTarget = null; } - if ( material.bumpMap ) { - - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; + this.setRenderTarget( renderTarget ); - } + // - if ( material.normalMap ) { + background.render( currentRenderList, scene, camera, forceClear ); - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); + // render scene - } + var opaqueObjects = currentRenderList.opaque; + var transparentObjects = currentRenderList.transparent; - if ( material.displacementMap ) { + if ( scene.overrideMaterial ) { - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + var overrideMaterial = scene.overrideMaterial; - } + if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial ); + if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial ); - } + } else { - function refreshUniformsToon( uniforms, material ) { + // opaque pass (front-to-back order) - refreshUniformsPhong( uniforms, material ); + if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera ); - if ( material.gradientMap ) { + // transparent pass (back-to-front order) - uniforms.gradientMap.value = material.gradientMap; + if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera ); } - } + // custom renderers - function refreshUniformsStandard( uniforms, material ) { + var spritesArray = currentRenderState.state.spritesArray; - uniforms.roughness.value = material.roughness; - uniforms.metalness.value = material.metalness; + spriteRenderer.render( spritesArray, scene, camera ); - if ( material.roughnessMap ) { + // Generate mipmap if we're using any kind of mipmap filtering - uniforms.roughnessMap.value = material.roughnessMap; + if ( renderTarget ) { - } - - if ( material.metalnessMap ) { - - uniforms.metalnessMap.value = material.metalnessMap; + textures.updateRenderTargetMipmap( renderTarget ); } - if ( material.emissiveMap ) { + // Ensure depth buffer writing is enabled so it can be cleared on next render - uniforms.emissiveMap.value = material.emissiveMap; + state.buffers.depth.setTest( true ); + state.buffers.depth.setMask( true ); + state.buffers.color.setMask( true ); - } + state.setPolygonOffset( false ); - if ( material.bumpMap ) { + scene.onAfterRender( _this, scene, camera ); - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; + if ( vr.enabled ) { + + vr.submitFrame(); } - if ( material.normalMap ) { + // _gl.finish(); - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); + currentRenderList = null; + currentRenderState = null; - } + }; - if ( material.displacementMap ) { + /* + // TODO Duplicated code (Frustum) - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + var _sphere = new Sphere(); - } + function isObjectViewable( object ) { - if ( material.envMap ) { + var geometry = object.geometry; - //uniforms.envMap.value = material.envMap; // part of uniforms common - uniforms.envMapIntensity.value = material.envMapIntensity; + if ( geometry.boundingSphere === null ) + geometry.computeBoundingSphere(); - } + _sphere.copy( geometry.boundingSphere ). + applyMatrix4( object.matrixWorld ); + + return isSphereViewable( _sphere ); } - function refreshUniformsPhysical( uniforms, material ) { + function isSpriteViewable( sprite ) { - uniforms.clearCoat.value = material.clearCoat; - uniforms.clearCoatRoughness.value = material.clearCoatRoughness; + _sphere.center.set( 0, 0, 0 ); + _sphere.radius = 0.7071067811865476; + _sphere.applyMatrix4( sprite.matrixWorld ); - refreshUniformsStandard( uniforms, material ); + return isSphereViewable( _sphere ); } - function refreshUniformsNormal( uniforms, material ) { + function isSphereViewable( sphere ) { - if ( material.bumpMap ) { + if ( ! _frustum.intersectsSphere( sphere ) ) return false; - uniforms.bumpMap.value = material.bumpMap; - uniforms.bumpScale.value = material.bumpScale; + var numPlanes = _clipping.numPlanes; - } + if ( numPlanes === 0 ) return true; - if ( material.normalMap ) { + var planes = _this.clippingPlanes, - uniforms.normalMap.value = material.normalMap; - uniforms.normalScale.value.copy( material.normalScale ); + center = sphere.center, + negRad = - sphere.radius, + i = 0; - } + do { - if ( material.displacementMap ) { + // out when deeper than radius in the negative halfspace + if ( planes[ i ].distanceToPoint( center ) < negRad ) return false; - uniforms.displacementMap.value = material.displacementMap; - uniforms.displacementScale.value = material.displacementScale; - uniforms.displacementBias.value = material.displacementBias; + } while ( ++ i !== numPlanes ); - } + return true; } + */ - // If uniforms are marked as clean, they don't need to be loaded to the GPU. - - function markUniformsLightsNeedsUpdate( uniforms, value ) { + function projectObject( object, camera, sortObjects ) { - uniforms.ambientLightColor.needsUpdate = value; + if ( object.visible === false ) return; - uniforms.directionalLights.needsUpdate = value; - uniforms.pointLights.needsUpdate = value; - uniforms.spotLights.needsUpdate = value; - uniforms.rectAreaLights.needsUpdate = value; - uniforms.hemisphereLights.needsUpdate = value; + var visible = object.layers.test( camera.layers ); - } + if ( visible ) { - // Lighting + if ( object.isLight ) { - function setupShadows( lights ) { + currentRenderState.pushLight( object ); - var lightShadowsLength = 0; + if ( object.castShadow ) { - for ( var i = 0, l = lights.length; i < l; i ++ ) { + currentRenderState.pushShadow( object ); - var light = lights[ i ]; + } - if ( light.castShadow ) { + } else if ( object.isSprite ) { - _lights.shadows[ lightShadowsLength ] = light; - lightShadowsLength ++; + if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { - } + currentRenderState.pushSprite( object ); - } + } - _lights.shadows.length = lightShadowsLength; + } else if ( object.isImmediateRenderObject ) { - } + if ( sortObjects ) { - function setupLights( lights, camera ) { + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); - var l, ll, light, shadow, - r = 0, g = 0, b = 0, - color, - intensity, - distance, - shadowMap, + } - viewMatrix = camera.matrixWorldInverse, + currentRenderList.push( object, null, object.material, _vector3.z, null ); - directionalLength = 0, - pointLength = 0, - spotLength = 0, - rectAreaLength = 0, - hemiLength = 0; + } else if ( object.isMesh || object.isLine || object.isPoints ) { - for ( l = 0, ll = lights.length; l < ll; l ++ ) { + if ( object.isSkinnedMesh ) { - light = lights[ l ]; + object.skeleton.update(); - color = light.color; - intensity = light.intensity; - distance = light.distance; + } - shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; + if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { - if ( light.isAmbientLight ) { + if ( sortObjects ) { - r += color.r * intensity; - g += color.g * intensity; - b += color.b * intensity; + _vector3.setFromMatrixPosition( object.matrixWorld ) + .applyMatrix4( _projScreenMatrix ); - } else if ( light.isDirectionalLight ) { + } - var uniforms = lightCache.get( light ); + var geometry = objects.update( object ); + var material = object.material; - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - _vector3.setFromMatrixPosition( light.target.matrixWorld ); - uniforms.direction.sub( _vector3 ); - uniforms.direction.transformDirection( viewMatrix ); + if ( Array.isArray( material ) ) { - uniforms.shadow = light.castShadow; + var groups = geometry.groups; - if ( light.castShadow ) { + for ( var i = 0, l = groups.length; i < l; i ++ ) { - shadow = light.shadow; + var group = groups[ i ]; + var groupMaterial = material[ group.materialIndex ]; - uniforms.shadowBias = shadow.bias; - uniforms.shadowRadius = shadow.radius; - uniforms.shadowMapSize = shadow.mapSize; + if ( groupMaterial && groupMaterial.visible ) { - } + currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group ); - _lights.directionalShadowMap[ directionalLength ] = shadowMap; - _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; - _lights.directional[ directionalLength ] = uniforms; + } - directionalLength ++; + } - } else if ( light.isSpotLight ) { + } else if ( material.visible ) { - var uniforms = lightCache.get( light ); + currentRenderList.push( object, geometry, material, _vector3.z, null ); - uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.position.applyMatrix4( viewMatrix ); + } - uniforms.color.copy( color ).multiplyScalar( intensity ); - uniforms.distance = distance; + } - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - _vector3.setFromMatrixPosition( light.target.matrixWorld ); - uniforms.direction.sub( _vector3 ); - uniforms.direction.transformDirection( viewMatrix ); + } - uniforms.coneCos = Math.cos( light.angle ); - uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); - uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; + } - uniforms.shadow = light.castShadow; + var children = object.children; - if ( light.castShadow ) { + for ( var i = 0, l = children.length; i < l; i ++ ) { - shadow = light.shadow; + projectObject( children[ i ], camera, sortObjects ); - uniforms.shadowBias = shadow.bias; - uniforms.shadowRadius = shadow.radius; - uniforms.shadowMapSize = shadow.mapSize; + } - } + } - _lights.spotShadowMap[ spotLength ] = shadowMap; - _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix; - _lights.spot[ spotLength ] = uniforms; + function renderObjects( renderList, scene, camera, overrideMaterial ) { - spotLength ++; + for ( var i = 0, l = renderList.length; i < l; i ++ ) { - } else if ( light.isRectAreaLight ) { + var renderItem = renderList[ i ]; - var uniforms = lightCache.get( light ); + var object = renderItem.object; + var geometry = renderItem.geometry; + var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial; + var group = renderItem.group; - // (a) intensity controls irradiance of entire light - uniforms.color - .copy( color ) - .multiplyScalar( intensity / ( light.width * light.height ) ); + if ( camera.isArrayCamera ) { - // (b) intensity controls the radiance per light area - // uniforms.color.copy( color ).multiplyScalar( intensity ); + _currentArrayCamera = camera; - uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.position.applyMatrix4( viewMatrix ); + var cameras = camera.cameras; - // extract local rotation of light to derive width/height half vectors - _matrix42.identity(); - _matrix4.copy( light.matrixWorld ); - _matrix4.premultiply( viewMatrix ); - _matrix42.extractRotation( _matrix4 ); + for ( var j = 0, jl = cameras.length; j < jl; j ++ ) { - uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); - uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); + var camera2 = cameras[ j ]; - uniforms.halfWidth.applyMatrix4( _matrix42 ); - uniforms.halfHeight.applyMatrix4( _matrix42 ); + if ( object.layers.test( camera2.layers ) ) { - // TODO (abelnation): RectAreaLight distance? - // uniforms.distance = distance; + var bounds = camera2.bounds; - _lights.rectArea[ rectAreaLength ] = uniforms; + var x = bounds.x * _width; + var y = bounds.y * _height; + var width = bounds.z * _width; + var height = bounds.w * _height; - rectAreaLength ++; + state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) ); - } else if ( light.isPointLight ) { + renderObject( object, scene, camera2, geometry, material, group ); - var uniforms = lightCache.get( light ); + } - uniforms.position.setFromMatrixPosition( light.matrixWorld ); - uniforms.position.applyMatrix4( viewMatrix ); + } - uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); - uniforms.distance = light.distance; - uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay; + } else { - uniforms.shadow = light.castShadow; + _currentArrayCamera = null; - if ( light.castShadow ) { + renderObject( object, scene, camera, geometry, material, group ); - shadow = light.shadow; + } - uniforms.shadowBias = shadow.bias; - uniforms.shadowRadius = shadow.radius; - uniforms.shadowMapSize = shadow.mapSize; + } - } + } - _lights.pointShadowMap[ pointLength ] = shadowMap; - _lights.pointShadowMatrix[ pointLength ] = light.shadow.matrix; - _lights.point[ pointLength ] = uniforms; + function renderObject( object, scene, camera, geometry, material, group ) { - pointLength ++; + object.onBeforeRender( _this, scene, camera, geometry, material, group ); + currentRenderState = renderStates.get( scene, _currentArrayCamera || camera ); - } else if ( light.isHemisphereLight ) { + object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); + object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); - var uniforms = lightCache.get( light ); + if ( object.isImmediateRenderObject ) { - uniforms.direction.setFromMatrixPosition( light.matrixWorld ); - uniforms.direction.transformDirection( viewMatrix ); - uniforms.direction.normalize(); + var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 ); - uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); - uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); + state.setMaterial( material, frontFaceCW ); - _lights.hemi[ hemiLength ] = uniforms; + var program = setProgram( camera, scene.fog, material, object ); - hemiLength ++; + _currentGeometryProgram = ''; - } + renderObjectImmediate( object, program, material ); - } + } else { - _lights.ambient[ 0 ] = r; - _lights.ambient[ 1 ] = g; - _lights.ambient[ 2 ] = b; + _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group ); - _lights.directional.length = directionalLength; - _lights.spot.length = spotLength; - _lights.rectArea.length = rectAreaLength; - _lights.point.length = pointLength; - _lights.hemi.length = hemiLength; + } - // TODO (sam-g-steel) why aren't we using join - _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length; + object.onAfterRender( _this, scene, camera, geometry, material, group ); + currentRenderState = renderStates.get( scene, _currentArrayCamera || camera ); } - // GL state setting + function initMaterial( material, fog, object ) { - this.setFaceCulling = function ( cullFace, frontFaceDirection ) { + var materialProperties = properties.get( material ); - state.setCullFace( cullFace ); - state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW ); + var lights = currentRenderState.state.lights; + var shadowsArray = currentRenderState.state.shadowsArray; - }; + var parameters = programCache.getParameters( + material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object ); - // Textures + var code = programCache.getProgramCode( material, parameters ); - function allocTextureUnit() { + var program = materialProperties.program; + var programChange = true; - var textureUnit = _usedTextureUnits; + if ( program === undefined ) { - if ( textureUnit >= capabilities.maxTextures ) { + // new material + material.addEventListener( 'dispose', onMaterialDispose ); - console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures ); + } else if ( program.code !== code ) { - } + // changed glsl or parameters + releaseMaterialProgramReference( material ); - _usedTextureUnits += 1; + } else if ( materialProperties.lightsHash !== lights.state.hash ) { - return textureUnit; + properties.update( material, 'lightsHash', lights.state.hash ); + programChange = false; - } + } else if ( parameters.shaderID !== undefined ) { - this.allocTextureUnit = allocTextureUnit; + // same glsl and uniform list + return; - // this.setTexture2D = setTexture2D; - this.setTexture2D = ( function () { + } else { - var warned = false; + // only rebuild uniform list + programChange = false; - // backwards compatibility: peel texture.texture - return function setTexture2D( texture, slot ) { + } - if ( texture && texture.isWebGLRenderTarget ) { + if ( programChange ) { - if ( ! warned ) { + if ( parameters.shaderID ) { - console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." ); - warned = true; + var shader = ShaderLib[ parameters.shaderID ]; - } + materialProperties.shader = { + name: material.type, + uniforms: UniformsUtils.clone( shader.uniforms ), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader + }; - texture = texture.texture; + } else { + + materialProperties.shader = { + name: material.type, + uniforms: material.uniforms, + vertexShader: material.vertexShader, + fragmentShader: material.fragmentShader + }; } - textures.setTexture2D( texture, slot ); + material.onBeforeCompile( materialProperties.shader, _this ); - }; + program = programCache.acquireProgram( material, materialProperties.shader, parameters, code ); - }() ); + materialProperties.program = program; + material.program = program; - this.setTexture = ( function () { + } - var warned = false; + var programAttributes = program.getAttributes(); - return function setTexture( texture, slot ) { + if ( material.morphTargets ) { - if ( ! warned ) { + material.numSupportedMorphTargets = 0; - console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." ); - warned = true; + for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { - } + if ( programAttributes[ 'morphTarget' + i ] >= 0 ) { - textures.setTexture2D( texture, slot ); + material.numSupportedMorphTargets ++; - }; + } - }() ); + } - this.setTextureCube = ( function () { + } - var warned = false; + if ( material.morphNormals ) { - return function setTextureCube( texture, slot ) { + material.numSupportedMorphNormals = 0; - // backwards compatibility: peel texture.texture - if ( texture && texture.isWebGLRenderTargetCube ) { + for ( var i = 0; i < _this.maxMorphNormals; i ++ ) { - if ( ! warned ) { + if ( programAttributes[ 'morphNormal' + i ] >= 0 ) { - console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); - warned = true; + material.numSupportedMorphNormals ++; } - texture = texture.texture; - } - // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture - // TODO: unify these code paths - if ( ( texture && texture.isCubeTexture ) || - ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { - - // CompressedTexture can have Array in image :/ - - // this function alone should take care of cube textures - textures.setTextureCube( texture, slot ); + } - } else { + var uniforms = materialProperties.shader.uniforms; - // assumed: texture property of THREE.WebGLRenderTargetCube + if ( ! material.isShaderMaterial && + ! material.isRawShaderMaterial || + material.clipping === true ) { - textures.setTextureCubeDynamic( texture, slot ); + materialProperties.numClippingPlanes = _clipping.numPlanes; + materialProperties.numIntersection = _clipping.numIntersection; + uniforms.clippingPlanes = _clipping.uniform; - } + } - }; + materialProperties.fog = fog; - }() ); + // store the light setup it was created for - this.getRenderTarget = function () { + materialProperties.lightsHash = lights.state.hash; - return _currentRenderTarget; + if ( material.lights ) { - }; + // wire up the material to this renderer's lighting state - this.setRenderTarget = function ( renderTarget ) { + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.directionalLights.value = lights.state.directional; + uniforms.spotLights.value = lights.state.spot; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.pointLights.value = lights.state.point; + uniforms.hemisphereLights.value = lights.state.hemi; + + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + // TODO (abelnation): add area lights shadow info to uniforms - _currentRenderTarget = renderTarget; + } - if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { + var progUniforms = materialProperties.program.getUniforms(), + uniformsList = + WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); - textures.setupRenderTarget( renderTarget ); + materialProperties.uniformsList = uniformsList; - } + } - var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube ); - var framebuffer; + function setProgram( camera, fog, material, object ) { - if ( renderTarget ) { + _usedTextureUnits = 0; - var renderTargetProperties = properties.get( renderTarget ); + var materialProperties = properties.get( material ); + var lights = currentRenderState.state.lights; - if ( isCube ) { + if ( _clippingEnabled ) { - framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ]; + if ( _localClippingEnabled || camera !== _currentCamera ) { - } else { + var useCache = + camera === _currentCamera && + material.id === _currentMaterialId; - framebuffer = renderTargetProperties.__webglFramebuffer; + // we might want to call this function with some ClippingGroup + // object instead of the material, once it becomes feasible + // (#8465, #8379) + _clipping.setState( + material.clippingPlanes, material.clipIntersection, material.clipShadows, + camera, materialProperties, useCache ); } - _currentScissor.copy( renderTarget.scissor ); - _currentScissorTest = renderTarget.scissorTest; + } - _currentViewport.copy( renderTarget.viewport ); + if ( material.needsUpdate === false ) { - } else { + if ( materialProperties.program === undefined ) { - framebuffer = null; + material.needsUpdate = true; - _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ); - _currentScissorTest = _scissorTest; + } else if ( material.fog && materialProperties.fog !== fog ) { - _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ); + material.needsUpdate = true; - } + } else if ( material.lights && materialProperties.lightsHash !== lights.state.hash ) { - if ( _currentFramebuffer !== framebuffer ) { + material.needsUpdate = true; - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - _currentFramebuffer = framebuffer; + } else if ( materialProperties.numClippingPlanes !== undefined && + ( materialProperties.numClippingPlanes !== _clipping.numPlanes || + materialProperties.numIntersection !== _clipping.numIntersection ) ) { - } + material.needsUpdate = true; - state.scissor( _currentScissor ); - state.setScissorTest( _currentScissorTest ); + } - state.viewport( _currentViewport ); + } - if ( isCube ) { + if ( material.needsUpdate ) { - var textureProperties = properties.get( renderTarget.texture ); - _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel ); + initMaterial( material, fog, object ); + material.needsUpdate = false; } - }; + var refreshProgram = false; + var refreshMaterial = false; + var refreshLights = false; - this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) { + var program = materialProperties.program, + p_uniforms = program.getUniforms(), + m_uniforms = materialProperties.shader.uniforms; - if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { + if ( state.useProgram( program.program ) ) { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); - return; + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; } - var framebuffer = properties.get( renderTarget ).__webglFramebuffer; - - if ( framebuffer ) { - - var restore = false; + if ( material.id !== _currentMaterialId ) { - if ( framebuffer !== _currentFramebuffer ) { + _currentMaterialId = material.id; - _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + refreshMaterial = true; - restore = true; + } - } + if ( refreshProgram || camera !== _currentCamera ) { - try { + p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); - var texture = renderTarget.texture; - var textureFormat = texture.format; - var textureType = texture.type; + if ( capabilities.logarithmicDepthBuffer ) { - if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { + p_uniforms.setValue( _gl, 'logDepthBufFC', + 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); - return; + } - } + // Avoid unneeded uniform updates per ArrayCamera's sub-camera - if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513) - ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox - ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) { + if ( _currentCamera !== ( _currentArrayCamera || camera ) ) { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); - return; + _currentCamera = ( _currentArrayCamera || camera ); - } + // lighting uniforms depend on the camera so enforce an update + // now, in case this material supports lights - or later, when + // the next material that does gets activated: - if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { + refreshMaterial = true; // set to true on material change + refreshLights = true; // remains set until update done - // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) + } - if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + // load material specific uniforms + // (shader material also gets them for the sake of genericity) - _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer ); + if ( material.isShaderMaterial || + material.isMeshPhongMaterial || + material.isMeshStandardMaterial || + material.envMap ) { - } + var uCamPos = p_uniforms.map.cameraPosition; - } else { + if ( uCamPos !== undefined ) { - console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); + uCamPos.setValue( _gl, + _vector3.setFromMatrixPosition( camera.matrixWorld ) ); } - } finally { - - if ( restore ) { + } - _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); + if ( material.isMeshPhongMaterial || + material.isMeshLambertMaterial || + material.isMeshBasicMaterial || + material.isMeshStandardMaterial || + material.isShaderMaterial || + material.skinning ) { - } + p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); } } - }; - - // Map three.js constants to WebGL constants - - function paramThreeToGL( p ) { + // skinning uniforms must be set even if material didn't change + // auto-setting of texture unit for bone texture must go before other textures + // not sure why, but otherwise weird things happen - var extension; + if ( material.skinning ) { - if ( p === RepeatWrapping ) return _gl.REPEAT; - if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; - if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; + p_uniforms.setOptional( _gl, object, 'bindMatrix' ); + p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); - if ( p === NearestFilter ) return _gl.NEAREST; - if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; - if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; + var skeleton = object.skeleton; - if ( p === LinearFilter ) return _gl.LINEAR; - if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; - if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; + if ( skeleton ) { - if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE; - if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; - if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; - if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; + var bones = skeleton.bones; - if ( p === ByteType ) return _gl.BYTE; - if ( p === ShortType ) return _gl.SHORT; - if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT; - if ( p === IntType ) return _gl.INT; - if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT; - if ( p === FloatType ) return _gl.FLOAT; + if ( capabilities.floatVertexTextures ) { - if ( p === HalfFloatType ) { + if ( skeleton.boneTexture === undefined ) { - extension = extensions.get( 'OES_texture_half_float' ); + // layout (1 matrix = 4 pixels) + // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) + // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) + // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) + // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) + // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) - if ( extension !== null ) return extension.HALF_FLOAT_OES; - } + var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix + size = _Math.ceilPowerOfTwo( size ); + size = Math.max( size, 4 ); - if ( p === AlphaFormat ) return _gl.ALPHA; - if ( p === RGBFormat ) return _gl.RGB; - if ( p === RGBAFormat ) return _gl.RGBA; - if ( p === LuminanceFormat ) return _gl.LUMINANCE; - if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; - if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT; - if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL; + var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel + boneMatrices.set( skeleton.boneMatrices ); // copy current values - if ( p === AddEquation ) return _gl.FUNC_ADD; - if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT; - if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; + var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType ); + boneTexture.needsUpdate = true; - if ( p === ZeroFactor ) return _gl.ZERO; - if ( p === OneFactor ) return _gl.ONE; - if ( p === SrcColorFactor ) return _gl.SRC_COLOR; - if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; - if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA; - if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; - if ( p === DstAlphaFactor ) return _gl.DST_ALPHA; - if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; + skeleton.boneMatrices = boneMatrices; + skeleton.boneTexture = boneTexture; + skeleton.boneTextureSize = size; - if ( p === DstColorFactor ) return _gl.DST_COLOR; - if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; - if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; + } - if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || - p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { + p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture ); + p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize ); - extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); + } else { - if ( extension !== null ) { + p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); - if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; - if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; - if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; - if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + } } } - if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || - p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { - - extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); + if ( refreshMaterial ) { - if ( extension !== null ) { + p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); + p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint ); - if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; - if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; - if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; - if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + if ( material.lights ) { - } + // the current material requires lighting info - } + // note: all lighting uniforms are always set correctly + // they simply reference the renderer's state for their + // values + // + // use the current material's .needsUpdate flags to set + // the GL state when required - if ( p === RGB_ETC1_Format ) { + markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); - extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); + } - if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL; + // refresh uniforms common to several materials - } + if ( fog && material.fog ) { - if ( p === MinEquation || p === MaxEquation ) { + refreshUniformsFog( m_uniforms, fog ); - extension = extensions.get( 'EXT_blend_minmax' ); + } - if ( extension !== null ) { + if ( material.isMeshBasicMaterial ) { - if ( p === MinEquation ) return extension.MIN_EXT; - if ( p === MaxEquation ) return extension.MAX_EXT; + refreshUniformsCommon( m_uniforms, material ); - } + } else if ( material.isMeshLambertMaterial ) { - } + refreshUniformsCommon( m_uniforms, material ); + refreshUniformsLambert( m_uniforms, material ); - if ( p === UnsignedInt248Type ) { + } else if ( material.isMeshPhongMaterial ) { - extension = extensions.get( 'WEBGL_depth_texture' ); + refreshUniformsCommon( m_uniforms, material ); - if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL; + if ( material.isMeshToonMaterial ) { - } + refreshUniformsToon( m_uniforms, material ); - return 0; + } else { - } + refreshUniformsPhong( m_uniforms, material ); - } + } - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + } else if ( material.isMeshStandardMaterial ) { - function FogExp2 ( color, density ) { + refreshUniformsCommon( m_uniforms, material ); - this.name = ''; + if ( material.isMeshPhysicalMaterial ) { - this.color = new Color( color ); - this.density = ( density !== undefined ) ? density : 0.00025; + refreshUniformsPhysical( m_uniforms, material ); - } + } else { - FogExp2.prototype.isFogExp2 = true; + refreshUniformsStandard( m_uniforms, material ); - FogExp2.prototype.clone = function () { + } - return new FogExp2( this.color.getHex(), this.density ); + } else if ( material.isMeshDepthMaterial ) { - }; + refreshUniformsCommon( m_uniforms, material ); + refreshUniformsDepth( m_uniforms, material ); - FogExp2.prototype.toJSON = function ( meta ) { + } else if ( material.isMeshDistanceMaterial ) { - return { - type: 'FogExp2', - color: this.color.getHex(), - density: this.density - }; + refreshUniformsCommon( m_uniforms, material ); + refreshUniformsDistance( m_uniforms, material ); - }; + } else if ( material.isMeshNormalMaterial ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + refreshUniformsCommon( m_uniforms, material ); + refreshUniformsNormal( m_uniforms, material ); - function Fog ( color, near, far ) { + } else if ( material.isLineBasicMaterial ) { - this.name = ''; + refreshUniformsLine( m_uniforms, material ); - this.color = new Color( color ); + if ( material.isLineDashedMaterial ) { - this.near = ( near !== undefined ) ? near : 1; - this.far = ( far !== undefined ) ? far : 1000; + refreshUniformsDash( m_uniforms, material ); - } + } - Fog.prototype.isFog = true; + } else if ( material.isPointsMaterial ) { - Fog.prototype.clone = function () { + refreshUniformsPoints( m_uniforms, material ); - return new Fog( this.color.getHex(), this.near, this.far ); + } else if ( material.isShadowMaterial ) { - }; + m_uniforms.color.value = material.color; + m_uniforms.opacity.value = material.opacity; - Fog.prototype.toJSON = function ( meta ) { + } - return { - type: 'Fog', - color: this.color.getHex(), - near: this.near, - far: this.far - }; + // RectAreaLight Texture + // TODO (mrdoob): Find a nicer implementation - }; + if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1; + if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2; - /** - * @author mrdoob / http://mrdoob.com/ - */ + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this ); - function Scene () { + } - Object3D.call( this ); + if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { - this.type = 'Scene'; + WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this ); + material.uniformsNeedUpdate = false; - this.background = null; - this.fog = null; - this.overrideMaterial = null; + } - this.autoUpdate = true; // checked by the renderer + // common matrices - } + p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); + p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); + p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); - Scene.prototype = Object.assign( Object.create( Object3D.prototype ), { + return program; - constructor: Scene, + } - copy: function ( source, recursive ) { + // Uniforms (refresh uniforms objects) - Object3D.prototype.copy.call( this, source, recursive ); + function refreshUniformsCommon( uniforms, material ) { - if ( source.background !== null ) this.background = source.background.clone(); - if ( source.fog !== null ) this.fog = source.fog.clone(); - if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); + uniforms.opacity.value = material.opacity; - this.autoUpdate = source.autoUpdate; - this.matrixAutoUpdate = source.matrixAutoUpdate; + if ( material.color ) { - return this; + uniforms.diffuse.value = material.color; - }, + } - toJSON: function ( meta ) { + if ( material.emissive ) { - var data = Object3D.prototype.toJSON.call( this, meta ); + uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); - if ( this.background !== null ) data.object.background = this.background.toJSON( meta ); - if ( this.fog !== null ) data.object.fog = this.fog.toJSON(); + } - return data; + if ( material.map ) { - } + uniforms.map.value = material.map; - } ); + } - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + if ( material.alphaMap ) { - function LensFlare( texture, size, distance, blending, color ) { + uniforms.alphaMap.value = material.alphaMap; - Object3D.call( this ); + } - this.lensFlares = []; + if ( material.specularMap ) { - this.positionScreen = new Vector3(); - this.customUpdateCallback = undefined; + uniforms.specularMap.value = material.specularMap; - if ( texture !== undefined ) { + } - this.add( texture, size, distance, blending, color ); + if ( material.envMap ) { - } + uniforms.envMap.value = material.envMap; - } + // don't flip CubeTexture envMaps, flip everything else: + // WebGLRenderTargetCube will be flipped for backwards compatibility + // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture + // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future + uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1; - LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), { + uniforms.reflectivity.value = material.reflectivity; + uniforms.refractionRatio.value = material.refractionRatio; - constructor: LensFlare, + uniforms.maxMipLevel.value = properties.get( material.envMap ).__maxMipLevel; - isLensFlare: true, + } - copy: function ( source ) { + if ( material.lightMap ) { - Object3D.prototype.copy.call( this, source ); + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; - this.positionScreen.copy( source.positionScreen ); - this.customUpdateCallback = source.customUpdateCallback; + } - for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) { + if ( material.aoMap ) { - this.lensFlares.push( source.lensFlares[ i ] ); + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; } - return this; - - }, + // uv repeat and offset setting priorities + // 1. color map + // 2. specular map + // 3. normal map + // 4. bump map + // 5. alpha map + // 6. emissive map - add: function ( texture, size, distance, blending, color, opacity ) { + var uvScaleMap; - if ( size === undefined ) size = - 1; - if ( distance === undefined ) distance = 0; - if ( opacity === undefined ) opacity = 1; - if ( color === undefined ) color = new Color( 0xffffff ); - if ( blending === undefined ) blending = NormalBlending; - - distance = Math.min( distance, Math.max( 0, distance ) ); - - this.lensFlares.push( { - texture: texture, // THREE.Texture - size: size, // size in pixels (-1 = use texture.width) - distance: distance, // distance (0-1) from light source (0=at light source) - x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back - scale: 1, // scale - rotation: 0, // rotation - opacity: opacity, // opacity - color: color, // color - blending: blending // blending - } ); + if ( material.map ) { - }, + uvScaleMap = material.map; - /* - * Update lens flares update positions on all flares based on the screen position - * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way. - */ + } else if ( material.specularMap ) { - updateLensFlares: function () { + uvScaleMap = material.specularMap; - var f, fl = this.lensFlares.length; - var flare; - var vecX = - this.positionScreen.x * 2; - var vecY = - this.positionScreen.y * 2; + } else if ( material.displacementMap ) { - for ( f = 0; f < fl; f ++ ) { + uvScaleMap = material.displacementMap; - flare = this.lensFlares[ f ]; + } else if ( material.normalMap ) { - flare.x = this.positionScreen.x + vecX * flare.distance; - flare.y = this.positionScreen.y + vecY * flare.distance; + uvScaleMap = material.normalMap; - flare.wantedRotation = flare.x * Math.PI * 0.25; - flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25; + } else if ( material.bumpMap ) { - } + uvScaleMap = material.bumpMap; - } + } else if ( material.roughnessMap ) { - } ); + uvScaleMap = material.roughnessMap; - /** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * uvOffset: new THREE.Vector2(), - * uvScale: new THREE.Vector2() - * } - */ + } else if ( material.metalnessMap ) { - function SpriteMaterial( parameters ) { + uvScaleMap = material.metalnessMap; - Material.call( this ); + } else if ( material.alphaMap ) { - this.type = 'SpriteMaterial'; + uvScaleMap = material.alphaMap; - this.color = new Color( 0xffffff ); - this.map = null; + } else if ( material.emissiveMap ) { - this.rotation = 0; + uvScaleMap = material.emissiveMap; - this.fog = false; - this.lights = false; + } - this.setValues( parameters ); + if ( uvScaleMap !== undefined ) { - } + // backwards compatibility + if ( uvScaleMap.isWebGLRenderTarget ) { - SpriteMaterial.prototype = Object.create( Material.prototype ); - SpriteMaterial.prototype.constructor = SpriteMaterial; - SpriteMaterial.prototype.isSpriteMaterial = true; + uvScaleMap = uvScaleMap.texture; - SpriteMaterial.prototype.copy = function ( source ) { + } - Material.prototype.copy.call( this, source ); + if ( uvScaleMap.matrixAutoUpdate === true ) { - this.color.copy( source.color ); - this.map = source.map; + var offset = uvScaleMap.offset; + var repeat = uvScaleMap.repeat; + var rotation = uvScaleMap.rotation; + var center = uvScaleMap.center; - this.rotation = source.rotation; + uvScaleMap.matrix.setUvTransform( offset.x, offset.y, repeat.x, repeat.y, rotation, center.x, center.y ); - return this; + } - }; + uniforms.uvTransform.value.copy( uvScaleMap.matrix ); - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - */ + } - function Sprite( material ) { + } - Object3D.call( this ); + function refreshUniformsLine( uniforms, material ) { - this.type = 'Sprite'; + uniforms.diffuse.value = material.color; + uniforms.opacity.value = material.opacity; - this.material = ( material !== undefined ) ? material : new SpriteMaterial(); + } - } + function refreshUniformsDash( uniforms, material ) { - Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), { + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; - constructor: Sprite, + } - isSprite: true, + function refreshUniformsPoints( uniforms, material ) { - raycast: ( function () { + uniforms.diffuse.value = material.color; + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * _pixelRatio; + uniforms.scale.value = _height * 0.5; - var intersectPoint = new Vector3(); - var worldPosition = new Vector3(); - var worldScale = new Vector3(); + uniforms.map.value = material.map; - return function raycast( raycaster, intersects ) { + if ( material.map !== null ) { - worldPosition.setFromMatrixPosition( this.matrixWorld ); - raycaster.ray.closestPointToPoint( worldPosition, intersectPoint ); + if ( material.map.matrixAutoUpdate === true ) { - worldScale.setFromMatrixScale( this.matrixWorld ); - var guessSizeSq = worldScale.x * worldScale.y / 4; + var offset = material.map.offset; + var repeat = material.map.repeat; + var rotation = material.map.rotation; + var center = material.map.center; - if ( worldPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return; + material.map.matrix.setUvTransform( offset.x, offset.y, repeat.x, repeat.y, rotation, center.x, center.y ); - var distance = raycaster.ray.origin.distanceTo( intersectPoint ); + } - if ( distance < raycaster.near || distance > raycaster.far ) return; + uniforms.uvTransform.value.copy( material.map.matrix ); - intersects.push( { + } - distance: distance, - point: intersectPoint.clone(), - face: null, - object: this + } - } ); + function refreshUniformsFog( uniforms, fog ) { - }; + uniforms.fogColor.value = fog.color; - }() ), + if ( fog.isFog ) { - clone: function () { + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; - return new this.constructor( this.material ).copy( this ); + } else if ( fog.isFogExp2 ) { - } + uniforms.fogDensity.value = fog.density; - } ); + } - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author mrdoob / http://mrdoob.com/ - */ + } - function LOD() { + function refreshUniformsLambert( uniforms, material ) { - Object3D.call( this ); + if ( material.emissiveMap ) { - this.type = 'LOD'; + uniforms.emissiveMap.value = material.emissiveMap; - Object.defineProperties( this, { - levels: { - enumerable: true, - value: [] } - } ); - - } - LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { + } - constructor: LOD, + function refreshUniformsPhong( uniforms, material ) { - copy: function ( source ) { + uniforms.specular.value = material.specular; + uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) - Object3D.prototype.copy.call( this, source, false ); + if ( material.emissiveMap ) { - var levels = source.levels; + uniforms.emissiveMap.value = material.emissiveMap; - for ( var i = 0, l = levels.length; i < l; i ++ ) { + } - var level = levels[ i ]; + if ( material.bumpMap ) { - this.addLevel( level.object.clone(), level.distance ); + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; } - return this; + if ( material.normalMap ) { - }, + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); - addLevel: function ( object, distance ) { + } - if ( distance === undefined ) distance = 0; + if ( material.displacementMap ) { - distance = Math.abs( distance ); + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - var levels = this.levels; + } - for ( var l = 0; l < levels.length; l ++ ) { + } - if ( distance < levels[ l ].distance ) { + function refreshUniformsToon( uniforms, material ) { - break; + refreshUniformsPhong( uniforms, material ); - } + if ( material.gradientMap ) { - } + uniforms.gradientMap.value = material.gradientMap; - levels.splice( l, 0, { distance: distance, object: object } ); + } - this.add( object ); + } - }, + function refreshUniformsStandard( uniforms, material ) { - getObjectForDistance: function ( distance ) { + uniforms.roughness.value = material.roughness; + uniforms.metalness.value = material.metalness; - var levels = this.levels; + if ( material.roughnessMap ) { - for ( var i = 1, l = levels.length; i < l; i ++ ) { + uniforms.roughnessMap.value = material.roughnessMap; - if ( distance < levels[ i ].distance ) { + } - break; + if ( material.metalnessMap ) { - } + uniforms.metalnessMap.value = material.metalnessMap; } - return levels[ i - 1 ].object; + if ( material.emissiveMap ) { - }, + uniforms.emissiveMap.value = material.emissiveMap; - raycast: ( function () { + } - var matrixPosition = new Vector3(); + if ( material.bumpMap ) { - return function raycast( raycaster, intersects ) { + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; - matrixPosition.setFromMatrixPosition( this.matrixWorld ); + } - var distance = raycaster.ray.origin.distanceTo( matrixPosition ); + if ( material.normalMap ) { - this.getObjectForDistance( distance ).raycast( raycaster, intersects ); + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); - }; + } - }() ), + if ( material.displacementMap ) { - update: function () { + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - var v1 = new Vector3(); - var v2 = new Vector3(); + } - return function update( camera ) { + if ( material.envMap ) { - var levels = this.levels; + //uniforms.envMap.value = material.envMap; // part of uniforms common + uniforms.envMapIntensity.value = material.envMapIntensity; - if ( levels.length > 1 ) { + } - v1.setFromMatrixPosition( camera.matrixWorld ); - v2.setFromMatrixPosition( this.matrixWorld ); + } - var distance = v1.distanceTo( v2 ); + function refreshUniformsPhysical( uniforms, material ) { - levels[ 0 ].object.visible = true; + uniforms.clearCoat.value = material.clearCoat; + uniforms.clearCoatRoughness.value = material.clearCoatRoughness; - for ( var i = 1, l = levels.length; i < l; i ++ ) { + refreshUniformsStandard( uniforms, material ); - if ( distance >= levels[ i ].distance ) { + } - levels[ i - 1 ].object.visible = false; - levels[ i ].object.visible = true; + function refreshUniformsDepth( uniforms, material ) { - } else { + if ( material.displacementMap ) { - break; + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - } + } - } + } - for ( ; i < l; i ++ ) { + function refreshUniformsDistance( uniforms, material ) { - levels[ i ].object.visible = false; - - } - - } - - }; - - }(), + if ( material.displacementMap ) { - toJSON: function ( meta ) { + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - var data = Object3D.prototype.toJSON.call( this, meta ); + } - data.object.levels = []; + uniforms.referencePosition.value.copy( material.referencePosition ); + uniforms.nearDistance.value = material.nearDistance; + uniforms.farDistance.value = material.farDistance; - var levels = this.levels; + } - for ( var i = 0, l = levels.length; i < l; i ++ ) { + function refreshUniformsNormal( uniforms, material ) { - var level = levels[ i ]; + if ( material.bumpMap ) { - data.object.levels.push( { - object: level.object.uuid, - distance: level.distance - } ); + uniforms.bumpMap.value = material.bumpMap; + uniforms.bumpScale.value = material.bumpScale; } - return data; - - } + if ( material.normalMap ) { - } ); + uniforms.normalMap.value = material.normalMap; + uniforms.normalScale.value.copy( material.normalScale ); - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author michael guerrero / http://realitymeltdown.com - * @author ikerr / http://verold.com - */ + } - function Skeleton( bones, boneInverses ) { + if ( material.displacementMap ) { - // copy the bone array + uniforms.displacementMap.value = material.displacementMap; + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; - bones = bones || []; + } - this.bones = bones.slice( 0 ); - this.boneMatrices = new Float32Array( this.bones.length * 16 ); + } - // use the supplied bone inverses or calculate the inverses + // If uniforms are marked as clean, they don't need to be loaded to the GPU. - if ( boneInverses === undefined ) { + function markUniformsLightsNeedsUpdate( uniforms, value ) { - this.calculateInverses(); + uniforms.ambientLightColor.needsUpdate = value; - } else { + uniforms.directionalLights.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.rectAreaLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; - if ( this.bones.length === boneInverses.length ) { + } - this.boneInverses = boneInverses.slice( 0 ); + // Textures - } else { + function allocTextureUnit() { - console.warn( 'THREE.Skeleton boneInverses is the wrong length.' ); + var textureUnit = _usedTextureUnits; - this.boneInverses = []; + if ( textureUnit >= capabilities.maxTextures ) { - for ( var i = 0, il = this.bones.length; i < il; i ++ ) { + console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures ); - this.boneInverses.push( new Matrix4() ); + } - } + _usedTextureUnits += 1; - } + return textureUnit; } - } - - Object.assign( Skeleton.prototype, { + this.allocTextureUnit = allocTextureUnit; - calculateInverses: function () { + // this.setTexture2D = setTexture2D; + this.setTexture2D = ( function () { - this.boneInverses = []; + var warned = false; - for ( var i = 0, il = this.bones.length; i < il; i ++ ) { + // backwards compatibility: peel texture.texture + return function setTexture2D( texture, slot ) { - var inverse = new Matrix4(); + if ( texture && texture.isWebGLRenderTarget ) { - if ( this.bones[ i ] ) { + if ( ! warned ) { - inverse.getInverse( this.bones[ i ].matrixWorld ); + console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." ); + warned = true; - } + } - this.boneInverses.push( inverse ); + texture = texture.texture; - } + } - }, + textures.setTexture2D( texture, slot ); - pose: function () { + }; - var bone, i, il; + }() ); - // recover the bind-time world matrices + this.setTexture = ( function () { - for ( i = 0, il = this.bones.length; i < il; i ++ ) { + var warned = false; - bone = this.bones[ i ]; + return function setTexture( texture, slot ) { - if ( bone ) { + if ( ! warned ) { - bone.matrixWorld.getInverse( this.boneInverses[ i ] ); + console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." ); + warned = true; } - } + textures.setTexture2D( texture, slot ); - // compute the local matrices, positions, rotations and scales + }; - for ( i = 0, il = this.bones.length; i < il; i ++ ) { + }() ); - bone = this.bones[ i ]; + this.setTextureCube = ( function () { - if ( bone ) { + var warned = false; - if ( bone.parent && bone.parent.isBone ) { + return function setTextureCube( texture, slot ) { - bone.matrix.getInverse( bone.parent.matrixWorld ); - bone.matrix.multiply( bone.matrixWorld ); + // backwards compatibility: peel texture.texture + if ( texture && texture.isWebGLRenderTargetCube ) { - } else { + if ( ! warned ) { - bone.matrix.copy( bone.matrixWorld ); + console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); + warned = true; } - bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); + texture = texture.texture; } - } + // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture + // TODO: unify these code paths + if ( ( texture && texture.isCubeTexture ) || + ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { - }, + // CompressedTexture can have Array in image :/ - update: ( function () { + // this function alone should take care of cube textures + textures.setTextureCube( texture, slot ); - var offsetMatrix = new Matrix4(); - var identityMatrix = new Matrix4(); + } else { - return function update() { + // assumed: texture property of THREE.WebGLRenderTargetCube - var bones = this.bones; - var boneInverses = this.boneInverses; - var boneMatrices = this.boneMatrices; - var boneTexture = this.boneTexture; + textures.setTextureCubeDynamic( texture, slot ); - // flatten bone matrices to array + } - for ( var i = 0, il = bones.length; i < il; i ++ ) { + }; - // compute the offset between the current and the original transform + }() ); - var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix; + this.getRenderTarget = function () { - offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] ); - offsetMatrix.toArray( boneMatrices, i * 16 ); + return _currentRenderTarget; - } + }; - if ( boneTexture !== undefined ) { + this.setRenderTarget = function ( renderTarget ) { - boneTexture.needsUpdate = true; + _currentRenderTarget = renderTarget; - } + if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { - }; + textures.setupRenderTarget( renderTarget ); - } )(), + } - clone: function () { + var framebuffer = null; + var isCube = false; - return new Skeleton( this.bones, this.boneInverses ); + if ( renderTarget ) { - } + var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; - } ); + if ( renderTarget.isWebGLRenderTargetCube ) { - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ + framebuffer = __webglFramebuffer[ renderTarget.activeCubeFace ]; + isCube = true; - function Bone() { + } else { - Object3D.call( this ); + framebuffer = __webglFramebuffer; - this.type = 'Bone'; + } - } + _currentViewport.copy( renderTarget.viewport ); + _currentScissor.copy( renderTarget.scissor ); + _currentScissorTest = renderTarget.scissorTest; - Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { + } else { - constructor: Bone, + _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ); + _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ); + _currentScissorTest = _scissorTest; - isBone: true + } - } ); + if ( _currentFramebuffer !== framebuffer ) { - /** - * @author mikael emtinger / http://gomo.se/ - * @author alteredq / http://alteredqualia.com/ - * @author ikerr / http://verold.com - */ + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); + _currentFramebuffer = framebuffer; - function SkinnedMesh( geometry, material ) { + } - Mesh.call( this, geometry, material ); + state.viewport( _currentViewport ); + state.scissor( _currentScissor ); + state.setScissorTest( _currentScissorTest ); - this.type = 'SkinnedMesh'; + if ( isCube ) { - this.bindMode = 'attached'; - this.bindMatrix = new Matrix4(); - this.bindMatrixInverse = new Matrix4(); + var textureProperties = properties.get( renderTarget.texture ); + _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel ); - var bones = this.initBones(); - var skeleton = new Skeleton( bones ); + } - this.bind( skeleton, this.matrixWorld ); + }; - this.normalizeSkinWeights(); + this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) { - } + if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { - SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); + return; - constructor: SkinnedMesh, + } - isSkinnedMesh: true, + var framebuffer = properties.get( renderTarget ).__webglFramebuffer; - initBones: function () { + if ( framebuffer ) { - var bones = [], bone, gbone; - var i, il; + var restore = false; - if ( this.geometry && this.geometry.bones !== undefined ) { + if ( framebuffer !== _currentFramebuffer ) { - // first, create array of 'Bone' objects from geometry data + _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); - for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) { + restore = true; - gbone = this.geometry.bones[ i ]; + } - // create new 'Bone' object + try { - bone = new Bone(); - bones.push( bone ); + var texture = renderTarget.texture; + var textureFormat = texture.format; + var textureType = texture.type; - // apply values + if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) { - bone.name = gbone.name; - bone.position.fromArray( gbone.pos ); - bone.quaternion.fromArray( gbone.rotq ); - if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl ); + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); + return; - } + } - // second, create bone hierarchy + if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513) + ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox + ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) { - for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) { + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); + return; - gbone = this.geometry.bones[ i ]; + } - if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) { + if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) { - // subsequent bones in the hierarchy + // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) - bones[ gbone.parent ].add( bones[ i ] ); + if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { + + _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); + + } } else { - // topmost bone, immediate child of the skinned mesh + console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); - this.add( bones[ i ] ); + } + + } finally { + + if ( restore ) { + + _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer ); } @@ -23869,1804 +23671,1699 @@ } - // now the bones are part of the scene graph and children of the skinned mesh. - // let's update the corresponding matrices - - this.updateMatrixWorld( true ); + }; - return bones; + this.copyFramebufferToTexture = function ( position, texture, level ) { - }, + var width = texture.image.width; + var height = texture.image.height; + var glFormat = utils.convert( texture.format ); - bind: function ( skeleton, bindMatrix ) { + this.setTexture2D( texture, 0 ); - this.skeleton = skeleton; + _gl.copyTexImage2D( _gl.TEXTURE_2D, level || 0, glFormat, position.x, position.y, width, height, 0 ); - if ( bindMatrix === undefined ) { + }; - this.updateMatrixWorld( true ); + this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) { - this.skeleton.calculateInverses(); + var width = srcTexture.image.width; + var height = srcTexture.image.height; + var glFormat = utils.convert( dstTexture.format ); + var glType = utils.convert( dstTexture.type ); + var pixels = srcTexture.isDataTexture ? srcTexture.image.data : srcTexture.image; - bindMatrix = this.matrixWorld; + this.setTexture2D( dstTexture, 0 ); - } + _gl.texSubImage2D( _gl.TEXTURE_2D, level || 0, position.x, position.y, width, height, glFormat, glType, pixels ); - this.bindMatrix.copy( bindMatrix ); - this.bindMatrixInverse.getInverse( bindMatrix ); + }; - }, + } - pose: function () { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - this.skeleton.pose(); + function FogExp2( color, density ) { - }, + this.name = ''; - normalizeSkinWeights: function () { + this.color = new Color( color ); + this.density = ( density !== undefined ) ? density : 0.00025; - var scale, i; + } - if ( this.geometry && this.geometry.isGeometry ) { + FogExp2.prototype.isFogExp2 = true; - for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) { + FogExp2.prototype.clone = function () { - var sw = this.geometry.skinWeights[ i ]; + return new FogExp2( this.color.getHex(), this.density ); - scale = 1.0 / sw.lengthManhattan(); + }; - if ( scale !== Infinity ) { + FogExp2.prototype.toJSON = function ( /* meta */ ) { - sw.multiplyScalar( scale ); + return { + type: 'FogExp2', + color: this.color.getHex(), + density: this.density + }; - } else { + }; - sw.set( 1, 0, 0, 0 ); // do something reasonable + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - } + function Fog( color, near, far ) { - } + this.name = ''; - } else if ( this.geometry && this.geometry.isBufferGeometry ) { + this.color = new Color( color ); - var vec = new Vector4(); + this.near = ( near !== undefined ) ? near : 1; + this.far = ( far !== undefined ) ? far : 1000; - var skinWeight = this.geometry.attributes.skinWeight; + } - for ( i = 0; i < skinWeight.count; i ++ ) { + Fog.prototype.isFog = true; - vec.x = skinWeight.getX( i ); - vec.y = skinWeight.getY( i ); - vec.z = skinWeight.getZ( i ); - vec.w = skinWeight.getW( i ); + Fog.prototype.clone = function () { - scale = 1.0 / vec.lengthManhattan(); + return new Fog( this.color.getHex(), this.near, this.far ); - if ( scale !== Infinity ) { + }; - vec.multiplyScalar( scale ); + Fog.prototype.toJSON = function ( /* meta */ ) { - } else { + return { + type: 'Fog', + color: this.color.getHex(), + near: this.near, + far: this.far + }; - vec.set( 1, 0, 0, 0 ); // do something reasonable + }; - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w ); + function Scene() { - } + Object3D.call( this ); - } + this.type = 'Scene'; - }, + this.background = null; + this.fog = null; + this.overrideMaterial = null; - updateMatrixWorld: function ( force ) { + this.autoUpdate = true; // checked by the renderer - Mesh.prototype.updateMatrixWorld.call( this, force ); + } - if ( this.bindMode === 'attached' ) { + Scene.prototype = Object.assign( Object.create( Object3D.prototype ), { - this.bindMatrixInverse.getInverse( this.matrixWorld ); + constructor: Scene, - } else if ( this.bindMode === 'detached' ) { + copy: function ( source, recursive ) { - this.bindMatrixInverse.getInverse( this.bindMatrix ); + Object3D.prototype.copy.call( this, source, recursive ); - } else { + if ( source.background !== null ) this.background = source.background.clone(); + if ( source.fog !== null ) this.fog = source.fog.clone(); + if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone(); - console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode ); + this.autoUpdate = source.autoUpdate; + this.matrixAutoUpdate = source.matrixAutoUpdate; - } + return this; }, - clone: function () { + toJSON: function ( meta ) { - return new this.constructor( this.geometry, this.material ).copy( this ); + var data = Object3D.prototype.toJSON.call( this, meta ); + + if ( this.background !== null ) data.object.background = this.background.toJSON( meta ); + if ( this.fog !== null ) data.object.fog = this.fog.toJSON(); + + return data; } } ); /** - * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * * parameters = { * color: , * opacity: , + * map: new THREE.Texture( ), * - * linewidth: , - * linecap: "round", - * linejoin: "round" + * uvOffset: new THREE.Vector2(), + * uvScale: new THREE.Vector2() * } */ - function LineBasicMaterial( parameters ) { + function SpriteMaterial( parameters ) { Material.call( this ); - this.type = 'LineBasicMaterial'; + this.type = 'SpriteMaterial'; this.color = new Color( 0xffffff ); + this.map = null; - this.linewidth = 1; - this.linecap = 'round'; - this.linejoin = 'round'; + this.rotation = 0; + this.fog = false; this.lights = false; this.setValues( parameters ); } - LineBasicMaterial.prototype = Object.create( Material.prototype ); - LineBasicMaterial.prototype.constructor = LineBasicMaterial; - - LineBasicMaterial.prototype.isLineBasicMaterial = true; + SpriteMaterial.prototype = Object.create( Material.prototype ); + SpriteMaterial.prototype.constructor = SpriteMaterial; + SpriteMaterial.prototype.isSpriteMaterial = true; - LineBasicMaterial.prototype.copy = function ( source ) { + SpriteMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.color.copy( source.color ); + this.map = source.map; - this.linewidth = source.linewidth; - this.linecap = source.linecap; - this.linejoin = source.linejoin; + this.rotation = source.rotation; return this; }; /** - * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ */ - function Line( geometry, material, mode ) { - - if ( mode === 1 ) { - - console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' ); - return new LineSegments( geometry, material ); - - } + function Sprite( material ) { Object3D.call( this ); - this.type = 'Line'; + this.type = 'Sprite'; - this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); - this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } ); + this.material = ( material !== undefined ) ? material : new SpriteMaterial(); + + this.center = new Vector2( 0.5, 0.5 ); } - Line.prototype = Object.assign( Object.create( Object3D.prototype ), { + Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), { - constructor: Line, + constructor: Sprite, - isLine: true, + isSprite: true, raycast: ( function () { - var inverseMatrix = new Matrix4(); - var ray = new Ray(); - var sphere = new Sphere(); + var intersectPoint = new Vector3(); + var worldPosition = new Vector3(); + var worldScale = new Vector3(); return function raycast( raycaster, intersects ) { - var precision = raycaster.linePrecision; - var precisionSq = precision * precision; + worldPosition.setFromMatrixPosition( this.matrixWorld ); + raycaster.ray.closestPointToPoint( worldPosition, intersectPoint ); - var geometry = this.geometry; - var matrixWorld = this.matrixWorld; + worldScale.setFromMatrixScale( this.matrixWorld ); + var guessSizeSq = worldScale.x * worldScale.y / 4; - // Checking boundingSphere distance to ray + if ( worldPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return; - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + var distance = raycaster.ray.origin.distanceTo( intersectPoint ); - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); + if ( distance < raycaster.near || distance > raycaster.far ) return; - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + intersects.push( { - // + distance: distance, + point: intersectPoint.clone(), + face: null, + object: this - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + } ); - var vStart = new Vector3(); - var vEnd = new Vector3(); - var interSegment = new Vector3(); - var interRay = new Vector3(); - var step = (this && this.isLineSegments) ? 2 : 1; + }; - if ( geometry.isBufferGeometry ) { + }() ), - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + clone: function () { - if ( index !== null ) { + return new this.constructor( this.material ).copy( this ); - var indices = index.array; + }, - for ( var i = 0, l = indices.length - 1; i < l; i += step ) { + copy: function ( source ) { - var a = indices[ i ]; - var b = indices[ i + 1 ]; + Object3D.prototype.copy.call( this, source ); - vStart.fromArray( positions, a * 3 ); - vEnd.fromArray( positions, b * 3 ); + if ( source.center !== undefined ) this.center.copy( source.center ); - var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + return this; - if ( distSq > precisionSq ) continue; + } - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - var distance = raycaster.ray.origin.distanceTo( interRay ); + } ); - if ( distance < raycaster.near || distance > raycaster.far ) continue; + /** + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author mrdoob / http://mrdoob.com/ + */ - intersects.push( { + function LOD() { - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + Object3D.call( this ); - } ); + this.type = 'LOD'; - } + Object.defineProperties( this, { + levels: { + enumerable: true, + value: [] + } + } ); - } else { + } - for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) { + LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { - vStart.fromArray( positions, 3 * i ); - vEnd.fromArray( positions, 3 * i + 3 ); + constructor: LOD, - var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); + copy: function ( source ) { - if ( distSq > precisionSq ) continue; + Object3D.prototype.copy.call( this, source, false ); - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + var levels = source.levels; - var distance = raycaster.ray.origin.distanceTo( interRay ); + for ( var i = 0, l = levels.length; i < l; i ++ ) { - if ( distance < raycaster.near || distance > raycaster.far ) continue; + var level = levels[ i ]; - intersects.push( { + this.addLevel( level.object.clone(), level.distance ); - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + } - } ); + return this; - } + }, - } + addLevel: function ( object, distance ) { - } else if ( geometry.isGeometry ) { + if ( distance === undefined ) distance = 0; - var vertices = geometry.vertices; - var nbVertices = vertices.length; + distance = Math.abs( distance ); - for ( var i = 0; i < nbVertices - 1; i += step ) { + var levels = this.levels; - var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); + for ( var l = 0; l < levels.length; l ++ ) { - if ( distSq > precisionSq ) continue; + if ( distance < levels[ l ].distance ) { - interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation + break; - var distance = raycaster.ray.origin.distanceTo( interRay ); + } - if ( distance < raycaster.near || distance > raycaster.far ) continue; + } - intersects.push( { + levels.splice( l, 0, { distance: distance, object: object } ); - distance: distance, - // What do we want? intersection point on the ray or on the segment?? - // point: raycaster.ray.at( distance ), - point: interSegment.clone().applyMatrix4( this.matrixWorld ), - index: i, - face: null, - faceIndex: null, - object: this + this.add( object ); - } ); + }, - } + getObjectForDistance: function ( distance ) { + + var levels = this.levels; + + for ( var i = 1, l = levels.length; i < l; i ++ ) { + + if ( distance < levels[ i ].distance ) { + + break; } - }; + } - }() ), + return levels[ i - 1 ].object; - clone: function () { + }, - return new this.constructor( this.geometry, this.material ).copy( this ); + raycast: ( function () { - } + var matrixPosition = new Vector3(); - } ); + return function raycast( raycaster, intersects ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + matrixPosition.setFromMatrixPosition( this.matrixWorld ); - function LineSegments( geometry, material ) { + var distance = raycaster.ray.origin.distanceTo( matrixPosition ); - Line.call( this, geometry, material ); + this.getObjectForDistance( distance ).raycast( raycaster, intersects ); - this.type = 'LineSegments'; + }; - } + }() ), - LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { + update: function () { - constructor: LineSegments, + var v1 = new Vector3(); + var v2 = new Vector3(); - isLineSegments: true + return function update( camera ) { - } ); + var levels = this.levels; - /** - * @author mgreter / http://github.com/mgreter - */ + if ( levels.length > 1 ) { - function LineLoop( geometry, material ) { + v1.setFromMatrixPosition( camera.matrixWorld ); + v2.setFromMatrixPosition( this.matrixWorld ); - Line.call( this, geometry, material ); + var distance = v1.distanceTo( v2 ); - this.type = 'LineLoop'; + levels[ 0 ].object.visible = true; - } + for ( var i = 1, l = levels.length; i < l; i ++ ) { - LineLoop.prototype = Object.assign( Object.create( Line.prototype ), { + if ( distance >= levels[ i ].distance ) { - constructor: LineLoop, + levels[ i - 1 ].object.visible = false; + levels[ i ].object.visible = true; - isLineLoop: true, + } else { - } ); + break; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * map: new THREE.Texture( ), - * - * size: , - * sizeAttenuation: - * } - */ + } - function PointsMaterial( parameters ) { + } - Material.call( this ); + for ( ; i < l; i ++ ) { - this.type = 'PointsMaterial'; + levels[ i ].object.visible = false; - this.color = new Color( 0xffffff ); + } - this.map = null; + } - this.size = 1; - this.sizeAttenuation = true; + }; - this.lights = false; + }(), - this.setValues( parameters ); + toJSON: function ( meta ) { - } + var data = Object3D.prototype.toJSON.call( this, meta ); - PointsMaterial.prototype = Object.create( Material.prototype ); - PointsMaterial.prototype.constructor = PointsMaterial; + data.object.levels = []; - PointsMaterial.prototype.isPointsMaterial = true; + var levels = this.levels; - PointsMaterial.prototype.copy = function ( source ) { + for ( var i = 0, l = levels.length; i < l; i ++ ) { - Material.prototype.copy.call( this, source ); + var level = levels[ i ]; - this.color.copy( source.color ); + data.object.levels.push( { + object: level.object.uuid, + distance: level.distance + } ); - this.map = source.map; + } - this.size = source.size; - this.sizeAttenuation = source.sizeAttenuation; + return data; - return this; + } - }; + } ); /** + * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ + * @author michael guerrero / http://realitymeltdown.com + * @author ikerr / http://verold.com */ - function Points( geometry, material ) { - - Object3D.call( this ); - - this.type = 'Points'; - - this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); - this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } ); + function Skeleton( bones, boneInverses ) { - } + // copy the bone array - Points.prototype = Object.assign( Object.create( Object3D.prototype ), { + bones = bones || []; - constructor: Points, + this.bones = bones.slice( 0 ); + this.boneMatrices = new Float32Array( this.bones.length * 16 ); - isPoints: true, + // use the supplied bone inverses or calculate the inverses - raycast: ( function () { + if ( boneInverses === undefined ) { - var inverseMatrix = new Matrix4(); - var ray = new Ray(); - var sphere = new Sphere(); + this.calculateInverses(); - return function raycast( raycaster, intersects ) { + } else { - var object = this; - var geometry = this.geometry; - var matrixWorld = this.matrixWorld; - var threshold = raycaster.params.Points.threshold; + if ( this.bones.length === boneInverses.length ) { - // Checking boundingSphere distance to ray + this.boneInverses = boneInverses.slice( 0 ); - if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); + } else { - sphere.copy( geometry.boundingSphere ); - sphere.applyMatrix4( matrixWorld ); - sphere.radius += threshold; + console.warn( 'THREE.Skeleton boneInverses is the wrong length.' ); - if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; + this.boneInverses = []; - // + for ( var i = 0, il = this.bones.length; i < il; i ++ ) { - inverseMatrix.getInverse( matrixWorld ); - ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); + this.boneInverses.push( new Matrix4() ); - var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); - var localThresholdSq = localThreshold * localThreshold; - var position = new Vector3(); + } - function testPoint( point, index ) { + } - var rayPointDistanceSq = ray.distanceSqToPoint( point ); + } - if ( rayPointDistanceSq < localThresholdSq ) { + } - var intersectPoint = ray.closestPointToPoint( point ); - intersectPoint.applyMatrix4( matrixWorld ); + Object.assign( Skeleton.prototype, { - var distance = raycaster.ray.origin.distanceTo( intersectPoint ); + calculateInverses: function () { - if ( distance < raycaster.near || distance > raycaster.far ) return; + this.boneInverses = []; - intersects.push( { + for ( var i = 0, il = this.bones.length; i < il; i ++ ) { - distance: distance, - distanceToRay: Math.sqrt( rayPointDistanceSq ), - point: intersectPoint.clone(), - index: index, - face: null, - object: object + var inverse = new Matrix4(); - } ); + if ( this.bones[ i ] ) { - } + inverse.getInverse( this.bones[ i ].matrixWorld ); } - if ( geometry.isBufferGeometry ) { + this.boneInverses.push( inverse ); - var index = geometry.index; - var attributes = geometry.attributes; - var positions = attributes.position.array; + } - if ( index !== null ) { + }, - var indices = index.array; + pose: function () { - for ( var i = 0, il = indices.length; i < il; i ++ ) { + var bone, i, il; - var a = indices[ i ]; + // recover the bind-time world matrices - position.fromArray( positions, a * 3 ); + for ( i = 0, il = this.bones.length; i < il; i ++ ) { - testPoint( position, a ); + bone = this.bones[ i ]; - } + if ( bone ) { - } else { + bone.matrixWorld.getInverse( this.boneInverses[ i ] ); - for ( var i = 0, l = positions.length / 3; i < l; i ++ ) { + } - position.fromArray( positions, i * 3 ); + } - testPoint( position, i ); + // compute the local matrices, positions, rotations and scales - } + for ( i = 0, il = this.bones.length; i < il; i ++ ) { - } + bone = this.bones[ i ]; - } else { + if ( bone ) { - var vertices = geometry.vertices; + if ( bone.parent && bone.parent.isBone ) { - for ( var i = 0, l = vertices.length; i < l; i ++ ) { + bone.matrix.getInverse( bone.parent.matrixWorld ); + bone.matrix.multiply( bone.matrixWorld ); - testPoint( vertices[ i ], i ); + } else { + + bone.matrix.copy( bone.matrixWorld ); } + bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); + } - }; + } - }() ), + }, - clone: function () { + update: ( function () { - return new this.constructor( this.geometry, this.material ).copy( this ); + var offsetMatrix = new Matrix4(); + var identityMatrix = new Matrix4(); - } + return function update() { - } ); + var bones = this.bones; + var boneInverses = this.boneInverses; + var boneMatrices = this.boneMatrices; + var boneTexture = this.boneTexture; - /** - * @author mrdoob / http://mrdoob.com/ - */ + // flatten bone matrices to array - function Group() { + for ( var i = 0, il = bones.length; i < il; i ++ ) { - Object3D.call( this ); + // compute the offset between the current and the original transform - this.type = 'Group'; + var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix; - } + offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] ); + offsetMatrix.toArray( boneMatrices, i * 16 ); - Group.prototype = Object.assign( Object.create( Object3D.prototype ), { + } - constructor: Group + if ( boneTexture !== undefined ) { - } ); + boneTexture.needsUpdate = true; - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + }; - Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + } )(), - this.generateMipmaps = false; + clone: function () { - var scope = this; + return new Skeleton( this.bones, this.boneInverses ); - function update() { + }, - requestAnimationFrame( update ); + getBoneByName: function ( name ) { - if ( video.readyState >= video.HAVE_CURRENT_DATA ) { + for ( var i = 0, il = this.bones.length; i < il; i ++ ) { - scope.needsUpdate = true; + var bone = this.bones[ i ]; - } + if ( bone.name === name ) { - } + return bone; - update(); + } - } + } + + return undefined; + + } - VideoTexture.prototype = Object.create( Texture.prototype ); - VideoTexture.prototype.constructor = VideoTexture; + } ); /** + * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com */ - function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { - - Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - - this.image = { width: width, height: height }; - this.mipmaps = mipmaps; + function Bone() { - // no flipping for cube textures - // (also flipping doesn't work for compressed textures ) + Object3D.call( this ); - this.flipY = false; + this.type = 'Bone'; - // can't generate mipmaps for compressed textures - // mips must be embedded in DDS files + } - this.generateMipmaps = false; + Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { - } + constructor: Bone, - CompressedTexture.prototype = Object.create( Texture.prototype ); - CompressedTexture.prototype.constructor = CompressedTexture; + isBone: true - CompressedTexture.prototype.isCompressedTexture = true; + } ); /** - * @author mrdoob / http://mrdoob.com/ + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author ikerr / http://verold.com */ - function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { + function SkinnedMesh( geometry, material ) { - Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + Mesh.call( this, geometry, material ); - this.needsUpdate = true; + this.type = 'SkinnedMesh'; - } + this.bindMode = 'attached'; + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); - CanvasTexture.prototype = Object.create( Texture.prototype ); - CanvasTexture.prototype.constructor = CanvasTexture; + var bones = this.initBones(); + var skeleton = new Skeleton( bones ); - /** - * @author Matt DesLauriers / @mattdesl - * @author atix / arthursilber.de - */ + this.bind( skeleton, this.matrixWorld ); - function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { + this.normalizeSkinWeights(); - format = format !== undefined ? format : DepthFormat; + } - if ( format !== DepthFormat && format !== DepthStencilFormat ) { + SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { - throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ) + constructor: SkinnedMesh, - } + isSkinnedMesh: true, - if ( type === undefined && format === DepthFormat ) type = UnsignedShortType; - if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type; + initBones: function () { - Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); + var bones = [], bone, gbone; + var i, il; - this.image = { width: width, height: height }; + if ( this.geometry && this.geometry.bones !== undefined ) { - this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; - this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + // first, create array of 'Bone' objects from geometry data - this.flipY = false; - this.generateMipmaps = false; + for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) { - } + gbone = this.geometry.bones[ i ]; - DepthTexture.prototype = Object.create( Texture.prototype ); - DepthTexture.prototype.constructor = DepthTexture; - DepthTexture.prototype.isDepthTexture = true; - - /** - * @author mrdoob / http://mrdoob.com/ - * @author Mugen87 / https://github.com/Mugen87 - */ + // create new 'Bone' object - function WireframeGeometry( geometry ) { + bone = new Bone(); + bones.push( bone ); - BufferGeometry.call( this ); + // apply values - this.type = 'WireframeGeometry'; + bone.name = gbone.name; + bone.position.fromArray( gbone.pos ); + bone.quaternion.fromArray( gbone.rotq ); + if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl ); - // buffer + } - var vertices = []; + // second, create bone hierarchy - // helper variables + for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) { - var i, j, l, o, ol; - var edge = [ 0, 0 ], edges = {}, e, edge1, edge2; - var key, keys = [ 'a', 'b', 'c' ]; - var vertex; + gbone = this.geometry.bones[ i ]; - // different logic for Geometry and BufferGeometry + if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) { - if ( geometry && geometry.isGeometry ) { + // subsequent bones in the hierarchy - // create a data structure that contains all edges without duplicates + bones[ gbone.parent ].add( bones[ i ] ); - var faces = geometry.faces; + } else { - for ( i = 0, l = faces.length; i < l; i ++ ) { + // topmost bone, immediate child of the skinned mesh - var face = faces[ i ]; + this.add( bones[ i ] ); - for ( j = 0; j < 3; j ++ ) { + } - edge1 = face[ keys[ j ] ]; - edge2 = face[ keys[ ( j + 1 ) % 3 ] ]; - edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates - edge[ 1 ] = Math.max( edge1, edge2 ); + } - key = edge[ 0 ] + ',' + edge[ 1 ]; + } - if ( edges[ key ] === undefined ) { + // now the bones are part of the scene graph and children of the skinned mesh. + // let's update the corresponding matrices - edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] }; + this.updateMatrixWorld( true ); - } + return bones; - } + }, - } + bind: function ( skeleton, bindMatrix ) { - // generate vertices + this.skeleton = skeleton; - for ( key in edges ) { + if ( bindMatrix === undefined ) { - e = edges[ key ]; + this.updateMatrixWorld( true ); - vertex = geometry.vertices[ e.index1 ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + this.skeleton.calculateInverses(); - vertex = geometry.vertices[ e.index2 ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + bindMatrix = this.matrixWorld; } - } else if ( geometry && geometry.isBufferGeometry ) { + this.bindMatrix.copy( bindMatrix ); + this.bindMatrixInverse.getInverse( bindMatrix ); - var position, indices, groups; - var group, start, count; - var index1, index2; + }, - vertex = new Vector3(); + pose: function () { - if ( geometry.index !== null ) { + this.skeleton.pose(); - // indexed BufferGeometry + }, - position = geometry.attributes.position; - indices = geometry.index; - groups = geometry.groups; + normalizeSkinWeights: function () { - if ( groups.length === 0 ) { + var scale, i; - groups = [ { start: 0, count: indices.count, materialIndex: 0 } ]; + if ( this.geometry && this.geometry.isGeometry ) { - } + for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) { - // create a data structure that contains all eges without duplicates + var sw = this.geometry.skinWeights[ i ]; - for ( o = 0, ol = groups.length; o < ol; ++ o ) { + scale = 1.0 / sw.manhattanLength(); - group = groups[ o ]; + if ( scale !== Infinity ) { - start = group.start; - count = group.count; + sw.multiplyScalar( scale ); - for ( i = start, l = ( start + count ); i < l; i += 3 ) { + } else { - for ( j = 0; j < 3; j ++ ) { + sw.set( 1, 0, 0, 0 ); // do something reasonable - edge1 = indices.getX( i + j ); - edge2 = indices.getX( i + ( j + 1 ) % 3 ); - edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates - edge[ 1 ] = Math.max( edge1, edge2 ); + } - key = edge[ 0 ] + ',' + edge[ 1 ]; + } - if ( edges[ key ] === undefined ) { + } else if ( this.geometry && this.geometry.isBufferGeometry ) { - edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] }; + var vec = new Vector4(); - } + var skinWeight = this.geometry.attributes.skinWeight; - } + for ( i = 0; i < skinWeight.count; i ++ ) { - } + vec.x = skinWeight.getX( i ); + vec.y = skinWeight.getY( i ); + vec.z = skinWeight.getZ( i ); + vec.w = skinWeight.getW( i ); - } + scale = 1.0 / vec.manhattanLength(); - // generate vertices + if ( scale !== Infinity ) { - for ( key in edges ) { + vec.multiplyScalar( scale ); - e = edges[ key ]; + } else { - vertex.fromBufferAttribute( position, e.index1 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + vec.set( 1, 0, 0, 0 ); // do something reasonable - vertex.fromBufferAttribute( position, e.index2 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + } + + skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w ); } - } else { + } - // non-indexed BufferGeometry + }, - position = geometry.attributes.position; + updateMatrixWorld: function ( force ) { - for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) { + Mesh.prototype.updateMatrixWorld.call( this, force ); - for ( j = 0; j < 3; j ++ ) { + if ( this.bindMode === 'attached' ) { - // three edges per triangle, an edge is represented as (index1, index2) - // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0) + this.bindMatrixInverse.getInverse( this.matrixWorld ); - index1 = 3 * i + j; - vertex.fromBufferAttribute( position, index1 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + } else if ( this.bindMode === 'detached' ) { - index2 = 3 * i + ( ( j + 1 ) % 3 ); - vertex.fromBufferAttribute( position, index2 ); - vertices.push( vertex.x, vertex.y, vertex.z ); + this.bindMatrixInverse.getInverse( this.bindMatrix ); - } + } else { - } + console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode ); } - } + }, - // build geometry + clone: function () { - this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + return new this.constructor( this.geometry, this.material ).copy( this ); - } + } - WireframeGeometry.prototype = Object.create( BufferGeometry.prototype ); - WireframeGeometry.prototype.constructor = WireframeGeometry; + } ); /** - * @author zz85 / https://github.com/zz85 - * @author Mugen87 / https://github.com/Mugen87 + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ * - * Parametric Surfaces Geometry - * based on the brilliant article by @prideout http://prideout.net/blog/?p=44 + * parameters = { + * color: , + * opacity: , + * + * linewidth: , + * linecap: "round", + * linejoin: "round" + * } */ - // ParametricGeometry + function LineBasicMaterial( parameters ) { - function ParametricGeometry( func, slices, stacks ) { + Material.call( this ); - Geometry.call( this ); + this.type = 'LineBasicMaterial'; - this.type = 'ParametricGeometry'; + this.color = new Color( 0xffffff ); - this.parameters = { - func: func, - slices: slices, - stacks: stacks - }; + this.linewidth = 1; + this.linecap = 'round'; + this.linejoin = 'round'; - this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) ); - this.mergeVertices(); + this.lights = false; + + this.setValues( parameters ); } - ParametricGeometry.prototype = Object.create( Geometry.prototype ); - ParametricGeometry.prototype.constructor = ParametricGeometry; + LineBasicMaterial.prototype = Object.create( Material.prototype ); + LineBasicMaterial.prototype.constructor = LineBasicMaterial; - // ParametricBufferGeometry + LineBasicMaterial.prototype.isLineBasicMaterial = true; - function ParametricBufferGeometry( func, slices, stacks ) { + LineBasicMaterial.prototype.copy = function ( source ) { - BufferGeometry.call( this ); + Material.prototype.copy.call( this, source ); - this.type = 'ParametricBufferGeometry'; + this.color.copy( source.color ); - this.parameters = { - func: func, - slices: slices, - stacks: stacks - }; + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; - // buffers + return this; - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + }; - var EPS = 0.00001; + /** + * @author mrdoob / http://mrdoob.com/ + */ - var normal = new Vector3(); + function Line( geometry, material, mode ) { - var p0 = new Vector3(), p1 = new Vector3(); - var pu = new Vector3(), pv = new Vector3(); + if ( mode === 1 ) { - var i, j; + console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' ); + return new LineSegments( geometry, material ); - // generate vertices, normals and uvs + } - var sliceCount = slices + 1; + Object3D.call( this ); - for ( i = 0; i <= stacks; i ++ ) { + this.type = 'Line'; - var v = i / stacks; + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } ); - for ( j = 0; j <= slices; j ++ ) { + } - var u = j / slices; + Line.prototype = Object.assign( Object.create( Object3D.prototype ), { - // vertex + constructor: Line, - p0 = func( u, v, p0 ); - vertices.push( p0.x, p0.y, p0.z ); + isLine: true, - // normal + computeLineDistances: ( function () { - // approximate tangent vectors via finite differences + var start = new Vector3(); + var end = new Vector3(); - if ( u - EPS >= 0 ) { + return function computeLineDistances() { - p1 = func( u - EPS, v, p1 ); - pu.subVectors( p0, p1 ); + var geometry = this.geometry; - } else { + if ( geometry.isBufferGeometry ) { - p1 = func( u + EPS, v, p1 ); - pu.subVectors( p1, p0 ); + // we assume non-indexed geometry - } + if ( geometry.index === null ) { - if ( v - EPS >= 0 ) { + var positionAttribute = geometry.attributes.position; + var lineDistances = [ 0 ]; - p1 = func( u, v - EPS, p1 ); - pv.subVectors( p0, p1 ); + for ( var i = 1, l = positionAttribute.count; i < l; i ++ ) { - } else { + start.fromBufferAttribute( positionAttribute, i - 1 ); + end.fromBufferAttribute( positionAttribute, i ); - p1 = func( u, v + EPS, p1 ); - pv.subVectors( p1, p0 ); + lineDistances[ i ] = lineDistances[ i - 1 ]; + lineDistances[ i ] += start.distanceTo( end ); - } + } - // cross product of tangent vectors returns surface normal + geometry.addAttribute( 'lineDistance', new THREE.Float32BufferAttribute( lineDistances, 1 ) ); - normal.crossVectors( pu, pv ).normalize(); - normals.push( normal.x, normal.y, normal.z ); + } else { - // uv + console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); - uvs.push( u, v ); + } - } + } else if ( geometry.isGeometry ) { - } + var vertices = geometry.vertices; + var lineDistances = geometry.lineDistances; - // generate indices + lineDistances[ 0 ] = 0; - for ( i = 0; i < stacks; i ++ ) { + for ( var i = 1, l = vertices.length; i < l; i ++ ) { - for ( j = 0; j < slices; j ++ ) { + lineDistances[ i ] = lineDistances[ i - 1 ]; + lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] ); - var a = i * sliceCount + j; - var b = i * sliceCount + j + 1; - var c = ( i + 1 ) * sliceCount + j + 1; - var d = ( i + 1 ) * sliceCount + j; + } - // faces one and two + } - indices.push( a, b, d ); - indices.push( b, c, d ); + return this; - } + }; - } + }() ), - // build geometry + raycast: ( function () { - this.setIndex( indices ); - this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - } + return function raycast( raycaster, intersects ) { - ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry; + var precision = raycaster.linePrecision; + var precisionSq = precision * precision; - /** - * @author clockworkgeek / https://github.com/clockworkgeek - * @author timothypratley / https://github.com/timothypratley - * @author WestLangley / http://github.com/WestLangley - * @author Mugen87 / https://github.com/Mugen87 - */ + var geometry = this.geometry; + var matrixWorld = this.matrixWorld; - // PolyhedronGeometry + // Checking boundingSphere distance to ray - function PolyhedronGeometry( vertices, indices, radius, detail ) { + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - Geometry.call( this ); + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); - this.type = 'PolyhedronGeometry'; + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; - this.parameters = { - vertices: vertices, - indices: indices, - radius: radius, - detail: detail - }; + // - this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) ); - this.mergeVertices(); + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - } + var vStart = new Vector3(); + var vEnd = new Vector3(); + var interSegment = new Vector3(); + var interRay = new Vector3(); + var step = ( this && this.isLineSegments ) ? 2 : 1; - PolyhedronGeometry.prototype = Object.create( Geometry.prototype ); - PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; + if ( geometry.isBufferGeometry ) { - // PolyhedronBufferGeometry + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - function PolyhedronBufferGeometry( vertices, indices, radius, detail ) { + if ( index !== null ) { - BufferGeometry.call( this ); + var indices = index.array; - this.type = 'PolyhedronBufferGeometry'; + for ( var i = 0, l = indices.length - 1; i < l; i += step ) { - this.parameters = { - vertices: vertices, - indices: indices, - radius: radius, - detail: detail - }; + var a = indices[ i ]; + var b = indices[ i + 1 ]; - radius = radius || 1; - detail = detail || 0; + vStart.fromArray( positions, a * 3 ); + vEnd.fromArray( positions, b * 3 ); - // default buffer data + var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - var vertexBuffer = []; - var uvBuffer = []; + if ( distSq > precisionSq ) continue; - // the subdivision creates the vertex buffer data + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - subdivide( detail ); + var distance = raycaster.ray.origin.distanceTo( interRay ); - // all vertices should lie on a conceptual sphere with a given radius + if ( distance < raycaster.near || distance > raycaster.far ) continue; - appplyRadius( radius ); + intersects.push( { - // finally, create the uv data + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - generateUVs(); + } ); - // build non-indexed geometry + } - this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) ); - this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) ); - this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) ); + } else { - if ( detail === 0 ) { + for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) { - this.computeVertexNormals(); // flat normals + vStart.fromArray( positions, 3 * i ); + vEnd.fromArray( positions, 3 * i + 3 ); - } else { + var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); - this.normalizeNormals(); // smooth normals + if ( distSq > precisionSq ) continue; - } + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - // helper functions + var distance = raycaster.ray.origin.distanceTo( interRay ); - function subdivide( detail ) { + if ( distance < raycaster.near || distance > raycaster.far ) continue; - var a = new Vector3(); - var b = new Vector3(); - var c = new Vector3(); + intersects.push( { - // iterate over all faces and apply a subdivison with the given detail value + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - for ( var i = 0; i < indices.length; i += 3 ) { + } ); - // get the vertices of the face + } - getVertexByIndex( indices[ i + 0 ], a ); - getVertexByIndex( indices[ i + 1 ], b ); - getVertexByIndex( indices[ i + 2 ], c ); + } - // perform subdivision + } else if ( geometry.isGeometry ) { - subdivideFace( a, b, c, detail ); + var vertices = geometry.vertices; + var nbVertices = vertices.length; - } + for ( var i = 0; i < nbVertices - 1; i += step ) { - } + var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); - function subdivideFace( a, b, c, detail ) { + if ( distSq > precisionSq ) continue; - var cols = Math.pow( 2, detail ); + interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation - // we use this multidimensional array as a data structure for creating the subdivision + var distance = raycaster.ray.origin.distanceTo( interRay ); - var v = []; + if ( distance < raycaster.near || distance > raycaster.far ) continue; - var i, j; + intersects.push( { - // construct all of the vertices for this subdivision + distance: distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4( this.matrixWorld ), + index: i, + face: null, + faceIndex: null, + object: this - for ( i = 0; i <= cols; i ++ ) { + } ); - v[ i ] = []; + } - var aj = a.clone().lerp( c, i / cols ); - var bj = b.clone().lerp( c, i / cols ); + } - var rows = cols - i; + }; - for ( j = 0; j <= rows; j ++ ) { + }() ), - if ( j === 0 && i === cols ) { + clone: function () { - v[ i ][ j ] = aj; + return new this.constructor( this.geometry, this.material ).copy( this ); - } else { + } - v[ i ][ j ] = aj.clone().lerp( bj, j / rows ); + } ); - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - } + function LineSegments( geometry, material ) { - } + Line.call( this, geometry, material ); - // construct all of the faces + this.type = 'LineSegments'; - for ( i = 0; i < cols; i ++ ) { + } - for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { + LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { - var k = Math.floor( j / 2 ); + constructor: LineSegments, - if ( j % 2 === 0 ) { + isLineSegments: true, - pushVertex( v[ i ][ k + 1 ] ); - pushVertex( v[ i + 1 ][ k ] ); - pushVertex( v[ i ][ k ] ); + computeLineDistances: ( function () { - } else { + var start = new Vector3(); + var end = new Vector3(); - pushVertex( v[ i ][ k + 1 ] ); - pushVertex( v[ i + 1 ][ k + 1 ] ); - pushVertex( v[ i + 1 ][ k ] ); + return function computeLineDistances() { - } + var geometry = this.geometry; - } + if ( geometry.isBufferGeometry ) { - } + // we assume non-indexed geometry - } + if ( geometry.index === null ) { - function appplyRadius( radius ) { + var positionAttribute = geometry.attributes.position; + var lineDistances = []; - var vertex = new Vector3(); + for ( var i = 0, l = positionAttribute.count; i < l; i += 2 ) { - // iterate over the entire buffer and apply the radius to each vertex + start.fromBufferAttribute( positionAttribute, i ); + end.fromBufferAttribute( positionAttribute, i + 1 ); - for ( var i = 0; i < vertexBuffer.length; i += 3 ) { + lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; + lineDistances[ i + 1 ] = lineDistances[ i ] + start.distanceTo( end ); - vertex.x = vertexBuffer[ i + 0 ]; - vertex.y = vertexBuffer[ i + 1 ]; - vertex.z = vertexBuffer[ i + 2 ]; + } - vertex.normalize().multiplyScalar( radius ); + geometry.addAttribute( 'lineDistance', new THREE.Float32BufferAttribute( lineDistances, 1 ) ); - vertexBuffer[ i + 0 ] = vertex.x; - vertexBuffer[ i + 1 ] = vertex.y; - vertexBuffer[ i + 2 ] = vertex.z; + } else { - } + console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); - } + } - function generateUVs() { + } else if ( geometry.isGeometry ) { - var vertex = new Vector3(); + var vertices = geometry.vertices; + var lineDistances = geometry.lineDistances; - for ( var i = 0; i < vertexBuffer.length; i += 3 ) { + for ( var i = 0, l = vertices.length; i < l; i += 2 ) { - vertex.x = vertexBuffer[ i + 0 ]; - vertex.y = vertexBuffer[ i + 1 ]; - vertex.z = vertexBuffer[ i + 2 ]; + start.copy( vertices[ i ] ); + end.copy( vertices[ i + 1 ] ); - var u = azimuth( vertex ) / 2 / Math.PI + 0.5; - var v = inclination( vertex ) / Math.PI + 0.5; - uvBuffer.push( u, 1 - v ); + lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; + lineDistances[ i + 1 ] = lineDistances[ i ] + start.distanceTo( end ); - } + } - correctUVs(); + } - correctSeam(); + return this; - } + }; - function correctSeam() { + }() ) - // handle case when face straddles the seam, see #3269 + } ); - for ( var i = 0; i < uvBuffer.length; i += 6 ) { + /** + * @author mgreter / http://github.com/mgreter + */ - // uv data of a single face + function LineLoop( geometry, material ) { - var x0 = uvBuffer[ i + 0 ]; - var x1 = uvBuffer[ i + 2 ]; - var x2 = uvBuffer[ i + 4 ]; + Line.call( this, geometry, material ); - var max = Math.max( x0, x1, x2 ); - var min = Math.min( x0, x1, x2 ); + this.type = 'LineLoop'; - // 0.9 is somewhat arbitrary + } - if ( max > 0.9 && min < 0.1 ) { + LineLoop.prototype = Object.assign( Object.create( Line.prototype ), { - if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1; - if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1; - if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1; + constructor: LineLoop, - } + isLineLoop: true, - } + } ); - } + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * map: new THREE.Texture( ), + * + * size: , + * sizeAttenuation: + * } + */ - function pushVertex( vertex ) { + function PointsMaterial( parameters ) { - vertexBuffer.push( vertex.x, vertex.y, vertex.z ); + Material.call( this ); - } + this.type = 'PointsMaterial'; - function getVertexByIndex( index, vertex ) { + this.color = new Color( 0xffffff ); - var stride = index * 3; + this.map = null; - vertex.x = vertices[ stride + 0 ]; - vertex.y = vertices[ stride + 1 ]; - vertex.z = vertices[ stride + 2 ]; + this.size = 1; + this.sizeAttenuation = true; - } + this.lights = false; - function correctUVs() { + this.setValues( parameters ); - var a = new Vector3(); - var b = new Vector3(); - var c = new Vector3(); + } - var centroid = new Vector3(); + PointsMaterial.prototype = Object.create( Material.prototype ); + PointsMaterial.prototype.constructor = PointsMaterial; - var uvA = new Vector2(); - var uvB = new Vector2(); - var uvC = new Vector2(); + PointsMaterial.prototype.isPointsMaterial = true; - for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) { + PointsMaterial.prototype.copy = function ( source ) { - a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] ); - b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] ); - c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] ); + Material.prototype.copy.call( this, source ); - uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] ); - uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] ); - uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] ); + this.color.copy( source.color ); - centroid.copy( a ).add( b ).add( c ).divideScalar( 3 ); + this.map = source.map; - var azi = azimuth( centroid ); + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; - correctUV( uvA, j + 0, a, azi ); - correctUV( uvB, j + 2, b, azi ); - correctUV( uvC, j + 4, c, azi ); + return this; - } + }; - } + /** + * @author alteredq / http://alteredqualia.com/ + */ - function correctUV( uv, stride, vector, azimuth ) { + function Points( geometry, material ) { - if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) { + Object3D.call( this ); - uvBuffer[ stride ] = uv.x - 1; + this.type = 'Points'; - } + this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); + this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } ); - if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) { + } - uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5; + Points.prototype = Object.assign( Object.create( Object3D.prototype ), { - } + constructor: Points, - } + isPoints: true, - // Angle around the Y axis, counter-clockwise when looking from above. + raycast: ( function () { - function azimuth( vector ) { + var inverseMatrix = new Matrix4(); + var ray = new Ray(); + var sphere = new Sphere(); - return Math.atan2( vector.z, - vector.x ); + return function raycast( raycaster, intersects ) { - } + var object = this; + var geometry = this.geometry; + var matrixWorld = this.matrixWorld; + var threshold = raycaster.params.Points.threshold; + // Checking boundingSphere distance to ray - // Angle above the XZ plane. + if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere(); - function inclination( vector ) { + sphere.copy( geometry.boundingSphere ); + sphere.applyMatrix4( matrixWorld ); + sphere.radius += threshold; - return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); + if ( raycaster.ray.intersectsSphere( sphere ) === false ) return; - } + // - } + inverseMatrix.getInverse( matrixWorld ); + ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); - PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry; + var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); + var localThresholdSq = localThreshold * localThreshold; + var position = new Vector3(); + var intersectPoint = new Vector3(); - /** - * @author timothypratley / https://github.com/timothypratley - * @author Mugen87 / https://github.com/Mugen87 - */ + function testPoint( point, index ) { - // TetrahedronGeometry + var rayPointDistanceSq = ray.distanceSqToPoint( point ); - function TetrahedronGeometry( radius, detail ) { + if ( rayPointDistanceSq < localThresholdSq ) { - Geometry.call( this ); + ray.closestPointToPoint( point, intersectPoint ); + intersectPoint.applyMatrix4( matrixWorld ); - this.type = 'TetrahedronGeometry'; + var distance = raycaster.ray.origin.distanceTo( intersectPoint ); - this.parameters = { - radius: radius, - detail: detail - }; + if ( distance < raycaster.near || distance > raycaster.far ) return; - this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) ); - this.mergeVertices(); + intersects.push( { - } + distance: distance, + distanceToRay: Math.sqrt( rayPointDistanceSq ), + point: intersectPoint.clone(), + index: index, + face: null, + object: object - TetrahedronGeometry.prototype = Object.create( Geometry.prototype ); - TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; + } ); - // TetrahedronBufferGeometry + } - function TetrahedronBufferGeometry( radius, detail ) { + } - var vertices = [ - 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 - ]; + if ( geometry.isBufferGeometry ) { - var indices = [ - 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 - ]; + var index = geometry.index; + var attributes = geometry.attributes; + var positions = attributes.position.array; - PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); + if ( index !== null ) { - this.type = 'TetrahedronBufferGeometry'; + var indices = index.array; - this.parameters = { - radius: radius, - detail: detail - }; + for ( var i = 0, il = indices.length; i < il; i ++ ) { - } + var a = indices[ i ]; - TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); - TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry; + position.fromArray( positions, a * 3 ); - /** - * @author timothypratley / https://github.com/timothypratley - * @author Mugen87 / https://github.com/Mugen87 - */ + testPoint( position, a ); - // OctahedronGeometry + } - function OctahedronGeometry( radius, detail ) { + } else { - Geometry.call( this ); + for ( var i = 0, l = positions.length / 3; i < l; i ++ ) { - this.type = 'OctahedronGeometry'; + position.fromArray( positions, i * 3 ); - this.parameters = { - radius: radius, - detail: detail - }; + testPoint( position, i ); - this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) ); - this.mergeVertices(); + } - } + } - OctahedronGeometry.prototype = Object.create( Geometry.prototype ); - OctahedronGeometry.prototype.constructor = OctahedronGeometry; + } else { - // OctahedronBufferGeometry + var vertices = geometry.vertices; - function OctahedronBufferGeometry( radius, detail ) { + for ( var i = 0, l = vertices.length; i < l; i ++ ) { - var vertices = [ - 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1 - ]; + testPoint( vertices[ i ], i ); - var indices = [ - 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2 - ]; + } - PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); + } - this.type = 'OctahedronBufferGeometry'; + }; - this.parameters = { - radius: radius, - detail: detail - }; + }() ), - } + clone: function () { - OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); - OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry; + return new this.constructor( this.geometry, this.material ).copy( this ); + + } + + } ); /** - * @author timothypratley / https://github.com/timothypratley - * @author Mugen87 / https://github.com/Mugen87 + * @author mrdoob / http://mrdoob.com/ */ - // IcosahedronGeometry + function Group() { - function IcosahedronGeometry( radius, detail ) { + Object3D.call( this ); - Geometry.call( this ); + this.type = 'Group'; - this.type = 'IcosahedronGeometry'; + } - this.parameters = { - radius: radius, - detail: detail - }; + Group.prototype = Object.assign( Object.create( Object3D.prototype ), { - this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) ); - this.mergeVertices(); + constructor: Group, - } + isGroup: true - IcosahedronGeometry.prototype = Object.create( Geometry.prototype ); - IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; + } ); - // IcosahedronBufferGeometry + /** + * @author mrdoob / http://mrdoob.com/ + */ - function IcosahedronBufferGeometry( radius, detail ) { + function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { - var t = ( 1 + Math.sqrt( 5 ) ) / 2; + Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - var vertices = [ - - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0, - 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, - t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1 - ]; + this.generateMipmaps = false; - var indices = [ - 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, - 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, - 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, - 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 - ]; + } - PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); + VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), { - this.type = 'IcosahedronBufferGeometry'; + constructor: VideoTexture, - this.parameters = { - radius: radius, - detail: detail - }; + isVideoTexture: true, - } + update: function () { - IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); - IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry; + var video = this.image; + + if ( video.readyState >= video.HAVE_CURRENT_DATA ) { + + this.needsUpdate = true; + + } + + } + + } ); /** - * @author Abe Pazos / https://hamoid.com - * @author Mugen87 / https://github.com/Mugen87 + * @author alteredq / http://alteredqualia.com/ */ - // DodecahedronGeometry + function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { - function DodecahedronGeometry( radius, detail ) { + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); - Geometry.call( this ); + this.image = { width: width, height: height }; + this.mipmaps = mipmaps; - this.type = 'DodecahedronGeometry'; + // no flipping for cube textures + // (also flipping doesn't work for compressed textures ) - this.parameters = { - radius: radius, - detail: detail - }; + this.flipY = false; - this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) ); - this.mergeVertices(); + // can't generate mipmaps for compressed textures + // mips must be embedded in DDS files + + this.generateMipmaps = false; } - DodecahedronGeometry.prototype = Object.create( Geometry.prototype ); - DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; + CompressedTexture.prototype = Object.create( Texture.prototype ); + CompressedTexture.prototype.constructor = CompressedTexture; - // DodecahedronBufferGeometry + CompressedTexture.prototype.isCompressedTexture = true; - function DodecahedronBufferGeometry( radius, detail ) { + /** + * @author Matt DesLauriers / @mattdesl + * @author atix / arthursilber.de + */ - var t = ( 1 + Math.sqrt( 5 ) ) / 2; - var r = 1 / t; + function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { - var vertices = [ + format = format !== undefined ? format : DepthFormat; - // (±1, ±1, ±1) - - 1, - 1, - 1, - 1, - 1, 1, - - 1, 1, - 1, - 1, 1, 1, - 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, 1, 1, 1, + if ( format !== DepthFormat && format !== DepthStencilFormat ) { - // (0, ±1/φ, ±φ) - 0, - r, - t, 0, - r, t, - 0, r, - t, 0, r, t, + throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ); - // (±1/φ, ±φ, 0) - - r, - t, 0, - r, t, 0, - r, - t, 0, r, t, 0, + } - // (±φ, 0, ±1/φ) - - t, 0, - r, t, 0, - r, - - t, 0, r, t, 0, r - ]; + if ( type === undefined && format === DepthFormat ) type = UnsignedShortType; + if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type; - var indices = [ - 3, 11, 7, 3, 7, 15, 3, 15, 13, - 7, 19, 17, 7, 17, 6, 7, 6, 15, - 17, 4, 8, 17, 8, 10, 17, 10, 6, - 8, 0, 16, 8, 16, 2, 8, 2, 10, - 0, 12, 1, 0, 1, 18, 0, 18, 16, - 6, 10, 2, 6, 2, 13, 6, 13, 15, - 2, 16, 18, 2, 18, 3, 2, 3, 13, - 18, 1, 9, 18, 9, 11, 18, 11, 3, - 4, 14, 12, 4, 12, 0, 4, 0, 8, - 11, 9, 5, 11, 5, 19, 11, 19, 7, - 19, 5, 14, 19, 14, 4, 19, 4, 17, - 1, 12, 14, 1, 14, 5, 1, 5, 9 - ]; + Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); - PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); + this.image = { width: width, height: height }; - this.type = 'DodecahedronBufferGeometry'; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; - this.parameters = { - radius: radius, - detail: detail - }; + this.flipY = false; + this.generateMipmaps = false; } - DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); - DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry; + DepthTexture.prototype = Object.create( Texture.prototype ); + DepthTexture.prototype.constructor = DepthTexture; + DepthTexture.prototype.isDepthTexture = true; /** - * @author oosmoxiecode / https://github.com/oosmoxiecode - * @author WestLangley / https://github.com/WestLangley - * @author zz85 / https://github.com/zz85 - * @author miningold / https://github.com/miningold - * @author jonobr1 / https://github.com/jonobr1 + * @author mrdoob / http://mrdoob.com/ * @author Mugen87 / https://github.com/Mugen87 - * */ - // TubeGeometry + function WireframeGeometry( geometry ) { - function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) { + BufferGeometry.call( this ); - Geometry.call( this ); + this.type = 'WireframeGeometry'; - this.type = 'TubeGeometry'; + // buffer - this.parameters = { - path: path, - tubularSegments: tubularSegments, - radius: radius, - radialSegments: radialSegments, - closed: closed - }; + var vertices = []; - if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' ); + // helper variables - var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ); + var i, j, l, o, ol; + var edge = [ 0, 0 ], edges = {}, e, edge1, edge2; + var key, keys = [ 'a', 'b', 'c' ]; + var vertex; - // expose internals + // different logic for Geometry and BufferGeometry - this.tangents = bufferGeometry.tangents; - this.normals = bufferGeometry.normals; - this.binormals = bufferGeometry.binormals; + if ( geometry && geometry.isGeometry ) { - // create geometry + // create a data structure that contains all edges without duplicates - this.fromBufferGeometry( bufferGeometry ); - this.mergeVertices(); + var faces = geometry.faces; - } + for ( i = 0, l = faces.length; i < l; i ++ ) { - TubeGeometry.prototype = Object.create( Geometry.prototype ); - TubeGeometry.prototype.constructor = TubeGeometry; + var face = faces[ i ]; - // TubeBufferGeometry + for ( j = 0; j < 3; j ++ ) { - function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) { + edge1 = face[ keys[ j ] ]; + edge2 = face[ keys[ ( j + 1 ) % 3 ] ]; + edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates + edge[ 1 ] = Math.max( edge1, edge2 ); - BufferGeometry.call( this ); + key = edge[ 0 ] + ',' + edge[ 1 ]; - this.type = 'TubeBufferGeometry'; + if ( edges[ key ] === undefined ) { - this.parameters = { - path: path, - tubularSegments: tubularSegments, - radius: radius, - radialSegments: radialSegments, - closed: closed - }; + edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] }; - tubularSegments = tubularSegments || 64; - radius = radius || 1; - radialSegments = radialSegments || 8; - closed = closed || false; + } - var frames = path.computeFrenetFrames( tubularSegments, closed ); + } - // expose internals + } - this.tangents = frames.tangents; - this.normals = frames.normals; - this.binormals = frames.binormals; + // generate vertices - // helper variables + for ( key in edges ) { - var vertex = new Vector3(); - var normal = new Vector3(); - var uv = new Vector2(); - - var i, j; + e = edges[ key ]; - // buffer + vertex = geometry.vertices[ e.index1 ]; + vertices.push( vertex.x, vertex.y, vertex.z ); - var vertices = []; - var normals = []; - var uvs = []; - var indices = []; + vertex = geometry.vertices[ e.index2 ]; + vertices.push( vertex.x, vertex.y, vertex.z ); - // create buffer data + } - generateBufferData(); + } else if ( geometry && geometry.isBufferGeometry ) { - // build geometry + var position, indices, groups; + var group, start, count; + var index1, index2; - this.setIndex( indices ); - this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + vertex = new Vector3(); - // functions + if ( geometry.index !== null ) { - function generateBufferData() { + // indexed BufferGeometry - for ( i = 0; i < tubularSegments; i ++ ) { + position = geometry.attributes.position; + indices = geometry.index; + groups = geometry.groups; - generateSegment( i ); + if ( groups.length === 0 ) { - } + groups = [ { start: 0, count: indices.count, materialIndex: 0 } ]; - // if the geometry is not closed, generate the last row of vertices and normals - // at the regular position on the given path - // - // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ) + } - generateSegment( ( closed === false ) ? tubularSegments : 0 ); + // create a data structure that contains all eges without duplicates - // uvs are generated in a separate function. - // this makes it easy compute correct values for closed geometries + for ( o = 0, ol = groups.length; o < ol; ++ o ) { - generateUVs(); + group = groups[ o ]; - // finally create faces + start = group.start; + count = group.count; - generateIndices(); + for ( i = start, l = ( start + count ); i < l; i += 3 ) { - } + for ( j = 0; j < 3; j ++ ) { - function generateSegment( i ) { + edge1 = indices.getX( i + j ); + edge2 = indices.getX( i + ( j + 1 ) % 3 ); + edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates + edge[ 1 ] = Math.max( edge1, edge2 ); - // we use getPointAt to sample evenly distributed points from the given path + key = edge[ 0 ] + ',' + edge[ 1 ]; - var P = path.getPointAt( i / tubularSegments ); + if ( edges[ key ] === undefined ) { - // retrieve corresponding normal and binormal + edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] }; - var N = frames.normals[ i ]; - var B = frames.binormals[ i ]; + } - // generate normals and vertices for the current segment + } - for ( j = 0; j <= radialSegments; j ++ ) { + } - var v = j / radialSegments * Math.PI * 2; + } - var sin = Math.sin( v ); - var cos = - Math.cos( v ); + // generate vertices - // normal + for ( key in edges ) { - normal.x = ( cos * N.x + sin * B.x ); - normal.y = ( cos * N.y + sin * B.y ); - normal.z = ( cos * N.z + sin * B.z ); - normal.normalize(); + e = edges[ key ]; - normals.push( normal.x, normal.y, normal.z ); + vertex.fromBufferAttribute( position, e.index1 ); + vertices.push( vertex.x, vertex.y, vertex.z ); - // vertex + vertex.fromBufferAttribute( position, e.index2 ); + vertices.push( vertex.x, vertex.y, vertex.z ); - vertex.x = P.x + radius * normal.x; - vertex.y = P.y + radius * normal.y; - vertex.z = P.z + radius * normal.z; + } - vertices.push( vertex.x, vertex.y, vertex.z ); + } else { - } + // non-indexed BufferGeometry - } + position = geometry.attributes.position; - function generateIndices() { + for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) { - for ( j = 1; j <= tubularSegments; j ++ ) { + for ( j = 0; j < 3; j ++ ) { - for ( i = 1; i <= radialSegments; i ++ ) { + // three edges per triangle, an edge is represented as (index1, index2) + // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0) - var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); - var b = ( radialSegments + 1 ) * j + ( i - 1 ); - var c = ( radialSegments + 1 ) * j + i; - var d = ( radialSegments + 1 ) * ( j - 1 ) + i; + index1 = 3 * i + j; + vertex.fromBufferAttribute( position, index1 ); + vertices.push( vertex.x, vertex.y, vertex.z ); - // faces + index2 = 3 * i + ( ( j + 1 ) % 3 ); + vertex.fromBufferAttribute( position, index2 ); + vertices.push( vertex.x, vertex.y, vertex.z ); - indices.push( a, b, d ); - indices.push( b, c, d ); + } } @@ -25674,86 +25371,59 @@ } - function generateUVs() { - - for ( i = 0; i <= tubularSegments; i ++ ) { - - for ( j = 0; j <= radialSegments; j ++ ) { - - uv.x = i / tubularSegments; - uv.y = j / radialSegments; - - uvs.push( uv.x, uv.y ); - - } - - } + // build geometry - } + this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); } - TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - TubeBufferGeometry.prototype.constructor = TubeBufferGeometry; + WireframeGeometry.prototype = Object.create( BufferGeometry.prototype ); + WireframeGeometry.prototype.constructor = WireframeGeometry; /** - * @author oosmoxiecode + * @author zz85 / https://github.com/zz85 * @author Mugen87 / https://github.com/Mugen87 * - * based on http://www.blackpawn.com/texts/pqtorus/ + * Parametric Surfaces Geometry + * based on the brilliant article by @prideout http://prideout.net/blog/?p=44 */ - // TorusKnotGeometry + // ParametricGeometry - function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { + function ParametricGeometry( func, slices, stacks ) { Geometry.call( this ); - this.type = 'TorusKnotGeometry'; + this.type = 'ParametricGeometry'; this.parameters = { - radius: radius, - tube: tube, - tubularSegments: tubularSegments, - radialSegments: radialSegments, - p: p, - q: q + func: func, + slices: slices, + stacks: stacks }; - if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); - - this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); + this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) ); this.mergeVertices(); } - TorusKnotGeometry.prototype = Object.create( Geometry.prototype ); - TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; + ParametricGeometry.prototype = Object.create( Geometry.prototype ); + ParametricGeometry.prototype.constructor = ParametricGeometry; - // TorusKnotBufferGeometry + // ParametricBufferGeometry - function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) { + function ParametricBufferGeometry( func, slices, stacks ) { BufferGeometry.call( this ); - this.type = 'TorusKnotBufferGeometry'; + this.type = 'ParametricBufferGeometry'; this.parameters = { - radius: radius, - tube: tube, - tubularSegments: tubularSegments, - radialSegments: radialSegments, - p: p, - q: q + func: func, + slices: slices, + stacks: stacks }; - radius = radius || 100; - tube = tube || 40; - tubularSegments = Math.floor( tubularSegments ) || 64; - radialSegments = Math.floor( radialSegments ) || 8; - p = p || 2; - q = q || 3; - // buffers var indices = []; @@ -25761,74 +25431,68 @@ var normals = []; var uvs = []; - // helper variables - - var i, j; + var EPS = 0.00001; - var vertex = new Vector3(); var normal = new Vector3(); - var P1 = new Vector3(); - var P2 = new Vector3(); + var p0 = new Vector3(), p1 = new Vector3(); + var pu = new Vector3(), pv = new Vector3(); - var B = new Vector3(); - var T = new Vector3(); - var N = new Vector3(); + var i, j; // generate vertices, normals and uvs - for ( i = 0; i <= tubularSegments; ++ i ) { + var sliceCount = slices + 1; - // the radian "u" is used to calculate the position on the torus curve of the current tubular segement + for ( i = 0; i <= stacks; i ++ ) { - var u = i / tubularSegments * p * Math.PI * 2; + var v = i / stacks; - // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead. - // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions + for ( j = 0; j <= slices; j ++ ) { - calculatePositionOnCurve( u, p, q, radius, P1 ); - calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); + var u = j / slices; - // calculate orthonormal basis + // vertex - T.subVectors( P2, P1 ); - N.addVectors( P2, P1 ); - B.crossVectors( T, N ); - N.crossVectors( B, T ); + func( u, v, p0 ); + vertices.push( p0.x, p0.y, p0.z ); - // normalize B, N. T can be ignored, we don't use it + // normal - B.normalize(); - N.normalize(); + // approximate tangent vectors via finite differences - for ( j = 0; j <= radialSegments; ++ j ) { + if ( u - EPS >= 0 ) { - // now calculate the vertices. they are nothing more than an extrusion of the torus curve. - // because we extrude a shape in the xy-plane, there is no need to calculate a z-value. + func( u - EPS, v, p1 ); + pu.subVectors( p0, p1 ); - var v = j / radialSegments * Math.PI * 2; - var cx = - tube * Math.cos( v ); - var cy = tube * Math.sin( v ); + } else { - // now calculate the final vertex position. - // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve + func( u + EPS, v, p1 ); + pu.subVectors( p1, p0 ); - vertex.x = P1.x + ( cx * N.x + cy * B.x ); - vertex.y = P1.y + ( cx * N.y + cy * B.y ); - vertex.z = P1.z + ( cx * N.z + cy * B.z ); + } - vertices.push( vertex.x, vertex.y, vertex.z ); + if ( v - EPS >= 0 ) { - // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) + func( u, v - EPS, p1 ); + pv.subVectors( p0, p1 ); - normal.subVectors( vertex, P1 ).normalize(); + } else { + + func( u, v + EPS, p1 ); + pv.subVectors( p1, p0 ); + + } + + // cross product of tangent vectors returns surface normal + normal.crossVectors( pu, pv ).normalize(); normals.push( normal.x, normal.y, normal.z ); // uv - uvs.push( i / tubularSegments ); - uvs.push( j / radialSegments ); + uvs.push( u, v ); } @@ -25836,18 +25500,16 @@ // generate indices - for ( j = 1; j <= tubularSegments; j ++ ) { - - for ( i = 1; i <= radialSegments; i ++ ) { + for ( i = 0; i < stacks; i ++ ) { - // indices + for ( j = 0; j < slices; j ++ ) { - var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); - var b = ( radialSegments + 1 ) * j + ( i - 1 ); - var c = ( radialSegments + 1 ) * j + i; - var d = ( radialSegments + 1 ) * ( j - 1 ) + i; + var a = i * sliceCount + j; + var b = i * sliceCount + j + 1; + var c = ( i + 1 ) * sliceCount + j + 1; + var d = ( i + 1 ) * sliceCount + j; - // faces + // faces one and two indices.push( a, b, d ); indices.push( b, c, d ); @@ -25863,2884 +25525,2983 @@ this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - // this function calculates the current position on the torus curve - - function calculatePositionOnCurve( u, p, q, radius, position ) { - - var cu = Math.cos( u ); - var su = Math.sin( u ); - var quOverP = q / p * u; - var cs = Math.cos( quOverP ); - - position.x = radius * ( 2 + cs ) * 0.5 * cu; - position.y = radius * ( 2 + cs ) * su * 0.5; - position.z = radius * Math.sin( quOverP ) * 0.5; - - } - } - TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry; + ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry; /** - * @author oosmoxiecode - * @author mrdoob / http://mrdoob.com/ + * @author clockworkgeek / https://github.com/clockworkgeek + * @author timothypratley / https://github.com/timothypratley + * @author WestLangley / http://github.com/WestLangley * @author Mugen87 / https://github.com/Mugen87 */ - // TorusGeometry + // PolyhedronGeometry - function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) { + function PolyhedronGeometry( vertices, indices, radius, detail ) { Geometry.call( this ); - this.type = 'TorusGeometry'; + this.type = 'PolyhedronGeometry'; this.parameters = { + vertices: vertices, + indices: indices, radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - arc: arc + detail: detail }; - this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); + this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) ); this.mergeVertices(); } - TorusGeometry.prototype = Object.create( Geometry.prototype ); - TorusGeometry.prototype.constructor = TorusGeometry; + PolyhedronGeometry.prototype = Object.create( Geometry.prototype ); + PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; - // TorusBufferGeometry + // PolyhedronBufferGeometry - function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) { + function PolyhedronBufferGeometry( vertices, indices, radius, detail ) { BufferGeometry.call( this ); - this.type = 'TorusBufferGeometry'; + this.type = 'PolyhedronBufferGeometry'; this.parameters = { + vertices: vertices, + indices: indices, radius: radius, - tube: tube, - radialSegments: radialSegments, - tubularSegments: tubularSegments, - arc: arc + detail: detail }; - radius = radius || 100; - tube = tube || 40; - radialSegments = Math.floor( radialSegments ) || 8; - tubularSegments = Math.floor( tubularSegments ) || 6; - arc = arc || Math.PI * 2; - - // buffers - - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + radius = radius || 1; + detail = detail || 0; - // helper variables + // default buffer data - var center = new Vector3(); - var vertex = new Vector3(); - var normal = new Vector3(); + var vertexBuffer = []; + var uvBuffer = []; - var j, i; + // the subdivision creates the vertex buffer data - // generate vertices, normals and uvs + subdivide( detail ); - for ( j = 0; j <= radialSegments; j ++ ) { + // all vertices should lie on a conceptual sphere with a given radius - for ( i = 0; i <= tubularSegments; i ++ ) { + appplyRadius( radius ); - var u = i / tubularSegments * arc; - var v = j / radialSegments * Math.PI * 2; + // finally, create the uv data - // vertex + generateUVs(); - vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u ); - vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u ); - vertex.z = tube * Math.sin( v ); + // build non-indexed geometry - vertices.push( vertex.x, vertex.y, vertex.z ); + this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) ); + this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) ); + this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) ); - // normal + if ( detail === 0 ) { - center.x = radius * Math.cos( u ); - center.y = radius * Math.sin( u ); - normal.subVectors( vertex, center ).normalize(); + this.computeVertexNormals(); // flat normals - normals.push( normal.x, normal.y, normal.z ); + } else { - // uv + this.normalizeNormals(); // smooth normals - uvs.push( i / tubularSegments ); - uvs.push( j / radialSegments ); + } - } + // helper functions - } + function subdivide( detail ) { - // generate indices + var a = new Vector3(); + var b = new Vector3(); + var c = new Vector3(); - for ( j = 1; j <= radialSegments; j ++ ) { + // iterate over all faces and apply a subdivison with the given detail value - for ( i = 1; i <= tubularSegments; i ++ ) { + for ( var i = 0; i < indices.length; i += 3 ) { - // indices + // get the vertices of the face - var a = ( tubularSegments + 1 ) * j + i - 1; - var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; - var c = ( tubularSegments + 1 ) * ( j - 1 ) + i; - var d = ( tubularSegments + 1 ) * j + i; + getVertexByIndex( indices[ i + 0 ], a ); + getVertexByIndex( indices[ i + 1 ], b ); + getVertexByIndex( indices[ i + 2 ], c ); - // faces + // perform subdivision - indices.push( a, b, d ); - indices.push( b, c, d ); + subdivideFace( a, b, c, detail ); } } - // build geometry - - this.setIndex( indices ); - this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - - } - - TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - TorusBufferGeometry.prototype.constructor = TorusBufferGeometry; - - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - */ + function subdivideFace( a, b, c, detail ) { - var ShapeUtils = { + var cols = Math.pow( 2, detail ); - // calculate area of the contour polygon + // we use this multidimensional array as a data structure for creating the subdivision - area: function ( contour ) { + var v = []; - var n = contour.length; - var a = 0.0; + var i, j; - for ( var p = n - 1, q = 0; q < n; p = q ++ ) { + // construct all of the vertices for this subdivision - a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; + for ( i = 0; i <= cols; i ++ ) { - } + v[ i ] = []; - return a * 0.5; + var aj = a.clone().lerp( c, i / cols ); + var bj = b.clone().lerp( c, i / cols ); - }, + var rows = cols - i; - triangulate: ( function () { + for ( j = 0; j <= rows; j ++ ) { - /** - * This code is a quick port of code written in C++ which was submitted to - * flipcode.com by John W. Ratcliff // July 22, 2000 - * See original code and more information here: - * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml - * - * ported to actionscript by Zevan Rosser - * www.actionsnippet.com - * - * ported to javascript by Joshua Koo - * http://www.lab4games.net/zz85/blog - * - */ + if ( j === 0 && i === cols ) { - function snip( contour, u, v, w, n, verts ) { + v[ i ][ j ] = aj; - var p; - var ax, ay, bx, by; - var cx, cy, px, py; + } else { - ax = contour[ verts[ u ] ].x; - ay = contour[ verts[ u ] ].y; + v[ i ][ j ] = aj.clone().lerp( bj, j / rows ); - bx = contour[ verts[ v ] ].x; - by = contour[ verts[ v ] ].y; + } - cx = contour[ verts[ w ] ].x; - cy = contour[ verts[ w ] ].y; + } - if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false; + } - var aX, aY, bX, bY, cX, cY; - var apx, apy, bpx, bpy, cpx, cpy; - var cCROSSap, bCROSScp, aCROSSbp; + // construct all of the faces - aX = cx - bx; aY = cy - by; - bX = ax - cx; bY = ay - cy; - cX = bx - ax; cY = by - ay; + for ( i = 0; i < cols; i ++ ) { - for ( p = 0; p < n; p ++ ) { + for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { - px = contour[ verts[ p ] ].x; - py = contour[ verts[ p ] ].y; + var k = Math.floor( j / 2 ); - if ( ( ( px === ax ) && ( py === ay ) ) || - ( ( px === bx ) && ( py === by ) ) || - ( ( px === cx ) && ( py === cy ) ) ) continue; + if ( j % 2 === 0 ) { - apx = px - ax; apy = py - ay; - bpx = px - bx; bpy = py - by; - cpx = px - cx; cpy = py - cy; + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); + pushVertex( v[ i ][ k ] ); - // see if p is inside triangle abc + } else { - aCROSSbp = aX * bpy - aY * bpx; - cCROSSap = cX * apy - cY * apx; - bCROSScp = bX * cpy - bY * cpx; + pushVertex( v[ i ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k + 1 ] ); + pushVertex( v[ i + 1 ][ k ] ); - if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false; + } } - return true; - } - // takes in an contour array and returns + } - return function triangulate( contour, indices ) { + function appplyRadius( radius ) { - var n = contour.length; + var vertex = new Vector3(); - if ( n < 3 ) return null; + // iterate over the entire buffer and apply the radius to each vertex - var result = [], - verts = [], - vertIndices = []; + for ( var i = 0; i < vertexBuffer.length; i += 3 ) { - /* we want a counter-clockwise polygon in verts */ + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; - var u, v, w; + vertex.normalize().multiplyScalar( radius ); - if ( ShapeUtils.area( contour ) > 0.0 ) { + vertexBuffer[ i + 0 ] = vertex.x; + vertexBuffer[ i + 1 ] = vertex.y; + vertexBuffer[ i + 2 ] = vertex.z; - for ( v = 0; v < n; v ++ ) verts[ v ] = v; + } - } else { + } - for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v; + function generateUVs() { - } + var vertex = new Vector3(); - var nv = n; + for ( var i = 0; i < vertexBuffer.length; i += 3 ) { - /* remove nv - 2 vertices, creating 1 triangle every time */ + vertex.x = vertexBuffer[ i + 0 ]; + vertex.y = vertexBuffer[ i + 1 ]; + vertex.z = vertexBuffer[ i + 2 ]; - var count = 2 * nv; /* error detection */ + var u = azimuth( vertex ) / 2 / Math.PI + 0.5; + var v = inclination( vertex ) / Math.PI + 0.5; + uvBuffer.push( u, 1 - v ); - for ( v = nv - 1; nv > 2; ) { + } - /* if we loop, it is probably a non-simple polygon */ + correctUVs(); - if ( ( count -- ) <= 0 ) { + correctSeam(); - //** Triangulate: ERROR - probable bad polygon! + } - //throw ( "Warning, unable to triangulate polygon!" ); - //return null; - // Sometimes warning is fine, especially polygons are triangulated in reverse. - console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' ); + function correctSeam() { - if ( indices ) return vertIndices; - return result; + // handle case when face straddles the seam, see #3269 - } + for ( var i = 0; i < uvBuffer.length; i += 6 ) { - /* three consecutive vertices in current polygon, */ + // uv data of a single face - u = v; if ( nv <= u ) u = 0; /* previous */ - v = u + 1; if ( nv <= v ) v = 0; /* new v */ - w = v + 1; if ( nv <= w ) w = 0; /* next */ + var x0 = uvBuffer[ i + 0 ]; + var x1 = uvBuffer[ i + 2 ]; + var x2 = uvBuffer[ i + 4 ]; - if ( snip( contour, u, v, w, nv, verts ) ) { + var max = Math.max( x0, x1, x2 ); + var min = Math.min( x0, x1, x2 ); - var a, b, c, s, t; + // 0.9 is somewhat arbitrary - /* true names of the vertices */ + if ( max > 0.9 && min < 0.1 ) { - a = verts[ u ]; - b = verts[ v ]; - c = verts[ w ]; + if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1; + if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1; + if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1; - /* output Triangle */ + } - result.push( [ contour[ a ], - contour[ b ], - contour[ c ] ] ); + } + } - vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] ); + function pushVertex( vertex ) { - /* remove v from the remaining polygon */ + vertexBuffer.push( vertex.x, vertex.y, vertex.z ); - for ( s = v, t = v + 1; t < nv; s ++, t ++ ) { + } - verts[ s ] = verts[ t ]; + function getVertexByIndex( index, vertex ) { - } + var stride = index * 3; - nv --; + vertex.x = vertices[ stride + 0 ]; + vertex.y = vertices[ stride + 1 ]; + vertex.z = vertices[ stride + 2 ]; - /* reset error detection counter */ + } - count = 2 * nv; + function correctUVs() { - } + var a = new Vector3(); + var b = new Vector3(); + var c = new Vector3(); - } + var centroid = new Vector3(); - if ( indices ) return vertIndices; - return result; + var uvA = new Vector2(); + var uvB = new Vector2(); + var uvC = new Vector2(); - } + for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) { - } )(), + a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] ); + b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] ); + c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] ); - triangulateShape: function ( contour, holes ) { + uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] ); + uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] ); + uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] ); - function removeDupEndPts(points) { + centroid.copy( a ).add( b ).add( c ).divideScalar( 3 ); - var l = points.length; + var azi = azimuth( centroid ); - if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { + correctUV( uvA, j + 0, a, azi ); + correctUV( uvB, j + 2, b, azi ); + correctUV( uvC, j + 4, c, azi ); - points.pop(); + } - } + } - } + function correctUV( uv, stride, vector, azimuth ) { - removeDupEndPts( contour ); - holes.forEach( removeDupEndPts ); + if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) { - function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) { + uvBuffer[ stride ] = uv.x - 1; - // inOtherPt needs to be collinear to the inSegment - if ( inSegPt1.x !== inSegPt2.x ) { + } - if ( inSegPt1.x < inSegPt2.x ) { + if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) { - return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) ); + uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5; - } else { + } - return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) ); + } - } + // Angle around the Y axis, counter-clockwise when looking from above. - } else { + function azimuth( vector ) { - if ( inSegPt1.y < inSegPt2.y ) { + return Math.atan2( vector.z, - vector.x ); - return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) ); + } - } else { - return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) ); + // Angle above the XZ plane. - } + function inclination( vector ) { - } + return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); - } + } - function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) { + } - var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y; - var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y; + PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry; - var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x; - var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y; + /** + * @author timothypratley / https://github.com/timothypratley + * @author Mugen87 / https://github.com/Mugen87 + */ - var limit = seg1dy * seg2dx - seg1dx * seg2dy; - var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy; + // TetrahedronGeometry - if ( Math.abs( limit ) > Number.EPSILON ) { + function TetrahedronGeometry( radius, detail ) { - // not parallel + Geometry.call( this ); - var perpSeg2; - if ( limit > 0 ) { + this.type = 'TetrahedronGeometry'; - if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return []; - perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; - if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return []; + this.parameters = { + radius: radius, + detail: detail + }; - } else { + this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) ); + this.mergeVertices(); - if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return []; - perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy; - if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return []; + } - } + TetrahedronGeometry.prototype = Object.create( Geometry.prototype ); + TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; - // i.e. to reduce rounding errors - // intersection at endpoint of segment#1? - if ( perpSeg2 === 0 ) { + // TetrahedronBufferGeometry - if ( ( inExcludeAdjacentSegs ) && - ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return []; - return [ inSeg1Pt1 ]; + function TetrahedronBufferGeometry( radius, detail ) { - } - if ( perpSeg2 === limit ) { + var vertices = [ + 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 + ]; - if ( ( inExcludeAdjacentSegs ) && - ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return []; - return [ inSeg1Pt2 ]; + var indices = [ + 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 + ]; - } - // intersection at endpoint of segment#2? - if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ]; - if ( perpSeg1 === limit ) return [ inSeg2Pt2 ]; + PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); - // return real intersection point - var factorSeg1 = perpSeg2 / limit; - return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx, - y: inSeg1Pt1.y + factorSeg1 * seg1dy } ]; + this.type = 'TetrahedronBufferGeometry'; - } else { + this.parameters = { + radius: radius, + detail: detail + }; - // parallel or collinear - if ( ( perpSeg1 !== 0 ) || - ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return []; + } - // they are collinear or degenerate - var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point? - var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point? - // both segments are points - if ( seg1Pt && seg2Pt ) { + TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); + TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry; - if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) || - ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points - return [ inSeg1Pt1 ]; // they are the same point + /** + * @author timothypratley / https://github.com/timothypratley + * @author Mugen87 / https://github.com/Mugen87 + */ - } - // segment#1 is a single point - if ( seg1Pt ) { + // OctahedronGeometry - if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2 - return [ inSeg1Pt1 ]; + function OctahedronGeometry( radius, detail ) { - } - // segment#2 is a single point - if ( seg2Pt ) { + Geometry.call( this ); - if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1 - return [ inSeg2Pt1 ]; + this.type = 'OctahedronGeometry'; - } + this.parameters = { + radius: radius, + detail: detail + }; - // they are collinear segments, which might overlap - var seg1min, seg1max, seg1minVal, seg1maxVal; - var seg2min, seg2max, seg2minVal, seg2maxVal; - if ( seg1dx !== 0 ) { + this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) ); + this.mergeVertices(); - // the segments are NOT on a vertical line - if ( inSeg1Pt1.x < inSeg1Pt2.x ) { + } - seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x; - seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x; + OctahedronGeometry.prototype = Object.create( Geometry.prototype ); + OctahedronGeometry.prototype.constructor = OctahedronGeometry; - } else { + // OctahedronBufferGeometry - seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x; - seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x; + function OctahedronBufferGeometry( radius, detail ) { - } - if ( inSeg2Pt1.x < inSeg2Pt2.x ) { + var vertices = [ + 1, 0, 0, - 1, 0, 0, 0, 1, 0, + 0, - 1, 0, 0, 0, 1, 0, 0, - 1 + ]; - seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x; - seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x; + var indices = [ + 0, 2, 4, 0, 4, 3, 0, 3, 5, + 0, 5, 2, 1, 2, 5, 1, 5, 3, + 1, 3, 4, 1, 4, 2 + ]; - } else { + PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); - seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x; - seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x; + this.type = 'OctahedronBufferGeometry'; - } + this.parameters = { + radius: radius, + detail: detail + }; - } else { + } - // the segments are on a vertical line - if ( inSeg1Pt1.y < inSeg1Pt2.y ) { + OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); + OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry; - seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y; - seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y; + /** + * @author timothypratley / https://github.com/timothypratley + * @author Mugen87 / https://github.com/Mugen87 + */ - } else { + // IcosahedronGeometry - seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y; - seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y; + function IcosahedronGeometry( radius, detail ) { - } - if ( inSeg2Pt1.y < inSeg2Pt2.y ) { + Geometry.call( this ); - seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y; - seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y; + this.type = 'IcosahedronGeometry'; - } else { + this.parameters = { + radius: radius, + detail: detail + }; - seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y; - seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y; + this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) ); + this.mergeVertices(); - } + } - } - if ( seg1minVal <= seg2minVal ) { + IcosahedronGeometry.prototype = Object.create( Geometry.prototype ); + IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; - if ( seg1maxVal < seg2minVal ) return []; - if ( seg1maxVal === seg2minVal ) { + // IcosahedronBufferGeometry - if ( inExcludeAdjacentSegs ) return []; - return [ seg2min ]; + function IcosahedronBufferGeometry( radius, detail ) { - } - if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ]; - return [ seg2min, seg2max ]; + var t = ( 1 + Math.sqrt( 5 ) ) / 2; - } else { + var vertices = [ + - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0, + 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, + t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1 + ]; - if ( seg1minVal > seg2maxVal ) return []; - if ( seg1minVal === seg2maxVal ) { + var indices = [ + 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, + 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, + 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, + 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 + ]; - if ( inExcludeAdjacentSegs ) return []; - return [ seg1min ]; + PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); - } - if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ]; - return [ seg1min, seg2max ]; + this.type = 'IcosahedronBufferGeometry'; - } + this.parameters = { + radius: radius, + detail: detail + }; - } + } - } + IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); + IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry; - function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) { + /** + * @author Abe Pazos / https://hamoid.com + * @author Mugen87 / https://github.com/Mugen87 + */ - // The order of legs is important + // DodecahedronGeometry - // translation of all points, so that Vertex is at (0,0) - var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y; - var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y; - var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y; + function DodecahedronGeometry( radius, detail ) { - // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg. - var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX; - var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX; + Geometry.call( this ); - if ( Math.abs( from2toAngle ) > Number.EPSILON ) { + this.type = 'DodecahedronGeometry'; - // angle != 180 deg. + this.parameters = { + radius: radius, + detail: detail + }; - var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX; - // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle ); + this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) ); + this.mergeVertices(); - if ( from2toAngle > 0 ) { + } - // main angle < 180 deg. - return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) ); + DodecahedronGeometry.prototype = Object.create( Geometry.prototype ); + DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; - } else { + // DodecahedronBufferGeometry - // main angle > 180 deg. - return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) ); + function DodecahedronBufferGeometry( radius, detail ) { - } + var t = ( 1 + Math.sqrt( 5 ) ) / 2; + var r = 1 / t; - } else { + var vertices = [ - // angle == 180 deg. - // console.log( "from2to: 180 deg., from2other: " + from2otherAngle ); - return ( from2otherAngle > 0 ); + // (±1, ±1, ±1) + - 1, - 1, - 1, - 1, - 1, 1, + - 1, 1, - 1, - 1, 1, 1, + 1, - 1, - 1, 1, - 1, 1, + 1, 1, - 1, 1, 1, 1, - } + // (0, ±1/φ, ±φ) + 0, - r, - t, 0, - r, t, + 0, r, - t, 0, r, t, - } + // (±1/φ, ±φ, 0) + - r, - t, 0, - r, t, 0, + r, - t, 0, r, t, 0, + // (±φ, 0, ±1/φ) + - t, 0, - r, t, 0, - r, + - t, 0, r, t, 0, r + ]; - function removeHoles( contour, holes ) { + var indices = [ + 3, 11, 7, 3, 7, 15, 3, 15, 13, + 7, 19, 17, 7, 17, 6, 7, 6, 15, + 17, 4, 8, 17, 8, 10, 17, 10, 6, + 8, 0, 16, 8, 16, 2, 8, 2, 10, + 0, 12, 1, 0, 1, 18, 0, 18, 16, + 6, 10, 2, 6, 2, 13, 6, 13, 15, + 2, 16, 18, 2, 18, 3, 2, 3, 13, + 18, 1, 9, 18, 9, 11, 18, 11, 3, + 4, 14, 12, 4, 12, 0, 4, 0, 8, + 11, 9, 5, 11, 5, 19, 11, 19, 7, + 19, 5, 14, 19, 14, 4, 19, 4, 17, + 1, 12, 14, 1, 14, 5, 1, 5, 9 + ]; - var shape = contour.concat(); // work on this shape - var hole; + PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); - function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) { + this.type = 'DodecahedronBufferGeometry'; - // Check if hole point lies within angle around shape point - var lastShapeIdx = shape.length - 1; + this.parameters = { + radius: radius, + detail: detail + }; - var prevShapeIdx = inShapeIdx - 1; - if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx; + } - var nextShapeIdx = inShapeIdx + 1; - if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0; + DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); + DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry; - var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] ); - if ( ! insideAngle ) { + /** + * @author oosmoxiecode / https://github.com/oosmoxiecode + * @author WestLangley / https://github.com/WestLangley + * @author zz85 / https://github.com/zz85 + * @author miningold / https://github.com/miningold + * @author jonobr1 / https://github.com/jonobr1 + * @author Mugen87 / https://github.com/Mugen87 + * + */ - // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y ); - return false; + // TubeGeometry - } + function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) { - // Check if shape point lies within angle around hole point - var lastHoleIdx = hole.length - 1; + Geometry.call( this ); - var prevHoleIdx = inHoleIdx - 1; - if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx; + this.type = 'TubeGeometry'; - var nextHoleIdx = inHoleIdx + 1; - if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0; + this.parameters = { + path: path, + tubularSegments: tubularSegments, + radius: radius, + radialSegments: radialSegments, + closed: closed + }; - insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] ); - if ( ! insideAngle ) { + if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' ); - // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y ); - return false; + var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ); - } + // expose internals - return true; + this.tangents = bufferGeometry.tangents; + this.normals = bufferGeometry.normals; + this.binormals = bufferGeometry.binormals; - } + // create geometry - function intersectsShapeEdge( inShapePt, inHolePt ) { + this.fromBufferGeometry( bufferGeometry ); + this.mergeVertices(); - // checks for intersections with shape edges - var sIdx, nextIdx, intersection; - for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) { + } - nextIdx = sIdx + 1; nextIdx %= shape.length; - intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true ); - if ( intersection.length > 0 ) return true; + TubeGeometry.prototype = Object.create( Geometry.prototype ); + TubeGeometry.prototype.constructor = TubeGeometry; - } + // TubeBufferGeometry - return false; + function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) { - } + BufferGeometry.call( this ); - var indepHoles = []; + this.type = 'TubeBufferGeometry'; - function intersectsHoleEdge( inShapePt, inHolePt ) { + this.parameters = { + path: path, + tubularSegments: tubularSegments, + radius: radius, + radialSegments: radialSegments, + closed: closed + }; - // checks for intersections with hole edges - var ihIdx, chkHole, - hIdx, nextIdx, intersection; - for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) { + tubularSegments = tubularSegments || 64; + radius = radius || 1; + radialSegments = radialSegments || 8; + closed = closed || false; - chkHole = holes[ indepHoles[ ihIdx ]]; - for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) { + var frames = path.computeFrenetFrames( tubularSegments, closed ); - nextIdx = hIdx + 1; nextIdx %= chkHole.length; - intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true ); - if ( intersection.length > 0 ) return true; + // expose internals - } + this.tangents = frames.tangents; + this.normals = frames.normals; + this.binormals = frames.binormals; - } - return false; + // helper variables - } + var vertex = new Vector3(); + var normal = new Vector3(); + var uv = new Vector2(); + var P = new Vector3(); - var holeIndex, shapeIndex, - shapePt, holePt, - holeIdx, cutKey, failedCuts = [], - tmpShape1, tmpShape2, - tmpHole1, tmpHole2; + var i, j; - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { + // buffer - indepHoles.push( h ); + var vertices = []; + var normals = []; + var uvs = []; + var indices = []; - } + // create buffer data - var minShapeIndex = 0; - var counter = indepHoles.length * 2; - while ( indepHoles.length > 0 ) { + generateBufferData(); - counter --; - if ( counter < 0 ) { + // build geometry - console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" ); - break; + this.setIndex( indices ); + this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - } + // functions - // search for shape-vertex and hole-vertex, - // which can be connected without intersections - for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) { + function generateBufferData() { - shapePt = shape[ shapeIndex ]; - holeIndex = - 1; + for ( i = 0; i < tubularSegments; i ++ ) { - // search for hole which can be reached without intersections - for ( var h = 0; h < indepHoles.length; h ++ ) { + generateSegment( i ); - holeIdx = indepHoles[ h ]; + } - // prevent multiple checks - cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx; - if ( failedCuts[ cutKey ] !== undefined ) continue; + // if the geometry is not closed, generate the last row of vertices and normals + // at the regular position on the given path + // + // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ) - hole = holes[ holeIdx ]; - for ( var h2 = 0; h2 < hole.length; h2 ++ ) { + generateSegment( ( closed === false ) ? tubularSegments : 0 ); - holePt = hole[ h2 ]; - if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue; - if ( intersectsShapeEdge( shapePt, holePt ) ) continue; - if ( intersectsHoleEdge( shapePt, holePt ) ) continue; + // uvs are generated in a separate function. + // this makes it easy compute correct values for closed geometries - holeIndex = h2; - indepHoles.splice( h, 1 ); + generateUVs(); - tmpShape1 = shape.slice( 0, shapeIndex + 1 ); - tmpShape2 = shape.slice( shapeIndex ); - tmpHole1 = hole.slice( holeIndex ); - tmpHole2 = hole.slice( 0, holeIndex + 1 ); + // finally create faces - shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 ); + generateIndices(); - minShapeIndex = shapeIndex; + } - // Debug only, to show the selected cuts - // glob_CutLines.push( [ shapePt, holePt ] ); + function generateSegment( i ) { - break; + // we use getPointAt to sample evenly distributed points from the given path - } - if ( holeIndex >= 0 ) break; // hole-vertex found + P = path.getPointAt( i / tubularSegments, P ); - failedCuts[ cutKey ] = true; // remember failure + // retrieve corresponding normal and binormal - } - if ( holeIndex >= 0 ) break; // hole-vertex found + var N = frames.normals[ i ]; + var B = frames.binormals[ i ]; - } + // generate normals and vertices for the current segment - } + for ( j = 0; j <= radialSegments; j ++ ) { - return shape; /* shape with no holes */ + var v = j / radialSegments * Math.PI * 2; - } + var sin = Math.sin( v ); + var cos = - Math.cos( v ); + // normal - var i, il, f, face, - key, index, - allPointsMap = {}; + normal.x = ( cos * N.x + sin * B.x ); + normal.y = ( cos * N.y + sin * B.y ); + normal.z = ( cos * N.z + sin * B.z ); + normal.normalize(); - // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first. + normals.push( normal.x, normal.y, normal.z ); - var allpoints = contour.concat(); + // vertex - for ( var h = 0, hl = holes.length; h < hl; h ++ ) { + vertex.x = P.x + radius * normal.x; + vertex.y = P.y + radius * normal.y; + vertex.z = P.z + radius * normal.z; - Array.prototype.push.apply( allpoints, holes[ h ] ); + vertices.push( vertex.x, vertex.y, vertex.z ); } - //console.log( "allpoints",allpoints, allpoints.length ); + } + + function generateIndices() { - // prepare all points map + for ( j = 1; j <= tubularSegments; j ++ ) { - for ( i = 0, il = allpoints.length; i < il; i ++ ) { + for ( i = 1; i <= radialSegments; i ++ ) { - key = allpoints[ i ].x + ":" + allpoints[ i ].y; + var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + var b = ( radialSegments + 1 ) * j + ( i - 1 ); + var c = ( radialSegments + 1 ) * j + i; + var d = ( radialSegments + 1 ) * ( j - 1 ) + i; - if ( allPointsMap[ key ] !== undefined ) { + // faces - console.warn( "THREE.ShapeUtils: Duplicate point", key, i ); + indices.push( a, b, d ); + indices.push( b, c, d ); } - allPointsMap[ key ] = i; - } - // remove holes by cutting paths to holes and adding them to the shape - var shapeWithoutHoles = removeHoles( contour, holes ); - - var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape - //console.log( "triangles",triangles, triangles.length ); - - // check all face vertices against all points map - - for ( i = 0, il = triangles.length; i < il; i ++ ) { - - face = triangles[ i ]; - - for ( f = 0; f < 3; f ++ ) { + } - key = face[ f ].x + ":" + face[ f ].y; + function generateUVs() { - index = allPointsMap[ key ]; + for ( i = 0; i <= tubularSegments; i ++ ) { - if ( index !== undefined ) { + for ( j = 0; j <= radialSegments; j ++ ) { - face[ f ] = index; + uv.x = i / tubularSegments; + uv.y = j / radialSegments; - } + uvs.push( uv.x, uv.y ); } } - return triangles.concat(); - - }, - - isClockWise: function ( pts ) { - - return ShapeUtils.area( pts ) < 0; - } - }; + } + + TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + TubeBufferGeometry.prototype.constructor = TubeBufferGeometry; /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - * Creates extruded geometry from a path shape. - * - * parameters = { - * - * curveSegments: , // number of points on the curves - * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too - * amount: , // Depth to extrude the shape - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into the original shape bevel goes - * bevelSize: , // how far from shape outline is bevel - * bevelSegments: , // number of bevel layers - * - * extrudePath: // curve to extrude shape along - * frames: // containing arrays of tangents, normals, binormals - * - * UVGenerator: // object that provides UV generator functions + * @author oosmoxiecode + * @author Mugen87 / https://github.com/Mugen87 * - * } + * based on http://www.blackpawn.com/texts/pqtorus/ */ - // ExtrudeGeometry + // TorusKnotGeometry - function ExtrudeGeometry( shapes, options ) { + function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { Geometry.call( this ); - this.type = 'ExtrudeGeometry'; + this.type = 'TorusKnotGeometry'; this.parameters = { - shapes: shapes, - options: options + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q }; - this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) ); + if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); + + this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); this.mergeVertices(); } - ExtrudeGeometry.prototype = Object.create( Geometry.prototype ); - ExtrudeGeometry.prototype.constructor = ExtrudeGeometry; + TorusKnotGeometry.prototype = Object.create( Geometry.prototype ); + TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; - // ExtrudeBufferGeometry + // TorusKnotBufferGeometry - function ExtrudeBufferGeometry( shapes, options ) { + function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) { - if ( typeof ( shapes ) === "undefined" ) { + BufferGeometry.call( this ); - return; + this.type = 'TorusKnotBufferGeometry'; - } + this.parameters = { + radius: radius, + tube: tube, + tubularSegments: tubularSegments, + radialSegments: radialSegments, + p: p, + q: q + }; - BufferGeometry.call( this ); + radius = radius || 1; + tube = tube || 0.4; + tubularSegments = Math.floor( tubularSegments ) || 64; + radialSegments = Math.floor( radialSegments ) || 8; + p = p || 2; + q = q || 3; - this.type = 'ExtrudeBufferGeometry'; + // buffers - shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; - this.addShapeList( shapes, options ); + // helper variables - this.computeVertexNormals(); + var i, j; - // can't really use automatic vertex normals - // as then front and back sides get smoothed too - // should do separate smoothing just for sides + var vertex = new Vector3(); + var normal = new Vector3(); - //this.computeVertexNormals(); + var P1 = new Vector3(); + var P2 = new Vector3(); - //console.log( "took", ( Date.now() - startTime ) ); + var B = new Vector3(); + var T = new Vector3(); + var N = new Vector3(); - } + // generate vertices, normals and uvs - ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry; + for ( i = 0; i <= tubularSegments; ++ i ) { - ExtrudeBufferGeometry.prototype.getArrays = function () { + // the radian "u" is used to calculate the position on the torus curve of the current tubular segement - var positionAttribute = this.getAttribute( "position" ); - var verticesArray = positionAttribute ? Array.prototype.slice.call( positionAttribute.array ) : []; + var u = i / tubularSegments * p * Math.PI * 2; - var uvAttribute = this.getAttribute( "uv" ); - var uvArray = uvAttribute ? Array.prototype.slice.call( uvAttribute.array ) : []; + // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead. + // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions - var IndexAttribute = this.index; - var indicesArray = IndexAttribute ? Array.prototype.slice.call( IndexAttribute.array ) : []; + calculatePositionOnCurve( u, p, q, radius, P1 ); + calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); - return { - position: verticesArray, - uv: uvArray, - index: indicesArray - }; + // calculate orthonormal basis - }; + T.subVectors( P2, P1 ); + N.addVectors( P2, P1 ); + B.crossVectors( T, N ); + N.crossVectors( B, T ); - ExtrudeBufferGeometry.prototype.addShapeList = function ( shapes, options ) { + // normalize B, N. T can be ignored, we don't use it - var sl = shapes.length; - options.arrays = this.getArrays(); + B.normalize(); + N.normalize(); - for ( var s = 0; s < sl; s ++ ) { + for ( j = 0; j <= radialSegments; ++ j ) { - var shape = shapes[ s ]; - this.addShape( shape, options ); + // now calculate the vertices. they are nothing more than an extrusion of the torus curve. + // because we extrude a shape in the xy-plane, there is no need to calculate a z-value. - } + var v = j / radialSegments * Math.PI * 2; + var cx = - tube * Math.cos( v ); + var cy = tube * Math.sin( v ); - this.setIndex( options.arrays.index ); - this.addAttribute( 'position', new Float32BufferAttribute( options.arrays.position, 3 ) ); - this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) ); + // now calculate the final vertex position. + // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve - }; + vertex.x = P1.x + ( cx * N.x + cy * B.x ); + vertex.y = P1.y + ( cx * N.y + cy * B.y ); + vertex.z = P1.z + ( cx * N.z + cy * B.z ); - ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) { + vertices.push( vertex.x, vertex.y, vertex.z ); - var arrays = options.arrays ? options.arrays : this.getArrays(); - var verticesArray = arrays.position; - var indicesArray = arrays.index; - var uvArray = arrays.uv; + // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) - var placeholder = []; + normal.subVectors( vertex, P1 ).normalize(); + normals.push( normal.x, normal.y, normal.z ); - var amount = options.amount !== undefined ? options.amount : 100; + // uv - var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10 - var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8 - var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); - var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false + } - var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + } - var steps = options.steps !== undefined ? options.steps : 1; + // generate indices - var extrudePath = options.extrudePath; - var extrudePts, extrudeByPath = false; + for ( j = 1; j <= tubularSegments; j ++ ) { - // Use default WorldUVGenerator if no UV generators are specified. - var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator; + for ( i = 1; i <= radialSegments; i ++ ) { - var splineTube, binormal, normal, position2; - if ( extrudePath ) { + // indices - extrudePts = extrudePath.getSpacedPoints( steps ); + var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); + var b = ( radialSegments + 1 ) * j + ( i - 1 ); + var c = ( radialSegments + 1 ) * j + i; + var d = ( radialSegments + 1 ) * ( j - 1 ) + i; - extrudeByPath = true; - bevelEnabled = false; // bevels not supported for path extrusion + // faces - // SETUP TNB variables + indices.push( a, b, d ); + indices.push( b, c, d ); - // TODO1 - have a .isClosed in spline? + } - splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false ); + } - // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); + // build geometry - binormal = new Vector3(); - normal = new Vector3(); - position2 = new Vector3(); + this.setIndex( indices ); + this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - } + // this function calculates the current position on the torus curve - // Safeguards if bevels are not enabled + function calculatePositionOnCurve( u, p, q, radius, position ) { - if ( ! bevelEnabled ) { + var cu = Math.cos( u ); + var su = Math.sin( u ); + var quOverP = q / p * u; + var cs = Math.cos( quOverP ); - bevelSegments = 0; - bevelThickness = 0; - bevelSize = 0; + position.x = radius * ( 2 + cs ) * 0.5 * cu; + position.y = radius * ( 2 + cs ) * su * 0.5; + position.z = radius * Math.sin( quOverP ) * 0.5; } - // Variables initialization - - var ahole, h, hl; // looping of holes - var scope = this; - - var shapePoints = shape.extractPoints( curveSegments ); + } - var vertices = shapePoints.shape; - var holes = shapePoints.holes; + TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry; - var reverse = ! ShapeUtils.isClockWise( vertices ); + /** + * @author oosmoxiecode + * @author mrdoob / http://mrdoob.com/ + * @author Mugen87 / https://github.com/Mugen87 + */ - if ( reverse ) { + // TorusGeometry - vertices = vertices.reverse(); + function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) { - // Maybe we should also check if holes are in the opposite direction, just to be safe ... + Geometry.call( this ); - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + this.type = 'TorusGeometry'; - ahole = holes[ h ]; + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; - if ( ShapeUtils.isClockWise( ahole ) ) { + this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); + this.mergeVertices(); - holes[ h ] = ahole.reverse(); + } - } + TorusGeometry.prototype = Object.create( Geometry.prototype ); + TorusGeometry.prototype.constructor = TorusGeometry; - } + // TorusBufferGeometry - } + function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) { + BufferGeometry.call( this ); - var faces = ShapeUtils.triangulateShape( vertices, holes ); + this.type = 'TorusBufferGeometry'; - /* Vertices */ + this.parameters = { + radius: radius, + tube: tube, + radialSegments: radialSegments, + tubularSegments: tubularSegments, + arc: arc + }; - var contour = vertices; // vertices has all points but contour has only points of circumference + radius = radius || 1; + tube = tube || 0.4; + radialSegments = Math.floor( radialSegments ) || 8; + tubularSegments = Math.floor( tubularSegments ) || 6; + arc = arc || Math.PI * 2; - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + // buffers - ahole = holes[ h ]; + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; - vertices = vertices.concat( ahole ); + // helper variables - } + var center = new Vector3(); + var vertex = new Vector3(); + var normal = new Vector3(); + var j, i; - function scalePt2( pt, vec, size ) { + // generate vertices, normals and uvs - if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" ); + for ( j = 0; j <= radialSegments; j ++ ) { - return vec.clone().multiplyScalar( size ).add( pt ); + for ( i = 0; i <= tubularSegments; i ++ ) { - } + var u = i / tubularSegments * arc; + var v = j / radialSegments * Math.PI * 2; - var b, bs, t, z, - vert, vlen = vertices.length, - face, flen = faces.length; + // vertex + vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u ); + vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u ); + vertex.z = tube * Math.sin( v ); - // Find directions for point movement + vertices.push( vertex.x, vertex.y, vertex.z ); + // normal - function getBevelVec( inPt, inPrev, inNext ) { + center.x = radius * Math.cos( u ); + center.y = radius * Math.sin( u ); + normal.subVectors( vertex, center ).normalize(); - // computes for inPt the corresponding point inPt' on a new contour - // shifted by 1 unit (length of normalized vector) to the left - // if we walk along contour clockwise, this new contour is outside the old one - // - // inPt' is the intersection of the two lines parallel to the two - // adjacent edges of inPt at a distance of 1 unit on the left side. + normals.push( normal.x, normal.y, normal.z ); - var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt + // uv - // good reading for geometry algorithms (here: line-line intersection) - // http://geomalgorithms.com/a05-_intersect-1.html + uvs.push( i / tubularSegments ); + uvs.push( j / radialSegments ); - var v_prev_x = inPt.x - inPrev.x, - v_prev_y = inPt.y - inPrev.y; - var v_next_x = inNext.x - inPt.x, - v_next_y = inNext.y - inPt.y; + } - var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); + } - // check for collinear edges - var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + // generate indices - if ( Math.abs( collinear0 ) > Number.EPSILON ) { + for ( j = 1; j <= radialSegments; j ++ ) { - // not collinear + for ( i = 1; i <= tubularSegments; i ++ ) { - // length of vectors for normalizing + // indices - var v_prev_len = Math.sqrt( v_prev_lensq ); - var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); + var a = ( tubularSegments + 1 ) * j + i - 1; + var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; + var c = ( tubularSegments + 1 ) * ( j - 1 ) + i; + var d = ( tubularSegments + 1 ) * j + i; - // shift adjacent points by unit vectors to the left + // faces - var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); - var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); + indices.push( a, b, d ); + indices.push( b, c, d ); - var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); - var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); + } - // scaling factor for v_prev to intersection point + } - var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - - ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / - ( v_prev_x * v_next_y - v_prev_y * v_next_x ); + // build geometry - // vector from inPt to intersection point + this.setIndex( indices ); + this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); - v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); - v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); + } - // Don't normalize!, otherwise sharp corners become ugly - // but prevent crazy spikes - var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); - if ( v_trans_lensq <= 2 ) { + TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + TorusBufferGeometry.prototype.constructor = TorusBufferGeometry; - return new Vector2( v_trans_x, v_trans_y ); + /** + * @author Mugen87 / https://github.com/Mugen87 + * Port from https://github.com/mapbox/earcut (v2.1.2) + */ - } else { + var Earcut = { - shrink_by = Math.sqrt( v_trans_lensq / 2 ); + triangulate: function ( data, holeIndices, dim ) { - } + dim = dim || 2; - } else { + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length, + outerNode = linkedList( data, 0, outerLen, dim, true ), + triangles = []; - // handle special case of collinear edges + if ( ! outerNode ) return triangles; - var direction_eq = false; // assumes: opposite - if ( v_prev_x > Number.EPSILON ) { + var minX, minY, maxX, maxY, x, y, invSize; - if ( v_next_x > Number.EPSILON ) { + if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); - direction_eq = true; + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox - } + if ( data.length > 80 * dim ) { - } else { + minX = maxX = data[ 0 ]; + minY = maxY = data[ 1 ]; - if ( v_prev_x < - Number.EPSILON ) { + for ( var i = dim; i < outerLen; i += dim ) { - if ( v_next_x < - Number.EPSILON ) { + x = data[ i ]; + y = data[ i + 1 ]; + if ( x < minX ) minX = x; + if ( y < minY ) minY = y; + if ( x > maxX ) maxX = x; + if ( y > maxY ) maxY = y; - direction_eq = true; + } - } + // minX, minY and invSize are later used to transform coords into integers for z-order calculation - } else { + invSize = Math.max( maxX - minX, maxY - minY ); + invSize = invSize !== 0 ? 1 / invSize : 0; - if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { + } - direction_eq = true; + earcutLinked( outerNode, triangles, dim, minX, minY, invSize ); - } + return triangles; - } + } - } + }; - if ( direction_eq ) { + // create a circular doubly linked list from polygon points in the specified winding order - // console.log("Warning: lines are a straight sequence"); - v_trans_x = - v_prev_y; - v_trans_y = v_prev_x; - shrink_by = Math.sqrt( v_prev_lensq ); + function linkedList( data, start, end, dim, clockwise ) { - } else { + var i, last; - // console.log("Warning: lines are a straight spike"); - v_trans_x = v_prev_x; - v_trans_y = v_prev_y; - shrink_by = Math.sqrt( v_prev_lensq / 2 ); + if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) { - } + for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); - } + } else { - return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); + for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last ); } + if ( last && equals( last, last.next ) ) { - var contourMovements = []; + removeNode( last ); + last = last.next; - for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + } - if ( j === il ) j = 0; - if ( k === il ) k = 0; + return last; - // (j)---(i)---(k) - // console.log('i,j,k', i, j , k) + } - contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); + // eliminate colinear or duplicate points - } + function filterPoints( start, end ) { - var holesMovements = [], - oneHoleMovements, verticesMovements = contourMovements.concat(); + if ( ! start ) return start; + if ( ! end ) end = start; - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + var p = start, again; - ahole = holes[ h ]; + do { - oneHoleMovements = []; + again = false; - for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { + if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { - if ( j === il ) j = 0; - if ( k === il ) k = 0; + removeNode( p ); + p = end = p.prev; + if ( p === p.next ) break; + again = true; - // (j)---(i)---(k) - oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); + } else { + + p = p.next; } - holesMovements.push( oneHoleMovements ); - verticesMovements = verticesMovements.concat( oneHoleMovements ); + } while ( again || p !== end ); - } + return end; + } - // Loop bevelSegments, 1 for the front, 1 for the back + // main ear slicing loop which triangulates a polygon (given as a linked list) - for ( b = 0; b < bevelSegments; b ++ ) { + function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) { - //for ( b = bevelSegments; b > 0; b -- ) { + if ( ! ear ) return; - t = b / bevelSegments; - z = bevelThickness * Math.cos( t * Math.PI / 2 ); - bs = bevelSize * Math.sin( t * Math.PI / 2 ); + // interlink polygon nodes in z-order - // contract shape + if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize ); - for ( i = 0, il = contour.length; i < il; i ++ ) { + var stop = ear, prev, next; - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + // iterate through ears, slicing them one by one - v( vert.x, vert.y, - z ); + while ( ear.prev !== ear.next ) { - } + prev = ear.prev; + next = ear.next; - // expand holes + if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) { - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + // cut off the triangle + triangles.push( prev.i / dim ); + triangles.push( ear.i / dim ); + triangles.push( next.i / dim ); - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + removeNode( ear ); - for ( i = 0, il = ahole.length; i < il; i ++ ) { + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + continue; - v( vert.x, vert.y, - z ); + } - } + ear = next; - } + // if we looped through the whole remaining polygon and can't find any more ears - } + if ( ear === stop ) { - bs = bevelSize; + // try filtering points and slicing again - // Back facing vertices + if ( ! pass ) { - for ( i = 0; i < vlen; i ++ ) { + earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 ); - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + // if this didn't work, try curing all small self-intersections locally - if ( ! extrudeByPath ) { + } else if ( pass === 1 ) { - v( vert.x, vert.y, 0 ); + ear = cureLocalIntersections( ear, triangles, dim ); + earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 ); - } else { + // as a last resort, try splitting the remaining polygon into two - // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); + } else if ( pass === 2 ) { - normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); + splitEarcut( ear, triangles, dim, minX, minY, invSize ); - position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); + } - v( position2.x, position2.y, position2.z ); + break; } } - // Add stepped vertices... - // Including front facing vertices - - var s; + } - for ( s = 1; s <= steps; s ++ ) { + // check whether a polygon node forms a valid ear with adjacent nodes - for ( i = 0; i < vlen; i ++ ) { + function isEar( ear ) { - vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; + var a = ear.prev, + b = ear, + c = ear.next; - if ( ! extrudeByPath ) { + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear - v( vert.x, vert.y, amount / steps * s ); + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; - } else { + while ( p !== ear.prev ) { - // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); + if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) { - normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); - binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); + return false; - position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); + } - v( position2.x, position2.y, position2.z ); + p = p.next; - } + } - } + return true; - } + } + function isEarHashed( ear, minX, minY, invSize ) { - // Add bevel segments planes + var a = ear.prev, + b = ear, + c = ear.next; - //for ( b = 1; b <= bevelSegments; b ++ ) { - for ( b = bevelSegments - 1; b >= 0; b -- ) { + if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear - t = b / bevelSegments; - z = bevelThickness * Math.cos( t * Math.PI / 2 ); - bs = bevelSize * Math.sin( t * Math.PI / 2 ); + // triangle bbox; min & max are calculated like this for speed - // contract shape + var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ), + minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ), + maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ), + maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y ); - for ( i = 0, il = contour.length; i < il; i ++ ) { + // z-order range for the current triangle bbox; - vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - v( vert.x, vert.y, amount + z ); + var minZ = zOrder( minTX, minTY, minX, minY, invSize ), + maxZ = zOrder( maxTX, maxTY, minX, minY, invSize ); - } + // first look for points inside the triangle in increasing z-order - // expand holes + var p = ear.nextZ; - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + while ( p && p.z <= maxZ ) { - ahole = holes[ h ]; - oneHoleMovements = holesMovements[ h ]; + if ( p !== ear.prev && p !== ear.next && + pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; + p = p.nextZ; - for ( i = 0, il = ahole.length; i < il; i ++ ) { + } - vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + // then look for points in decreasing z-order - if ( ! extrudeByPath ) { + p = ear.prevZ; - v( vert.x, vert.y, amount + z ); + while ( p && p.z >= minZ ) { - } else { + if ( p !== ear.prev && p !== ear.next && + pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && + area( p.prev, p, p.next ) >= 0 ) return false; - v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + p = p.prevZ; - } + } - } + return true; - } + } - } + // go through all polygon nodes and cure small local self-intersections - /* Faces */ + function cureLocalIntersections( start, triangles, dim ) { - // Top and bottom faces + var p = start; - buildLidFaces(); + do { - // Sides faces + var a = p.prev, b = p.next.next; - buildSideFaces(); + if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { + triangles.push( a.i / dim ); + triangles.push( p.i / dim ); + triangles.push( b.i / dim ); - ///// Internal functions + // remove two nodes involved - function buildLidFaces() { + removeNode( p ); + removeNode( p.next ); - var start = verticesArray.length/3; + p = start = b; - if ( bevelEnabled ) { + } - var layer = 0; // steps + 1 - var offset = vlen * layer; + p = p.next; - // Bottom faces + } while ( p !== start ); - for ( i = 0; i < flen; i ++ ) { + return p; - face = faces[ i ]; - f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); + } - } + // try splitting polygon into two and triangulate them independently - layer = steps + bevelSegments * 2; - offset = vlen * layer; + function splitEarcut( start, triangles, dim, minX, minY, invSize ) { - // Top faces + // look for a valid diagonal that divides the polygon into two - for ( i = 0; i < flen; i ++ ) { + var a = start; - face = faces[ i ]; - f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); + do { - } + var b = a.next.next; - } else { + while ( b !== a.prev ) { - // Bottom faces + if ( a.i !== b.i && isValidDiagonal( a, b ) ) { - for ( i = 0; i < flen; i ++ ) { + // split the polygon in two by the diagonal - face = faces[ i ]; - f3( face[ 2 ], face[ 1 ], face[ 0 ] ); + var c = splitPolygon( a, b ); - } + // filter colinear points around the cuts - // Top faces + a = filterPoints( a, a.next ); + c = filterPoints( c, c.next ); - for ( i = 0; i < flen; i ++ ) { + // run earcut on each half - face = faces[ i ]; - f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); + earcutLinked( a, triangles, dim, minX, minY, invSize ); + earcutLinked( c, triangles, dim, minX, minY, invSize ); + return; } + b = b.next; + } - scope.addGroup( start, verticesArray.length/3 -start, options.material !== undefined ? options.material : 0); + a = a.next; - } + } while ( a !== start ); - // Create faces for the z-sides of the shape + } - function buildSideFaces() { + // link every hole into the outer loop, producing a single-ring polygon without holes - var start = verticesArray.length/3; - var layeroffset = 0; - sidewalls( contour, layeroffset ); - layeroffset += contour.length; + function eliminateHoles( data, holeIndices, outerNode, dim ) { - for ( h = 0, hl = holes.length; h < hl; h ++ ) { + var queue = [], i, len, start, end, list; - ahole = holes[ h ]; - sidewalls( ahole, layeroffset ); + for ( i = 0, len = holeIndices.length; i < len; i ++ ) { - //, true - layeroffset += ahole.length; + start = holeIndices[ i ] * dim; + end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length; + list = linkedList( data, start, end, dim, false ); + if ( list === list.next ) list.steiner = true; + queue.push( getLeftmost( list ) ); - } + } + queue.sort( compareX ); - scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1); + // process holes from left to right + for ( i = 0; i < queue.length; i ++ ) { - } + eliminateHole( queue[ i ], outerNode ); + outerNode = filterPoints( outerNode, outerNode.next ); - function sidewalls( contour, layeroffset ) { + } - var j, k; - i = contour.length; + return outerNode; - while ( -- i >= 0 ) { + } - j = i; - k = i - 1; - if ( k < 0 ) k = contour.length - 1; + function compareX( a, b ) { - //console.log('b', i,j, i-1, k,vertices.length); + return a.x - b.x; - var s = 0, - sl = steps + bevelSegments * 2; + } - for ( s = 0; s < sl; s ++ ) { + // find a bridge between vertices that connects hole with an outer ring and and link it - var slen1 = vlen * s; - var slen2 = vlen * ( s + 1 ); + function eliminateHole( hole, outerNode ) { - var a = layeroffset + j + slen1, - b = layeroffset + k + slen1, - c = layeroffset + k + slen2, - d = layeroffset + j + slen2; + outerNode = findHoleBridge( hole, outerNode ); - f4( a, b, c, d, contour, s, sl, j, k ); + if ( outerNode ) { - } + var b = splitPolygon( outerNode, hole ); - } + filterPoints( b, b.next ); } - function v( x, y, z ) { + } - placeholder.push( x ); - placeholder.push( y ); - placeholder.push( z ); + // David Eberly's algorithm for finding a bridge between hole and outer polygon - } + function findHoleBridge( hole, outerNode ) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = - Infinity, + m; - function f3( a, b, c ) { + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point - addVertex( a ); - addVertex( b ); - addVertex( c ); + do { - var nextIndex = verticesArray.length / 3; - var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) { - addUV( uvs[ 0 ] ); - addUV( uvs[ 1 ] ); - addUV( uvs[ 2 ] ); + var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y ); - } + if ( x <= hx && x > qx ) { - function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) { + qx = x; - addVertex( a ); - addVertex( b ); - addVertex( d ); + if ( x === hx ) { - addVertex( b ); - addVertex( c ); - addVertex( d ); + if ( hy === p.y ) return p; + if ( hy === p.next.y ) return p.next; + } - var nextIndex = verticesArray.length / 3; - var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + m = p.x < p.next.x ? p : p.next; - addUV( uvs[ 0 ] ); - addUV( uvs[ 1 ] ); - addUV( uvs[ 3 ] ); + } - addUV( uvs[ 1 ] ); - addUV( uvs[ 2 ] ); - addUV( uvs[ 3 ] ); + } - } + p = p.next; - function addVertex( index ) { + } while ( p !== outerNode ); - indicesArray.push( verticesArray.length / 3 ); - verticesArray.push( placeholder[ index * 3 + 0 ] ); - verticesArray.push( placeholder[ index * 3 + 1 ] ); - verticesArray.push( placeholder[ index * 3 + 2 ] ); + if ( ! m ) return null; - } + if ( hx === qx ) return m.prev; // hole touches outer segment; pick lower endpoint + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point - function addUV( vector2 ) { + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; - uvArray.push( vector2.x ); - uvArray.push( vector2.y ); + p = m.next; - } + while ( p !== stop ) { - if ( ! options.arrays ) { + if ( hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) { - this.setIndex( indicesArray ); - this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) ); - this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) ); + tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential - } + if ( ( tan < tanMin || ( tan === tanMin && p.x > m.x ) ) && locallyInside( p, hole ) ) { - }; + m = p; + tanMin = tan; - ExtrudeGeometry.WorldUVGenerator = { + } - generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) { + } - var a_x = vertices[ indexA * 3 ]; - var a_y = vertices[ indexA * 3 + 1 ]; - var b_x = vertices[ indexB * 3 ]; - var b_y = vertices[ indexB * 3 + 1 ]; - var c_x = vertices[ indexC * 3 ]; - var c_y = vertices[ indexC * 3 + 1 ]; + p = p.next; - return [ - new Vector2( a_x, a_y ), - new Vector2( b_x, b_y ), - new Vector2( c_x, c_y ) - ]; + } - }, + return m; - generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) { + } - var a_x = vertices[ indexA * 3 ]; - var a_y = vertices[ indexA * 3 + 1 ]; - var a_z = vertices[ indexA * 3 + 2 ]; - var b_x = vertices[ indexB * 3 ]; - var b_y = vertices[ indexB * 3 + 1 ]; - var b_z = vertices[ indexB * 3 + 2 ]; - var c_x = vertices[ indexC * 3 ]; - var c_y = vertices[ indexC * 3 + 1 ]; - var c_z = vertices[ indexC * 3 + 2 ]; - var d_x = vertices[ indexD * 3 ]; - var d_y = vertices[ indexD * 3 + 1 ]; - var d_z = vertices[ indexD * 3 + 2 ]; + // interlink polygon nodes in z-order - if ( Math.abs( a_y - b_y ) < 0.01 ) { + function indexCurve( start, minX, minY, invSize ) { - return [ - new Vector2( a_x, 1 - a_z ), - new Vector2( b_x, 1 - b_z ), - new Vector2( c_x, 1 - c_z ), - new Vector2( d_x, 1 - d_z ) - ]; + var p = start; - } else { + do { - return [ - new Vector2( a_y, 1 - a_z ), - new Vector2( b_y, 1 - b_z ), - new Vector2( c_y, 1 - c_z ), - new Vector2( d_y, 1 - d_z ) - ]; + if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize ); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; - } + } while ( p !== start ); - } - }; + p.prevZ.nextZ = null; + p.prevZ = null; - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * @author alteredq / http://alteredqualia.com/ - * - * Text = 3D Text - * - * parameters = { - * font: , // font - * - * size: , // size of the text - * height: , // thickness to extrude text - * curveSegments: , // number of points on the curves - * - * bevelEnabled: , // turn on bevel - * bevelThickness: , // how deep into text bevel goes - * bevelSize: // how far from text outline is bevel - * } - */ + sortLinked( p ); - // TextGeometry + } - function TextGeometry( text, parameters ) { + // Simon Tatham's linked list merge sort algorithm + // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html - Geometry.call( this ); + function sortLinked( list ) { - this.type = 'TextGeometry'; + var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; - this.parameters = { - text: text, - parameters: parameters - }; + do { - this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) ); - this.mergeVertices(); + p = list; + list = null; + tail = null; + numMerges = 0; - } + while ( p ) { - TextGeometry.prototype = Object.create( Geometry.prototype ); - TextGeometry.prototype.constructor = TextGeometry; + numMerges ++; + q = p; + pSize = 0; - // TextBufferGeometry + for ( i = 0; i < inSize; i ++ ) { - function TextBufferGeometry( text, parameters ) { + pSize ++; + q = q.nextZ; + if ( ! q ) break; - parameters = parameters || {}; + } - var font = parameters.font; + qSize = inSize; - if ( ! ( font && font.isFont ) ) { + while ( pSize > 0 || ( qSize > 0 && q ) ) { - console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); - return new Geometry(); + if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) { - } + e = p; + p = p.nextZ; + pSize --; - var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments ); + } else { - // translate parameters to ExtrudeGeometry API + e = q; + q = q.nextZ; + qSize --; - parameters.amount = parameters.height !== undefined ? parameters.height : 50; + } - // defaults + if ( tail ) tail.nextZ = e; + else list = e; - if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; - if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; - if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; + e.prevZ = tail; + tail = e; - ExtrudeBufferGeometry.call( this, shapes, parameters ); + } - this.type = 'TextBufferGeometry'; + p = q; - } + } - TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype ); - TextBufferGeometry.prototype.constructor = TextBufferGeometry; + tail.nextZ = null; + inSize *= 2; - /** - * @author mrdoob / http://mrdoob.com/ - * @author benaadams / https://twitter.com/ben_a_adams - * @author Mugen87 / https://github.com/Mugen87 - */ + } while ( numMerges > 1 ); - // SphereGeometry + return list; - function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + } - Geometry.call( this ); + // z-order of a point given coords and inverse of the longer side of data bbox - this.type = 'SphereGeometry'; + function zOrder( x, y, minX, minY, invSize ) { - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + // coords are transformed into non-negative 15-bit integer range - this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); - this.mergeVertices(); + x = 32767 * ( x - minX ) * invSize; + y = 32767 * ( y - minY ) * invSize; - } + x = ( x | ( x << 8 ) ) & 0x00FF00FF; + x = ( x | ( x << 4 ) ) & 0x0F0F0F0F; + x = ( x | ( x << 2 ) ) & 0x33333333; + x = ( x | ( x << 1 ) ) & 0x55555555; - SphereGeometry.prototype = Object.create( Geometry.prototype ); - SphereGeometry.prototype.constructor = SphereGeometry; + y = ( y | ( y << 8 ) ) & 0x00FF00FF; + y = ( y | ( y << 4 ) ) & 0x0F0F0F0F; + y = ( y | ( y << 2 ) ) & 0x33333333; + y = ( y | ( y << 1 ) ) & 0x55555555; - // SphereBufferGeometry + return x | ( y << 1 ); - function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { + } - BufferGeometry.call( this ); + // find the leftmost node of a polygon ring - this.type = 'SphereBufferGeometry'; + function getLeftmost( start ) { - this.parameters = { - radius: radius, - widthSegments: widthSegments, - heightSegments: heightSegments, - phiStart: phiStart, - phiLength: phiLength, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + var p = start, leftmost = start; - radius = radius || 50; + do { - widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); - heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); + if ( p.x < leftmost.x ) leftmost = p; + p = p.next; - phiStart = phiStart !== undefined ? phiStart : 0; - phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; + } while ( p !== start ); - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; + return leftmost; - var thetaEnd = thetaStart + thetaLength; + } - var ix, iy; + // check if a point lies within a convex triangle - var index = 0; - var grid = []; + function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) { - var vertex = new Vector3(); - var normal = new Vector3(); + return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 && + ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 && + ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0; - // buffers + } - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + // check if a diagonal between two polygon nodes is valid (lies in polygon interior) - // generate vertices, normals and uvs + function isValidDiagonal( a, b ) { - for ( iy = 0; iy <= heightSegments; iy ++ ) { + return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && + locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ); - var verticesRow = []; + } - var v = iy / heightSegments; + // signed area of a triangle - for ( ix = 0; ix <= widthSegments; ix ++ ) { + function area( p, q, r ) { - var u = ix / widthSegments; + return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y ); - // vertex + } - vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); - vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + // check if two points are equal - vertices.push( vertex.x, vertex.y, vertex.z ); + function equals( p1, p2 ) { - // normal + return p1.x === p2.x && p1.y === p2.y; - normal.set( vertex.x, vertex.y, vertex.z ).normalize(); - normals.push( normal.x, normal.y, normal.z ); + } - // uv + // check if two segments intersect - uvs.push( u, 1 - v ); + function intersects( p1, q1, p2, q2 ) { - verticesRow.push( index ++ ); + if ( ( equals( p1, q1 ) && equals( p2, q2 ) ) || + ( equals( p1, q2 ) && equals( p2, q1 ) ) ) return true; - } + return area( p1, q1, p2 ) > 0 !== area( p1, q1, q2 ) > 0 && + area( p2, q2, p1 ) > 0 !== area( p2, q2, q1 ) > 0; - grid.push( verticesRow ); + } - } + // check if a polygon diagonal intersects any polygon segments - // indices + function intersectsPolygon( a, b ) { - for ( iy = 0; iy < heightSegments; iy ++ ) { + var p = a; - for ( ix = 0; ix < widthSegments; ix ++ ) { + do { - var a = grid[ iy ][ ix + 1 ]; - var b = grid[ iy ][ ix ]; - var c = grid[ iy + 1 ][ ix ]; - var d = grid[ iy + 1 ][ ix + 1 ]; + if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects( p, p.next, a, b ) ) { - if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d ); - if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d ); + return true; } - } + p = p.next; - // build geometry + } while ( p !== a ); - this.setIndex( indices ); - this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + return false; } - SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - SphereBufferGeometry.prototype.constructor = SphereBufferGeometry; + // check if a polygon diagonal is locally inside the polygon - /** - * @author Kaleb Murphy - * @author Mugen87 / https://github.com/Mugen87 - */ + function locallyInside( a, b ) { - // RingGeometry + return area( a.prev, a, a.next ) < 0 ? + area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 : + area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0; - function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + } - Geometry.call( this ); + // check if the middle point of a polygon diagonal is inside the polygon - this.type = 'RingGeometry'; + function middleInside( a, b ) { - this.parameters = { - innerRadius: innerRadius, - outerRadius: outerRadius, - thetaSegments: thetaSegments, - phiSegments: phiSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + var p = a, + inside = false, + px = ( a.x + b.x ) / 2, + py = ( a.y + b.y ) / 2; - this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); - this.mergeVertices(); + do { - } + if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y && + ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) { - RingGeometry.prototype = Object.create( Geometry.prototype ); - RingGeometry.prototype.constructor = RingGeometry; + inside = ! inside; - // RingBufferGeometry + } - function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + p = p.next; - BufferGeometry.call( this ); + } while ( p !== a ); - this.type = 'RingBufferGeometry'; + return inside; - this.parameters = { - innerRadius: innerRadius, - outerRadius: outerRadius, - thetaSegments: thetaSegments, - phiSegments: phiSegments, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + } - innerRadius = innerRadius || 20; - outerRadius = outerRadius || 50; + // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; + // if one belongs to the outer ring and another to a hole, it merges it into a single ring - thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; + function splitPolygon( a, b ) { - thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; - phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1; + var a2 = new Node( a.i, a.x, a.y ), + b2 = new Node( b.i, b.x, b.y ), + an = a.next, + bp = b.prev; - // buffers + a.next = b; + b.prev = a; - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + a2.next = an; + an.prev = a2; - // some helper variables + b2.next = a2; + a2.prev = b2; - var segment; - var radius = innerRadius; - var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); - var vertex = new Vector3(); - var uv = new Vector2(); - var j, i; + bp.next = b2; + b2.prev = bp; - // generate vertices, normals and uvs + return b2; - for ( j = 0; j <= phiSegments; j ++ ) { + } - for ( i = 0; i <= thetaSegments; i ++ ) { + // create a node and optionally link it with previous one (in a circular doubly linked list) - // values are generate from the inside of the ring to the outside + function insertNode( i, x, y, last ) { - segment = thetaStart + i / thetaSegments * thetaLength; + var p = new Node( i, x, y ); - // vertex + if ( ! last ) { - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); + p.prev = p; + p.next = p; - vertices.push( vertex.x, vertex.y, vertex.z ); + } else { - // normal + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; - normals.push( 0, 0, 1 ); + } - // uv + return p; - uv.x = ( vertex.x / outerRadius + 1 ) / 2; - uv.y = ( vertex.y / outerRadius + 1 ) / 2; + } - uvs.push( uv.x, uv.y ); + function removeNode( p ) { - } + p.next.prev = p.prev; + p.prev.next = p.next; - // increase the radius for next row of vertices + if ( p.prevZ ) p.prevZ.nextZ = p.nextZ; + if ( p.nextZ ) p.nextZ.prevZ = p.prevZ; - radius += radiusStep; + } - } + function Node( i, x, y ) { - // indices + // vertice index in coordinates array + this.i = i; - for ( j = 0; j < phiSegments; j ++ ) { + // vertex coordinates + this.x = x; + this.y = y; - var thetaSegmentLevel = j * ( thetaSegments + 1 ); + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; - for ( i = 0; i < thetaSegments; i ++ ) { + // z-order curve value + this.z = null; - segment = i + thetaSegmentLevel; + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; - var a = segment; - var b = segment + thetaSegments + 1; - var c = segment + thetaSegments + 2; - var d = segment + 1; + // indicates whether this is a steiner point + this.steiner = false; - // faces + } - indices.push( a, b, d ); - indices.push( b, c, d ); + function signedArea( data, start, end, dim ) { - } + var sum = 0; - } + for ( var i = start, j = end - dim; i < end; i += dim ) { - // build geometry + sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] ); + j = i; - this.setIndex( indices ); - this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + } - } + return sum; - RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - RingBufferGeometry.prototype.constructor = RingBufferGeometry; + } /** - * @author astrodud / http://astrodud.isgreat.org/ - * @author zz85 / https://github.com/zz85 - * @author bhouston / http://clara.io - * @author Mugen87 / https://github.com/Mugen87 + * @author zz85 / http://www.lab4games.net/zz85/blog */ - // LatheGeometry + var ShapeUtils = { - function LatheGeometry( points, segments, phiStart, phiLength ) { + // calculate area of the contour polygon - Geometry.call( this ); + area: function ( contour ) { - this.type = 'LatheGeometry'; + var n = contour.length; + var a = 0.0; - this.parameters = { - points: points, - segments: segments, - phiStart: phiStart, - phiLength: phiLength - }; + for ( var p = n - 1, q = 0; q < n; p = q ++ ) { - this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) ); - this.mergeVertices(); + a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; - } + } - LatheGeometry.prototype = Object.create( Geometry.prototype ); - LatheGeometry.prototype.constructor = LatheGeometry; + return a * 0.5; - // LatheBufferGeometry + }, - function LatheBufferGeometry( points, segments, phiStart, phiLength ) { + isClockWise: function ( pts ) { - BufferGeometry.call( this ); + return ShapeUtils.area( pts ) < 0; - this.type = 'LatheBufferGeometry'; + }, - this.parameters = { - points: points, - segments: segments, - phiStart: phiStart, - phiLength: phiLength - }; + triangulateShape: function ( contour, holes ) { - segments = Math.floor( segments ) || 12; - phiStart = phiStart || 0; - phiLength = phiLength || Math.PI * 2; + var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ] + var holeIndices = []; // array of hole indices + var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ] - // clamp phiLength so it's in range of [ 0, 2PI ] + removeDupEndPts( contour ); + addContour( vertices, contour ); - phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 ); + // + var holeIndex = contour.length; - // buffers + holes.forEach( removeDupEndPts ); - var indices = []; - var vertices = []; - var uvs = []; + for ( var i = 0; i < holes.length; i ++ ) { - // helper variables + holeIndices.push( holeIndex ); + holeIndex += holes[ i ].length; + addContour( vertices, holes[ i ] ); - var base; - var inverseSegments = 1.0 / segments; - var vertex = new Vector3(); - var uv = new Vector2(); - var i, j; + } - // generate vertices and uvs + // - for ( i = 0; i <= segments; i ++ ) { + var triangles = Earcut.triangulate( vertices, holeIndices ); - var phi = phiStart + i * inverseSegments * phiLength; + // - var sin = Math.sin( phi ); - var cos = Math.cos( phi ); + for ( var i = 0; i < triangles.length; i += 3 ) { - for ( j = 0; j <= ( points.length - 1 ); j ++ ) { + faces.push( triangles.slice( i, i + 3 ) ); - // vertex + } - vertex.x = points[ j ].x * sin; - vertex.y = points[ j ].y; - vertex.z = points[ j ].x * cos; + return faces; - vertices.push( vertex.x, vertex.y, vertex.z ); + } - // uv + }; - uv.x = i / segments; - uv.y = j / ( points.length - 1 ); + function removeDupEndPts( points ) { - uvs.push( uv.x, uv.y ); + var l = points.length; + if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { - } + points.pop(); } - // indices + } - for ( i = 0; i < segments; i ++ ) { + function addContour( vertices, contour ) { - for ( j = 0; j < ( points.length - 1 ); j ++ ) { + for ( var i = 0; i < contour.length; i ++ ) { - base = j + i * points.length; + vertices.push( contour[ i ].x ); + vertices.push( contour[ i ].y ); - var a = base; - var b = base + points.length; - var c = base + points.length + 1; - var d = base + 1; + } - // faces + } - indices.push( a, b, d ); - indices.push( b, c, d ); + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + * Creates extruded geometry from a path shape. + * + * parameters = { + * + * curveSegments: , // number of points on the curves + * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too + * amount: , // Depth to extrude the shape + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into the original shape bevel goes + * bevelSize: , // how far from shape outline is bevel + * bevelSegments: , // number of bevel layers + * + * extrudePath: // curve to extrude shape along + * frames: // containing arrays of tangents, normals, binormals + * + * UVGenerator: // object that provides UV generator functions + * + * } + */ - } + // ExtrudeGeometry - } + function ExtrudeGeometry( shapes, options ) { - // build geometry + Geometry.call( this ); - this.setIndex( indices ); - this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + this.type = 'ExtrudeGeometry'; - // generate normals + this.parameters = { + shapes: shapes, + options: options + }; - this.computeVertexNormals(); + this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) ); + this.mergeVertices(); - // if the geometry is closed, we need to average the normals along the seam. - // because the corresponding vertices are identical (but still have different UVs). + } - if ( phiLength === Math.PI * 2 ) { + ExtrudeGeometry.prototype = Object.create( Geometry.prototype ); + ExtrudeGeometry.prototype.constructor = ExtrudeGeometry; - var normals = this.attributes.normal.array; - var n1 = new Vector3(); - var n2 = new Vector3(); - var n = new Vector3(); + // ExtrudeBufferGeometry - // this is the buffer offset for the last line of vertices + function ExtrudeBufferGeometry( shapes, options ) { - base = segments * points.length * 3; + if ( typeof ( shapes ) === "undefined" ) { - for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) { + return; - // select the normal of the vertex in the first line + } - n1.x = normals[ j + 0 ]; - n1.y = normals[ j + 1 ]; - n1.z = normals[ j + 2 ]; + BufferGeometry.call( this ); - // select the normal of the vertex in the last line + this.type = 'ExtrudeBufferGeometry'; - n2.x = normals[ base + j + 0 ]; - n2.y = normals[ base + j + 1 ]; - n2.z = normals[ base + j + 2 ]; + shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; - // average normals + this.addShapeList( shapes, options ); - n.addVectors( n1, n2 ).normalize(); + this.computeVertexNormals(); - // assign the new values to both normals + // can't really use automatic vertex normals + // as then front and back sides get smoothed too + // should do separate smoothing just for sides - normals[ j + 0 ] = normals[ base + j + 0 ] = n.x; - normals[ j + 1 ] = normals[ base + j + 1 ] = n.y; - normals[ j + 2 ] = normals[ base + j + 2 ] = n.z; - - } + //this.computeVertexNormals(); - } + //console.log( "took", ( Date.now() - startTime ) ); } - LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - LatheBufferGeometry.prototype.constructor = LatheBufferGeometry; + ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry; - /** - * @author jonobr1 / http://jonobr1.com - * @author Mugen87 / https://github.com/Mugen87 - */ + ExtrudeBufferGeometry.prototype.getArrays = function () { - // ShapeGeometry + var positionAttribute = this.getAttribute( "position" ); + var verticesArray = positionAttribute ? Array.prototype.slice.call( positionAttribute.array ) : []; - function ShapeGeometry( shapes, curveSegments ) { + var uvAttribute = this.getAttribute( "uv" ); + var uvArray = uvAttribute ? Array.prototype.slice.call( uvAttribute.array ) : []; - Geometry.call( this ); + var IndexAttribute = this.index; + var indicesArray = IndexAttribute ? Array.prototype.slice.call( IndexAttribute.array ) : []; - this.type = 'ShapeGeometry'; + return { + position: verticesArray, + uv: uvArray, + index: indicesArray + }; - if ( typeof curveSegments === 'object' ) { + }; - console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' ); + ExtrudeBufferGeometry.prototype.addShapeList = function ( shapes, options ) { - curveSegments = curveSegments.curveSegments; + var sl = shapes.length; + options.arrays = this.getArrays(); - } + for ( var s = 0; s < sl; s ++ ) { - this.parameters = { - shapes: shapes, - curveSegments: curveSegments - }; + var shape = shapes[ s ]; + this.addShape( shape, options ); - this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) ); - this.mergeVertices(); + } - } + this.setIndex( options.arrays.index ); + this.addAttribute( 'position', new Float32BufferAttribute( options.arrays.position, 3 ) ); + this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) ); - ShapeGeometry.prototype = Object.create( Geometry.prototype ); - ShapeGeometry.prototype.constructor = ShapeGeometry; + }; - // ShapeBufferGeometry + ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) { - function ShapeBufferGeometry( shapes, curveSegments ) { + var arrays = options.arrays ? options.arrays : this.getArrays(); + var verticesArray = arrays.position; + var indicesArray = arrays.index; + var uvArray = arrays.uv; - BufferGeometry.call( this ); + var placeholder = []; - this.type = 'ShapeBufferGeometry'; - this.parameters = { - shapes: shapes, - curveSegments: curveSegments - }; + var amount = options.amount !== undefined ? options.amount : 100; - curveSegments = curveSegments || 12; + var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10 + var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8 + var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; - // buffers + var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; - // helper variables + var steps = options.steps !== undefined ? options.steps : 1; - var groupStart = 0; - var groupCount = 0; + var extrudePath = options.extrudePath; + var extrudePts, extrudeByPath = false; - // allow single and array values for "shapes" parameter + // Use default WorldUVGenerator if no UV generators are specified. + var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator; - if ( Array.isArray( shapes ) === false ) { + var splineTube, binormal, normal, position2; + if ( extrudePath ) { - addShape( shapes ); + extrudePts = extrudePath.getSpacedPoints( steps ); - } else { + extrudeByPath = true; + bevelEnabled = false; // bevels not supported for path extrusion - for ( var i = 0; i < shapes.length; i ++ ) { + // SETUP TNB variables - addShape( shapes[ i ] ); + // TODO1 - have a .isClosed in spline? - this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support + splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false ); - groupStart += groupCount; - groupCount = 0; + // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); - } + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); } - // build geometry - - this.setIndex( indices ); - this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + // Safeguards if bevels are not enabled + if ( ! bevelEnabled ) { - // helper functions + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; - function addShape( shape ) { + } - var i, l, shapeHole; + // Variables initialization - var indexOffset = vertices.length / 3; - var points = shape.extractPoints( curveSegments ); + var ahole, h, hl; // looping of holes + var scope = this; - var shapeVertices = points.shape; - var shapeHoles = points.holes; + var shapePoints = shape.extractPoints( curveSegments ); - // check direction of vertices + var vertices = shapePoints.shape; + var holes = shapePoints.holes; - if ( ShapeUtils.isClockWise( shapeVertices ) === false ) { + var reverse = ! ShapeUtils.isClockWise( vertices ); - shapeVertices = shapeVertices.reverse(); + if ( reverse ) { - // also check if holes are in the opposite direction + vertices = vertices.reverse(); - for ( i = 0, l = shapeHoles.length; i < l; i ++ ) { + // Maybe we should also check if holes are in the opposite direction, just to be safe ... - shapeHole = shapeHoles[ i ]; + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - if ( ShapeUtils.isClockWise( shapeHole ) === true ) { + ahole = holes[ h ]; - shapeHoles[ i ] = shapeHole.reverse(); + if ( ShapeUtils.isClockWise( ahole ) ) { - } + holes[ h ] = ahole.reverse(); } } - var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles ); - - // join vertices of inner and outer paths to a single array + } - for ( i = 0, l = shapeHoles.length; i < l; i ++ ) { - shapeHole = shapeHoles[ i ]; - shapeVertices = shapeVertices.concat( shapeHole ); + var faces = ShapeUtils.triangulateShape( vertices, holes ); - } + /* Vertices */ - // vertices, normals, uvs + var contour = vertices; // vertices has all points but contour has only points of circumference - for ( i = 0, l = shapeVertices.length; i < l; i ++ ) { + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - var vertex = shapeVertices[ i ]; + ahole = holes[ h ]; - vertices.push( vertex.x, vertex.y, 0 ); - normals.push( 0, 0, 1 ); - uvs.push( vertex.x, vertex.y ); // world uvs + vertices = vertices.concat( ahole ); - } + } - // incides - for ( i = 0, l = faces.length; i < l; i ++ ) { + function scalePt2( pt, vec, size ) { - var face = faces[ i ]; + if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" ); - var a = face[ 0 ] + indexOffset; - var b = face[ 1 ] + indexOffset; - var c = face[ 2 ] + indexOffset; + return vec.clone().multiplyScalar( size ).add( pt ); - indices.push( a, b, c ); - groupCount += 3; + } - } + var b, bs, t, z, + vert, vlen = vertices.length, + face, flen = faces.length; - } - } + // Find directions for point movement - ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry; - /** - * @author WestLangley / http://github.com/WestLangley - * @author Mugen87 / https://github.com/Mugen87 - */ + function getBevelVec( inPt, inPrev, inNext ) { - function EdgesGeometry( geometry, thresholdAngle ) { + // computes for inPt the corresponding point inPt' on a new contour + // shifted by 1 unit (length of normalized vector) to the left + // if we walk along contour clockwise, this new contour is outside the old one + // + // inPt' is the intersection of the two lines parallel to the two + // adjacent edges of inPt at a distance of 1 unit on the left side. - BufferGeometry.call( this ); + var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt - this.type = 'EdgesGeometry'; + // good reading for geometry algorithms (here: line-line intersection) + // http://geomalgorithms.com/a05-_intersect-1.html - this.parameters = { - thresholdAngle: thresholdAngle - }; + var v_prev_x = inPt.x - inPrev.x, + v_prev_y = inPt.y - inPrev.y; + var v_next_x = inNext.x - inPt.x, + v_next_y = inNext.y - inPt.y; - thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; + var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); - // buffer + // check for collinear edges + var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - var vertices = []; + if ( Math.abs( collinear0 ) > Number.EPSILON ) { - // helper variables + // not collinear - var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle ); - var edge = [ 0, 0 ], edges = {}, edge1, edge2; - var key, keys = [ 'a', 'b', 'c' ]; + // length of vectors for normalizing - // prepare source geometry + var v_prev_len = Math.sqrt( v_prev_lensq ); + var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); - var geometry2; + // shift adjacent points by unit vectors to the left - if ( geometry.isBufferGeometry ) { + var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); + var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); - geometry2 = new Geometry(); - geometry2.fromBufferGeometry( geometry ); + var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); + var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); - } else { + // scaling factor for v_prev to intersection point - geometry2 = geometry.clone(); + var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - + ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / + ( v_prev_x * v_next_y - v_prev_y * v_next_x ); - } + // vector from inPt to intersection point - geometry2.mergeVertices(); - geometry2.computeFaceNormals(); + v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); + v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); - var sourceVertices = geometry2.vertices; - var faces = geometry2.faces; + // Don't normalize!, otherwise sharp corners become ugly + // but prevent crazy spikes + var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); + if ( v_trans_lensq <= 2 ) { - // now create a data structure where each entry represents an edge with its adjoining faces + return new Vector2( v_trans_x, v_trans_y ); - for ( var i = 0, l = faces.length; i < l; i ++ ) { + } else { - var face = faces[ i ]; + shrink_by = Math.sqrt( v_trans_lensq / 2 ); - for ( var j = 0; j < 3; j ++ ) { + } - edge1 = face[ keys[ j ] ]; - edge2 = face[ keys[ ( j + 1 ) % 3 ] ]; - edge[ 0 ] = Math.min( edge1, edge2 ); - edge[ 1 ] = Math.max( edge1, edge2 ); + } else { - key = edge[ 0 ] + ',' + edge[ 1 ]; + // handle special case of collinear edges - if ( edges[ key ] === undefined ) { + var direction_eq = false; // assumes: opposite + if ( v_prev_x > Number.EPSILON ) { - edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined }; + if ( v_next_x > Number.EPSILON ) { - } else { + direction_eq = true; - edges[ key ].face2 = i; + } - } + } else { - } + if ( v_prev_x < - Number.EPSILON ) { - } + if ( v_next_x < - Number.EPSILON ) { - // generate vertices + direction_eq = true; - for ( key in edges ) { + } - var e = edges[ key ]; + } else { - // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree. + if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { - if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) { + direction_eq = true; - var vertex = sourceVertices[ e.index1 ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + } - vertex = sourceVertices[ e.index2 ]; - vertices.push( vertex.x, vertex.y, vertex.z ); + } - } + } - } + if ( direction_eq ) { - // build geometry + // console.log("Warning: lines are a straight sequence"); + v_trans_x = - v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt( v_prev_lensq ); - this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + } else { - } + // console.log("Warning: lines are a straight spike"); + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt( v_prev_lensq / 2 ); - EdgesGeometry.prototype = Object.create( BufferGeometry.prototype ); - EdgesGeometry.prototype.constructor = EdgesGeometry; + } - /** - * @author mrdoob / http://mrdoob.com/ - * @author Mugen87 / https://github.com/Mugen87 - */ + } - // CylinderGeometry + return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); - function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + } - Geometry.call( this ); - this.type = 'CylinderGeometry'; + var contourMovements = []; - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); - this.mergeVertices(); + if ( j === il ) j = 0; + if ( k === il ) k = 0; - } + // (j)---(i)---(k) + // console.log('i,j,k', i, j , k) - CylinderGeometry.prototype = Object.create( Geometry.prototype ); - CylinderGeometry.prototype.constructor = CylinderGeometry; + contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); - // CylinderBufferGeometry + } - function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + var holesMovements = [], + oneHoleMovements, verticesMovements = contourMovements.concat(); - BufferGeometry.call( this ); + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - this.type = 'CylinderBufferGeometry'; + ahole = holes[ h ]; - this.parameters = { - radiusTop: radiusTop, - radiusBottom: radiusBottom, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + oneHoleMovements = []; - var scope = this; + for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { - radiusTop = radiusTop !== undefined ? radiusTop : 20; - radiusBottom = radiusBottom !== undefined ? radiusBottom : 20; - height = height !== undefined ? height : 100; + if ( j === il ) j = 0; + if ( k === il ) k = 0; - radialSegments = Math.floor( radialSegments ) || 8; - heightSegments = Math.floor( heightSegments ) || 1; + // (j)---(i)---(k) + oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); - openEnded = openEnded !== undefined ? openEnded : false; - thetaStart = thetaStart !== undefined ? thetaStart : 0.0; - thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI; + } - // buffers + holesMovements.push( oneHoleMovements ); + verticesMovements = verticesMovements.concat( oneHoleMovements ); - var indices = []; - var vertices = []; - var normals = []; - var uvs = []; + } - // helper variables - var index = 0; - var indexArray = []; - var halfHeight = height / 2; - var groupStart = 0; + // Loop bevelSegments, 1 for the front, 1 for the back - // generate geometry + for ( b = 0; b < bevelSegments; b ++ ) { - generateTorso(); + //for ( b = bevelSegments; b > 0; b -- ) { - if ( openEnded === false ) { + t = b / bevelSegments; + z = bevelThickness * Math.cos( t * Math.PI / 2 ); + bs = bevelSize * Math.sin( t * Math.PI / 2 ); - if ( radiusTop > 0 ) generateCap( true ); - if ( radiusBottom > 0 ) generateCap( false ); + // contract shape - } + for ( i = 0, il = contour.length; i < il; i ++ ) { - // build geometry + vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); - this.setIndex( indices ); - this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); - this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); - this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + v( vert.x, vert.y, - z ); - function generateTorso() { + } - var x, y; - var normal = new Vector3(); - var vertex = new Vector3(); + // expand holes - var groupCount = 0; + for ( h = 0, hl = holes.length; h < hl; h ++ ) { - // this will be used to calculate the normal - var slope = ( radiusBottom - radiusTop ) / height; + ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; - // generate vertices, normals and uvs + for ( i = 0, il = ahole.length; i < il; i ++ ) { - for ( y = 0; y <= heightSegments; y ++ ) { + vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); - var indexRow = []; + v( vert.x, vert.y, - z ); - var v = y / heightSegments; + } - // calculate the radius of the current row + } - var radius = v * ( radiusBottom - radiusTop ) + radiusTop; + } - for ( x = 0; x <= radialSegments; x ++ ) { + bs = bevelSize; - var u = x / radialSegments; + // Back facing vertices - var theta = u * thetaLength + thetaStart; + for ( i = 0; i < vlen; i ++ ) { - var sinTheta = Math.sin( theta ); - var cosTheta = Math.cos( theta ); + vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - // vertex + if ( ! extrudeByPath ) { - vertex.x = radius * sinTheta; - vertex.y = - v * height + halfHeight; - vertex.z = radius * cosTheta; - vertices.push( vertex.x, vertex.y, vertex.z ); + v( vert.x, vert.y, 0 ); - // normal + } else { - normal.set( sinTheta, slope, cosTheta ).normalize(); - normals.push( normal.x, normal.y, normal.z ); + // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); - // uv + normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); - uvs.push( u, 1 - v ); + position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); - // save index of vertex in respective row + v( position2.x, position2.y, position2.z ); - indexRow.push( index ++ ); + } - } + } - // now save vertices of the row in our index array + // Add stepped vertices... + // Including front facing vertices - indexArray.push( indexRow ); + var s; - } + for ( s = 1; s <= steps; s ++ ) { - // generate indices + for ( i = 0; i < vlen; i ++ ) { - for ( x = 0; x < radialSegments; x ++ ) { + vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; - for ( y = 0; y < heightSegments; y ++ ) { + if ( ! extrudeByPath ) { - // we use the index array to access the correct indices + v( vert.x, vert.y, amount / steps * s ); - var a = indexArray[ y ][ x ]; - var b = indexArray[ y + 1 ][ x ]; - var c = indexArray[ y + 1 ][ x + 1 ]; - var d = indexArray[ y ][ x + 1 ]; + } else { - // faces + // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); - indices.push( a, b, d ); - indices.push( b, c, d ); + normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); + binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); - // update group counter + position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); - groupCount += 6; + v( position2.x, position2.y, position2.z ); } } - // add a group to the geometry. this will ensure multi material support + } - scope.addGroup( groupStart, groupCount, 0 ); - // calculate new start value for groups + // Add bevel segments planes - groupStart += groupCount; + //for ( b = 1; b <= bevelSegments; b ++ ) { + for ( b = bevelSegments - 1; b >= 0; b -- ) { + + t = b / bevelSegments; + z = bevelThickness * Math.cos( t * Math.PI / 2 ); + bs = bevelSize * Math.sin( t * Math.PI / 2 ); + + // contract shape + + for ( i = 0, il = contour.length; i < il; i ++ ) { + + vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); + v( vert.x, vert.y, amount + z ); + + } + + // expand holes + + for ( h = 0, hl = holes.length; h < hl; h ++ ) { + + ahole = holes[ h ]; + oneHoleMovements = holesMovements[ h ]; + + for ( i = 0, il = ahole.length; i < il; i ++ ) { + + vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); + + if ( ! extrudeByPath ) { + + v( vert.x, vert.y, amount + z ); + + } else { + + v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); + + } + + } + + } } - function generateCap( top ) { + /* Faces */ - var x, centerIndexStart, centerIndexEnd; + // Top and bottom faces - var uv = new Vector2(); - var vertex = new Vector3(); + buildLidFaces(); - var groupCount = 0; + // Sides faces - var radius = ( top === true ) ? radiusTop : radiusBottom; - var sign = ( top === true ) ? 1 : - 1; + buildSideFaces(); - // save the index of the first center vertex - centerIndexStart = index; - // first we generate the center vertex data of the cap. - // because the geometry needs one set of uvs per face, - // we must generate a center vertex per face/segment + ///// Internal functions - for ( x = 1; x <= radialSegments; x ++ ) { + function buildLidFaces() { - // vertex + var start = verticesArray.length / 3; - vertices.push( 0, halfHeight * sign, 0 ); + if ( bevelEnabled ) { - // normal + var layer = 0; // steps + 1 + var offset = vlen * layer; - normals.push( 0, sign, 0 ); + // Bottom faces - // uv + for ( i = 0; i < flen; i ++ ) { - uvs.push( 0.5, 0.5 ); + face = faces[ i ]; + f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); - // increase index + } - index ++; + layer = steps + bevelSegments * 2; + offset = vlen * layer; - } + // Top faces - // save the index of the last center vertex + for ( i = 0; i < flen; i ++ ) { - centerIndexEnd = index; + face = faces[ i ]; + f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); - // now we generate the surrounding vertices, normals and uvs + } - for ( x = 0; x <= radialSegments; x ++ ) { + } else { - var u = x / radialSegments; - var theta = u * thetaLength + thetaStart; + // Bottom faces - var cosTheta = Math.cos( theta ); - var sinTheta = Math.sin( theta ); + for ( i = 0; i < flen; i ++ ) { - // vertex + face = faces[ i ]; + f3( face[ 2 ], face[ 1 ], face[ 0 ] ); - vertex.x = radius * sinTheta; - vertex.y = halfHeight * sign; - vertex.z = radius * cosTheta; - vertices.push( vertex.x, vertex.y, vertex.z ); + } - // normal + // Top faces - normals.push( 0, sign, 0 ); + for ( i = 0; i < flen; i ++ ) { - // uv + face = faces[ i ]; + f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); - uv.x = ( cosTheta * 0.5 ) + 0.5; - uv.y = ( sinTheta * 0.5 * sign ) + 0.5; - uvs.push( uv.x, uv.y ); + } - // increase index + } - index ++; + scope.addGroup( start, verticesArray.length / 3 - start, 0 ); + + } + + // Create faces for the z-sides of the shape + + function buildSideFaces() { + + var start = verticesArray.length / 3; + var layeroffset = 0; + sidewalls( contour, layeroffset ); + layeroffset += contour.length; + + for ( h = 0, hl = holes.length; h < hl; h ++ ) { + + ahole = holes[ h ]; + sidewalls( ahole, layeroffset ); + + //, true + layeroffset += ahole.length; } - // generate indices - for ( x = 0; x < radialSegments; x ++ ) { + scope.addGroup( start, verticesArray.length / 3 - start, 1 ); - var c = centerIndexStart + x; - var i = centerIndexEnd + x; - if ( top === true ) { + } - // face top + function sidewalls( contour, layeroffset ) { - indices.push( i, i + 1, c ); + var j, k; + i = contour.length; - } else { + while ( -- i >= 0 ) { - // face bottom + j = i; + k = i - 1; + if ( k < 0 ) k = contour.length - 1; - indices.push( i + 1, i, c ); + //console.log('b', i,j, i-1, k,vertices.length); - } + var s = 0, + sl = steps + bevelSegments * 2; - groupCount += 3; + for ( s = 0; s < sl; s ++ ) { + + var slen1 = vlen * s; + var slen2 = vlen * ( s + 1 ); + + var a = layeroffset + j + slen1, + b = layeroffset + k + slen1, + c = layeroffset + k + slen2, + d = layeroffset + j + slen2; + + f4( a, b, c, d ); + + } } - // add a group to the geometry. this will ensure multi material support + } - scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); + function v( x, y, z ) { - // calculate new start value for groups + placeholder.push( x ); + placeholder.push( y ); + placeholder.push( z ); - groupStart += groupCount; + } + + + function f3( a, b, c ) { + + addVertex( a ); + addVertex( b ); + addVertex( c ); + + var nextIndex = verticesArray.length / 3; + var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); } - } + function f4( a, b, c, d ) { - CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry; + addVertex( a ); + addVertex( b ); + addVertex( d ); + + addVertex( b ); + addVertex( c ); + addVertex( d ); + + + var nextIndex = verticesArray.length / 3; + var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); + + addUV( uvs[ 0 ] ); + addUV( uvs[ 1 ] ); + addUV( uvs[ 3 ] ); + + addUV( uvs[ 1 ] ); + addUV( uvs[ 2 ] ); + addUV( uvs[ 3 ] ); + + } + + function addVertex( index ) { + + indicesArray.push( verticesArray.length / 3 ); + verticesArray.push( placeholder[ index * 3 + 0 ] ); + verticesArray.push( placeholder[ index * 3 + 1 ] ); + verticesArray.push( placeholder[ index * 3 + 2 ] ); + + } + + + function addUV( vector2 ) { + + uvArray.push( vector2.x ); + uvArray.push( vector2.y ); + + } + + if ( ! options.arrays ) { + + this.setIndex( indicesArray ); + this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) ); + this.addAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) ); + + } + + }; + + ExtrudeGeometry.WorldUVGenerator = { + + generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) { + + var a_x = vertices[ indexA * 3 ]; + var a_y = vertices[ indexA * 3 + 1 ]; + var b_x = vertices[ indexB * 3 ]; + var b_y = vertices[ indexB * 3 + 1 ]; + var c_x = vertices[ indexC * 3 ]; + var c_y = vertices[ indexC * 3 + 1 ]; + + return [ + new Vector2( a_x, a_y ), + new Vector2( b_x, b_y ), + new Vector2( c_x, c_y ) + ]; + + }, + + generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) { + + var a_x = vertices[ indexA * 3 ]; + var a_y = vertices[ indexA * 3 + 1 ]; + var a_z = vertices[ indexA * 3 + 2 ]; + var b_x = vertices[ indexB * 3 ]; + var b_y = vertices[ indexB * 3 + 1 ]; + var b_z = vertices[ indexB * 3 + 2 ]; + var c_x = vertices[ indexC * 3 ]; + var c_y = vertices[ indexC * 3 + 1 ]; + var c_z = vertices[ indexC * 3 + 2 ]; + var d_x = vertices[ indexD * 3 ]; + var d_y = vertices[ indexD * 3 + 1 ]; + var d_z = vertices[ indexD * 3 + 2 ]; + + if ( Math.abs( a_y - b_y ) < 0.01 ) { + + return [ + new Vector2( a_x, 1 - a_z ), + new Vector2( b_x, 1 - b_z ), + new Vector2( c_x, 1 - c_z ), + new Vector2( d_x, 1 - d_z ) + ]; + + } else { + + return [ + new Vector2( a_y, 1 - a_z ), + new Vector2( b_y, 1 - b_z ), + new Vector2( c_y, 1 - c_z ), + new Vector2( d_y, 1 - d_z ) + ]; + + } + + } + }; /** - * @author abelnation / http://github.com/abelnation + * @author zz85 / http://www.lab4games.net/zz85/blog + * @author alteredq / http://alteredqualia.com/ + * + * Text = 3D Text + * + * parameters = { + * font: , // font + * + * size: , // size of the text + * height: , // thickness to extrude text + * curveSegments: , // number of points on the curves + * + * bevelEnabled: , // turn on bevel + * bevelThickness: , // how deep into text bevel goes + * bevelSize: // how far from text outline is bevel + * } */ - // ConeGeometry + // TextGeometry - function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + function TextGeometry( text, parameters ) { - CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); + Geometry.call( this ); - this.type = 'ConeGeometry'; + this.type = 'TextGeometry'; this.parameters = { - radius: radius, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength + text: text, + parameters: parameters }; + this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) ); + this.mergeVertices(); + } - ConeGeometry.prototype = Object.create( CylinderGeometry.prototype ); - ConeGeometry.prototype.constructor = ConeGeometry; + TextGeometry.prototype = Object.create( Geometry.prototype ); + TextGeometry.prototype.constructor = TextGeometry; - // ConeBufferGeometry + // TextBufferGeometry - function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + function TextBufferGeometry( text, parameters ) { - CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); + parameters = parameters || {}; - this.type = 'ConeBufferGeometry'; + var font = parameters.font; - this.parameters = { - radius: radius, - height: height, - radialSegments: radialSegments, - heightSegments: heightSegments, - openEnded: openEnded, - thetaStart: thetaStart, - thetaLength: thetaLength - }; + if ( ! ( font && font.isFont ) ) { + + console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); + return new Geometry(); + + } + + var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments ); + + // translate parameters to ExtrudeGeometry API + + parameters.amount = parameters.height !== undefined ? parameters.height : 50; + + // defaults + + if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10; + if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8; + if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false; + + ExtrudeBufferGeometry.call( this, shapes, parameters ); + + this.type = 'TextBufferGeometry'; } - ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype ); - ConeBufferGeometry.prototype.constructor = ConeBufferGeometry; + TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype ); + TextBufferGeometry.prototype.constructor = TextBufferGeometry; /** + * @author mrdoob / http://mrdoob.com/ * @author benaadams / https://twitter.com/ben_a_adams * @author Mugen87 / https://github.com/Mugen87 - * @author hughes */ - // CircleGeometry + // SphereGeometry - function CircleGeometry( radius, segments, thetaStart, thetaLength ) { + function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { Geometry.call( this ); - this.type = 'CircleGeometry'; + this.type = 'SphereGeometry'; this.parameters = { radius: radius, - segments: segments, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, thetaStart: thetaStart, thetaLength: thetaLength }; - this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); + this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); this.mergeVertices(); } - CircleGeometry.prototype = Object.create( Geometry.prototype ); - CircleGeometry.prototype.constructor = CircleGeometry; + SphereGeometry.prototype = Object.create( Geometry.prototype ); + SphereGeometry.prototype.constructor = SphereGeometry; - // CircleBufferGeometry + // SphereBufferGeometry - function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) { + function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { BufferGeometry.call( this ); - this.type = 'CircleBufferGeometry'; + this.type = 'SphereBufferGeometry'; this.parameters = { radius: radius, - segments: segments, + widthSegments: widthSegments, + heightSegments: heightSegments, + phiStart: phiStart, + phiLength: phiLength, thetaStart: thetaStart, thetaLength: thetaLength }; - radius = radius || 50; - segments = segments !== undefined ? Math.max( 3, segments ) : 8; + radius = radius || 1; + + widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); + heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); + + phiStart = phiStart !== undefined ? phiStart : 0; + phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; thetaStart = thetaStart !== undefined ? thetaStart : 0; - thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; + + var thetaEnd = thetaStart + thetaLength; + + var ix, iy; + + var index = 0; + var grid = []; + + var vertex = new Vector3(); + var normal = new Vector3(); // buffers @@ -28749,47 +28510,58 @@ var normals = []; var uvs = []; - // helper variables + // generate vertices, normals and uvs - var i, s; - var vertex = new Vector3(); - var uv = new Vector2(); + for ( iy = 0; iy <= heightSegments; iy ++ ) { - // center point + var verticesRow = []; - vertices.push( 0, 0, 0 ); - normals.push( 0, 0, 1 ); - uvs.push( 0.5, 0.5 ); + var v = iy / heightSegments; - for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) { + for ( ix = 0; ix <= widthSegments; ix ++ ) { - var segment = thetaStart + s / segments * thetaLength; + var u = ix / widthSegments; - // vertex + // vertex - vertex.x = radius * Math.cos( segment ); - vertex.y = radius * Math.sin( segment ); + vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); + vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); + vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); - vertices.push( vertex.x, vertex.y, vertex.z ); + vertices.push( vertex.x, vertex.y, vertex.z ); - // normal + // normal - normals.push( 0, 0, 1 ); + normal.set( vertex.x, vertex.y, vertex.z ).normalize(); + normals.push( normal.x, normal.y, normal.z ); - // uvs + // uv - uv.x = ( vertices[ i ] / radius + 1 ) / 2; - uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; + uvs.push( u, 1 - v ); - uvs.push( uv.x, uv.y ); + verticesRow.push( index ++ ); + + } + + grid.push( verticesRow ); } // indices - for ( i = 1; i <= segments; i ++ ) { + for ( iy = 0; iy < heightSegments; iy ++ ) { - indices.push( i, i + 1, 0 ); + for ( ix = 0; ix < widthSegments; ix ++ ) { + + var a = grid[ iy ][ ix + 1 ]; + var b = grid[ iy ][ ix ]; + var c = grid[ iy + 1 ][ ix ]; + var d = grid[ iy + 1 ][ ix + 1 ]; + + if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d ); + if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d ); + + } } @@ -28802,19 +28574,1133 @@ } - CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); - CircleBufferGeometry.prototype.constructor = CircleBufferGeometry; + SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + SphereBufferGeometry.prototype.constructor = SphereBufferGeometry; + /** + * @author Kaleb Murphy + * @author Mugen87 / https://github.com/Mugen87 + */ + // RingGeometry - var Geometries = Object.freeze({ - WireframeGeometry: WireframeGeometry, - ParametricGeometry: ParametricGeometry, - ParametricBufferGeometry: ParametricBufferGeometry, - TetrahedronGeometry: TetrahedronGeometry, - TetrahedronBufferGeometry: TetrahedronBufferGeometry, - OctahedronGeometry: OctahedronGeometry, - OctahedronBufferGeometry: OctahedronBufferGeometry, + function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + + Geometry.call( this ); + + this.type = 'RingGeometry'; + + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); + this.mergeVertices(); + + } + + RingGeometry.prototype = Object.create( Geometry.prototype ); + RingGeometry.prototype.constructor = RingGeometry; + + // RingBufferGeometry + + function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { + + BufferGeometry.call( this ); + + this.type = 'RingBufferGeometry'; + + this.parameters = { + innerRadius: innerRadius, + outerRadius: outerRadius, + thetaSegments: thetaSegments, + phiSegments: phiSegments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + innerRadius = innerRadius || 0.5; + outerRadius = outerRadius || 1; + + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; + + thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; + phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1; + + // buffers + + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; + + // some helper variables + + var segment; + var radius = innerRadius; + var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); + var vertex = new Vector3(); + var uv = new Vector2(); + var j, i; + + // generate vertices, normals and uvs + + for ( j = 0; j <= phiSegments; j ++ ) { + + for ( i = 0; i <= thetaSegments; i ++ ) { + + // values are generate from the inside of the ring to the outside + + segment = thetaStart + i / thetaSegments * thetaLength; + + // vertex + + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, 0, 1 ); + + // uv + + uv.x = ( vertex.x / outerRadius + 1 ) / 2; + uv.y = ( vertex.y / outerRadius + 1 ) / 2; + + uvs.push( uv.x, uv.y ); + + } + + // increase the radius for next row of vertices + + radius += radiusStep; + + } + + // indices + + for ( j = 0; j < phiSegments; j ++ ) { + + var thetaSegmentLevel = j * ( thetaSegments + 1 ); + + for ( i = 0; i < thetaSegments; i ++ ) { + + segment = i + thetaSegmentLevel; + + var a = segment; + var b = segment + thetaSegments + 1; + var c = segment + thetaSegments + 2; + var d = segment + 1; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + RingBufferGeometry.prototype.constructor = RingBufferGeometry; + + /** + * @author astrodud / http://astrodud.isgreat.org/ + * @author zz85 / https://github.com/zz85 + * @author bhouston / http://clara.io + * @author Mugen87 / https://github.com/Mugen87 + */ + + // LatheGeometry + + function LatheGeometry( points, segments, phiStart, phiLength ) { + + Geometry.call( this ); + + this.type = 'LatheGeometry'; + + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; + + this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) ); + this.mergeVertices(); + + } + + LatheGeometry.prototype = Object.create( Geometry.prototype ); + LatheGeometry.prototype.constructor = LatheGeometry; + + // LatheBufferGeometry + + function LatheBufferGeometry( points, segments, phiStart, phiLength ) { + + BufferGeometry.call( this ); + + this.type = 'LatheBufferGeometry'; + + this.parameters = { + points: points, + segments: segments, + phiStart: phiStart, + phiLength: phiLength + }; + + segments = Math.floor( segments ) || 12; + phiStart = phiStart || 0; + phiLength = phiLength || Math.PI * 2; + + // clamp phiLength so it's in range of [ 0, 2PI ] + + phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 ); + + + // buffers + + var indices = []; + var vertices = []; + var uvs = []; + + // helper variables + + var base; + var inverseSegments = 1.0 / segments; + var vertex = new Vector3(); + var uv = new Vector2(); + var i, j; + + // generate vertices and uvs + + for ( i = 0; i <= segments; i ++ ) { + + var phi = phiStart + i * inverseSegments * phiLength; + + var sin = Math.sin( phi ); + var cos = Math.cos( phi ); + + for ( j = 0; j <= ( points.length - 1 ); j ++ ) { + + // vertex + + vertex.x = points[ j ].x * sin; + vertex.y = points[ j ].y; + vertex.z = points[ j ].x * cos; + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // uv + + uv.x = i / segments; + uv.y = j / ( points.length - 1 ); + + uvs.push( uv.x, uv.y ); + + + } + + } + + // indices + + for ( i = 0; i < segments; i ++ ) { + + for ( j = 0; j < ( points.length - 1 ); j ++ ) { + + base = j + i * points.length; + + var a = base; + var b = base + points.length; + var c = base + points.length + 1; + var d = base + 1; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + } + + } + + // build geometry + + this.setIndex( indices ); + this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + // generate normals + + this.computeVertexNormals(); + + // if the geometry is closed, we need to average the normals along the seam. + // because the corresponding vertices are identical (but still have different UVs). + + if ( phiLength === Math.PI * 2 ) { + + var normals = this.attributes.normal.array; + var n1 = new Vector3(); + var n2 = new Vector3(); + var n = new Vector3(); + + // this is the buffer offset for the last line of vertices + + base = segments * points.length * 3; + + for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) { + + // select the normal of the vertex in the first line + + n1.x = normals[ j + 0 ]; + n1.y = normals[ j + 1 ]; + n1.z = normals[ j + 2 ]; + + // select the normal of the vertex in the last line + + n2.x = normals[ base + j + 0 ]; + n2.y = normals[ base + j + 1 ]; + n2.z = normals[ base + j + 2 ]; + + // average normals + + n.addVectors( n1, n2 ).normalize(); + + // assign the new values to both normals + + normals[ j + 0 ] = normals[ base + j + 0 ] = n.x; + normals[ j + 1 ] = normals[ base + j + 1 ] = n.y; + normals[ j + 2 ] = normals[ base + j + 2 ] = n.z; + + } + + } + + } + + LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + LatheBufferGeometry.prototype.constructor = LatheBufferGeometry; + + /** + * @author jonobr1 / http://jonobr1.com + * @author Mugen87 / https://github.com/Mugen87 + */ + + // ShapeGeometry + + function ShapeGeometry( shapes, curveSegments ) { + + Geometry.call( this ); + + this.type = 'ShapeGeometry'; + + if ( typeof curveSegments === 'object' ) { + + console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' ); + + curveSegments = curveSegments.curveSegments; + + } + + this.parameters = { + shapes: shapes, + curveSegments: curveSegments + }; + + this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) ); + this.mergeVertices(); + + } + + ShapeGeometry.prototype = Object.create( Geometry.prototype ); + ShapeGeometry.prototype.constructor = ShapeGeometry; + + ShapeGeometry.prototype.toJSON = function () { + + var data = Geometry.prototype.toJSON.call( this ); + + var shapes = this.parameters.shapes; + + return toJSON( shapes, data ); + + }; + + // ShapeBufferGeometry + + function ShapeBufferGeometry( shapes, curveSegments ) { + + BufferGeometry.call( this ); + + this.type = 'ShapeBufferGeometry'; + + this.parameters = { + shapes: shapes, + curveSegments: curveSegments + }; + + curveSegments = curveSegments || 12; + + // buffers + + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; + + // helper variables + + var groupStart = 0; + var groupCount = 0; + + // allow single and array values for "shapes" parameter + + if ( Array.isArray( shapes ) === false ) { + + addShape( shapes ); + + } else { + + for ( var i = 0; i < shapes.length; i ++ ) { + + addShape( shapes[ i ] ); + + this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support + + groupStart += groupCount; + groupCount = 0; + + } + + } + + // build geometry + + this.setIndex( indices ); + this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + + // helper functions + + function addShape( shape ) { + + var i, l, shapeHole; + + var indexOffset = vertices.length / 3; + var points = shape.extractPoints( curveSegments ); + + var shapeVertices = points.shape; + var shapeHoles = points.holes; + + // check direction of vertices + + if ( ShapeUtils.isClockWise( shapeVertices ) === false ) { + + shapeVertices = shapeVertices.reverse(); + + // also check if holes are in the opposite direction + + for ( i = 0, l = shapeHoles.length; i < l; i ++ ) { + + shapeHole = shapeHoles[ i ]; + + if ( ShapeUtils.isClockWise( shapeHole ) === true ) { + + shapeHoles[ i ] = shapeHole.reverse(); + + } + + } + + } + + var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles ); + + // join vertices of inner and outer paths to a single array + + for ( i = 0, l = shapeHoles.length; i < l; i ++ ) { + + shapeHole = shapeHoles[ i ]; + shapeVertices = shapeVertices.concat( shapeHole ); + + } + + // vertices, normals, uvs + + for ( i = 0, l = shapeVertices.length; i < l; i ++ ) { + + var vertex = shapeVertices[ i ]; + + vertices.push( vertex.x, vertex.y, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( vertex.x, vertex.y ); // world uvs + + } + + // incides + + for ( i = 0, l = faces.length; i < l; i ++ ) { + + var face = faces[ i ]; + + var a = face[ 0 ] + indexOffset; + var b = face[ 1 ] + indexOffset; + var c = face[ 2 ] + indexOffset; + + indices.push( a, b, c ); + groupCount += 3; + + } + + } + + } + + ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry; + + ShapeBufferGeometry.prototype.toJSON = function () { + + var data = BufferGeometry.prototype.toJSON.call( this ); + + var shapes = this.parameters.shapes; + + return toJSON( shapes, data ); + + }; + + // + + function toJSON( shapes, data ) { + + data.shapes = []; + + if ( Array.isArray( shapes ) ) { + + for ( var i = 0, l = shapes.length; i < l; i ++ ) { + + var shape = shapes[ i ]; + + data.shapes.push( shape.uuid ); + + } + + } else { + + data.shapes.push( shapes.uuid ); + + } + + return data; + + } + + /** + * @author WestLangley / http://github.com/WestLangley + * @author Mugen87 / https://github.com/Mugen87 + */ + + function EdgesGeometry( geometry, thresholdAngle ) { + + BufferGeometry.call( this ); + + this.type = 'EdgesGeometry'; + + this.parameters = { + thresholdAngle: thresholdAngle + }; + + thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; + + // buffer + + var vertices = []; + + // helper variables + + var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle ); + var edge = [ 0, 0 ], edges = {}, edge1, edge2; + var key, keys = [ 'a', 'b', 'c' ]; + + // prepare source geometry + + var geometry2; + + if ( geometry.isBufferGeometry ) { + + geometry2 = new Geometry(); + geometry2.fromBufferGeometry( geometry ); + + } else { + + geometry2 = geometry.clone(); + + } + + geometry2.mergeVertices(); + geometry2.computeFaceNormals(); + + var sourceVertices = geometry2.vertices; + var faces = geometry2.faces; + + // now create a data structure where each entry represents an edge with its adjoining faces + + for ( var i = 0, l = faces.length; i < l; i ++ ) { + + var face = faces[ i ]; + + for ( var j = 0; j < 3; j ++ ) { + + edge1 = face[ keys[ j ] ]; + edge2 = face[ keys[ ( j + 1 ) % 3 ] ]; + edge[ 0 ] = Math.min( edge1, edge2 ); + edge[ 1 ] = Math.max( edge1, edge2 ); + + key = edge[ 0 ] + ',' + edge[ 1 ]; + + if ( edges[ key ] === undefined ) { + + edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined }; + + } else { + + edges[ key ].face2 = i; + + } + + } + + } + + // generate vertices + + for ( key in edges ) { + + var e = edges[ key ]; + + // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree. + + if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) { + + var vertex = sourceVertices[ e.index1 ]; + vertices.push( vertex.x, vertex.y, vertex.z ); + + vertex = sourceVertices[ e.index2 ]; + vertices.push( vertex.x, vertex.y, vertex.z ); + + } + + } + + // build geometry + + this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + + } + + EdgesGeometry.prototype = Object.create( BufferGeometry.prototype ); + EdgesGeometry.prototype.constructor = EdgesGeometry; + + /** + * @author mrdoob / http://mrdoob.com/ + * @author Mugen87 / https://github.com/Mugen87 + */ + + // CylinderGeometry + + function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + + Geometry.call( this ); + + this.type = 'CylinderGeometry'; + + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); + this.mergeVertices(); + + } + + CylinderGeometry.prototype = Object.create( Geometry.prototype ); + CylinderGeometry.prototype.constructor = CylinderGeometry; + + // CylinderBufferGeometry + + function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + + BufferGeometry.call( this ); + + this.type = 'CylinderBufferGeometry'; + + this.parameters = { + radiusTop: radiusTop, + radiusBottom: radiusBottom, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + var scope = this; + + radiusTop = radiusTop !== undefined ? radiusTop : 1; + radiusBottom = radiusBottom !== undefined ? radiusBottom : 1; + height = height || 1; + + radialSegments = Math.floor( radialSegments ) || 8; + heightSegments = Math.floor( heightSegments ) || 1; + + openEnded = openEnded !== undefined ? openEnded : false; + thetaStart = thetaStart !== undefined ? thetaStart : 0.0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; + + // buffers + + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; + + // helper variables + + var index = 0; + var indexArray = []; + var halfHeight = height / 2; + var groupStart = 0; + + // generate geometry + + generateTorso(); + + if ( openEnded === false ) { + + if ( radiusTop > 0 ) generateCap( true ); + if ( radiusBottom > 0 ) generateCap( false ); + + } + + // build geometry + + this.setIndex( indices ); + this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + function generateTorso() { + + var x, y; + var normal = new Vector3(); + var vertex = new Vector3(); + + var groupCount = 0; + + // this will be used to calculate the normal + var slope = ( radiusBottom - radiusTop ) / height; + + // generate vertices, normals and uvs + + for ( y = 0; y <= heightSegments; y ++ ) { + + var indexRow = []; + + var v = y / heightSegments; + + // calculate the radius of the current row + + var radius = v * ( radiusBottom - radiusTop ) + radiusTop; + + for ( x = 0; x <= radialSegments; x ++ ) { + + var u = x / radialSegments; + + var theta = u * thetaLength + thetaStart; + + var sinTheta = Math.sin( theta ); + var cosTheta = Math.cos( theta ); + + // vertex + + vertex.x = radius * sinTheta; + vertex.y = - v * height + halfHeight; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normal.set( sinTheta, slope, cosTheta ).normalize(); + normals.push( normal.x, normal.y, normal.z ); + + // uv + + uvs.push( u, 1 - v ); + + // save index of vertex in respective row + + indexRow.push( index ++ ); + + } + + // now save vertices of the row in our index array + + indexArray.push( indexRow ); + + } + + // generate indices + + for ( x = 0; x < radialSegments; x ++ ) { + + for ( y = 0; y < heightSegments; y ++ ) { + + // we use the index array to access the correct indices + + var a = indexArray[ y ][ x ]; + var b = indexArray[ y + 1 ][ x ]; + var c = indexArray[ y + 1 ][ x + 1 ]; + var d = indexArray[ y ][ x + 1 ]; + + // faces + + indices.push( a, b, d ); + indices.push( b, c, d ); + + // update group counter + + groupCount += 6; + + } + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, 0 ); + + // calculate new start value for groups + + groupStart += groupCount; + + } + + function generateCap( top ) { + + var x, centerIndexStart, centerIndexEnd; + + var uv = new Vector2(); + var vertex = new Vector3(); + + var groupCount = 0; + + var radius = ( top === true ) ? radiusTop : radiusBottom; + var sign = ( top === true ) ? 1 : - 1; + + // save the index of the first center vertex + centerIndexStart = index; + + // first we generate the center vertex data of the cap. + // because the geometry needs one set of uvs per face, + // we must generate a center vertex per face/segment + + for ( x = 1; x <= radialSegments; x ++ ) { + + // vertex + + vertices.push( 0, halfHeight * sign, 0 ); + + // normal + + normals.push( 0, sign, 0 ); + + // uv + + uvs.push( 0.5, 0.5 ); + + // increase index + + index ++; + + } + + // save the index of the last center vertex + + centerIndexEnd = index; + + // now we generate the surrounding vertices, normals and uvs + + for ( x = 0; x <= radialSegments; x ++ ) { + + var u = x / radialSegments; + var theta = u * thetaLength + thetaStart; + + var cosTheta = Math.cos( theta ); + var sinTheta = Math.sin( theta ); + + // vertex + + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, sign, 0 ); + + // uv + + uv.x = ( cosTheta * 0.5 ) + 0.5; + uv.y = ( sinTheta * 0.5 * sign ) + 0.5; + uvs.push( uv.x, uv.y ); + + // increase index + + index ++; + + } + + // generate indices + + for ( x = 0; x < radialSegments; x ++ ) { + + var c = centerIndexStart + x; + var i = centerIndexEnd + x; + + if ( top === true ) { + + // face top + + indices.push( i, i + 1, c ); + + } else { + + // face bottom + + indices.push( i + 1, i, c ); + + } + + groupCount += 3; + + } + + // add a group to the geometry. this will ensure multi material support + + scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); + + // calculate new start value for groups + + groupStart += groupCount; + + } + + } + + CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry; + + /** + * @author abelnation / http://github.com/abelnation + */ + + // ConeGeometry + + function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + + CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); + + this.type = 'ConeGeometry'; + + this.parameters = { + radius: radius, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + } + + ConeGeometry.prototype = Object.create( CylinderGeometry.prototype ); + ConeGeometry.prototype.constructor = ConeGeometry; + + // ConeBufferGeometry + + function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { + + CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); + + this.type = 'ConeBufferGeometry'; + + this.parameters = { + radius: radius, + height: height, + radialSegments: radialSegments, + heightSegments: heightSegments, + openEnded: openEnded, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + } + + ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype ); + ConeBufferGeometry.prototype.constructor = ConeBufferGeometry; + + /** + * @author benaadams / https://twitter.com/ben_a_adams + * @author Mugen87 / https://github.com/Mugen87 + * @author hughes + */ + + // CircleGeometry + + function CircleGeometry( radius, segments, thetaStart, thetaLength ) { + + Geometry.call( this ); + + this.type = 'CircleGeometry'; + + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); + this.mergeVertices(); + + } + + CircleGeometry.prototype = Object.create( Geometry.prototype ); + CircleGeometry.prototype.constructor = CircleGeometry; + + // CircleBufferGeometry + + function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) { + + BufferGeometry.call( this ); + + this.type = 'CircleBufferGeometry'; + + this.parameters = { + radius: radius, + segments: segments, + thetaStart: thetaStart, + thetaLength: thetaLength + }; + + radius = radius || 1; + segments = segments !== undefined ? Math.max( 3, segments ) : 8; + + thetaStart = thetaStart !== undefined ? thetaStart : 0; + thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; + + // buffers + + var indices = []; + var vertices = []; + var normals = []; + var uvs = []; + + // helper variables + + var i, s; + var vertex = new Vector3(); + var uv = new Vector2(); + + // center point + + vertices.push( 0, 0, 0 ); + normals.push( 0, 0, 1 ); + uvs.push( 0.5, 0.5 ); + + for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) { + + var segment = thetaStart + s / segments * thetaLength; + + // vertex + + vertex.x = radius * Math.cos( segment ); + vertex.y = radius * Math.sin( segment ); + + vertices.push( vertex.x, vertex.y, vertex.z ); + + // normal + + normals.push( 0, 0, 1 ); + + // uvs + + uv.x = ( vertices[ i ] / radius + 1 ) / 2; + uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; + + uvs.push( uv.x, uv.y ); + + } + + // indices + + for ( i = 1; i <= segments; i ++ ) { + + indices.push( i, i + 1, 0 ); + + } + + // build geometry + + this.setIndex( indices ); + this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); + this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + + } + + CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); + CircleBufferGeometry.prototype.constructor = CircleBufferGeometry; + + + + var Geometries = Object.freeze({ + WireframeGeometry: WireframeGeometry, + ParametricGeometry: ParametricGeometry, + ParametricBufferGeometry: ParametricBufferGeometry, + TetrahedronGeometry: TetrahedronGeometry, + TetrahedronBufferGeometry: TetrahedronBufferGeometry, + OctahedronGeometry: OctahedronGeometry, + OctahedronBufferGeometry: OctahedronBufferGeometry, IcosahedronGeometry: IcosahedronGeometry, IcosahedronBufferGeometry: IcosahedronBufferGeometry, DodecahedronGeometry: DodecahedronGeometry, @@ -28853,3042 +29739,4401 @@ }); /** - * @author mrdoob / http://mrdoob.com/ + * @author mrdoob / http://mrdoob.com/ + * + * parameters = { + * color: + * } + */ + + function ShadowMaterial( parameters ) { + + Material.call( this ); + + this.type = 'ShadowMaterial'; + + this.color = new Color( 0x000000 ); + this.transparent = true; + + this.setValues( parameters ); + + } + + ShadowMaterial.prototype = Object.create( Material.prototype ); + ShadowMaterial.prototype.constructor = ShadowMaterial; + + ShadowMaterial.prototype.isShadowMaterial = true; + + ShadowMaterial.prototype.copy = function ( source ) { + + Material.prototype.copy.call( this, source ); + + this.color.copy( source.color ); + + return this; + + }; + + /** + * @author mrdoob / http://mrdoob.com/ + */ + + function RawShaderMaterial( parameters ) { + + ShaderMaterial.call( this, parameters ); + + this.type = 'RawShaderMaterial'; + + } + + RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype ); + RawShaderMaterial.prototype.constructor = RawShaderMaterial; + + RawShaderMaterial.prototype.isRawShaderMaterial = true; + + /** + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * color: , + * roughness: , + * metalness: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * bumpMap: new THREE.Texture( ), + * bumpScale: , + * + * normalMap: new THREE.Texture( ), + * normalScale: , + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * roughnessMap: new THREE.Texture( ), + * + * metalnessMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), + * envMapIntensity: + * + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ + + function MeshStandardMaterial( parameters ) { + + Material.call( this ); + + this.defines = { 'STANDARD': '' }; + + this.type = 'MeshStandardMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + this.roughness = 0.5; + this.metalness = 0.5; + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.roughnessMap = null; + + this.metalnessMap = null; + + this.alphaMap = null; + + this.envMap = null; + this.envMapIntensity = 1.0; + + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; + + this.setValues( parameters ); + + } + + MeshStandardMaterial.prototype = Object.create( Material.prototype ); + MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; + + MeshStandardMaterial.prototype.isMeshStandardMaterial = true; + + MeshStandardMaterial.prototype.copy = function ( source ) { + + Material.prototype.copy.call( this, source ); + + this.defines = { 'STANDARD': '' }; + + this.color.copy( source.color ); + this.roughness = source.roughness; + this.metalness = source.metalness; + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.roughnessMap = source.roughnessMap; + + this.metalnessMap = source.metalnessMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.envMapIntensity = source.envMapIntensity; + + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; + + return this; + + }; + + /** + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * reflectivity: + * } + */ + + function MeshPhysicalMaterial( parameters ) { + + MeshStandardMaterial.call( this ); + + this.defines = { 'PHYSICAL': '' }; + + this.type = 'MeshPhysicalMaterial'; + + this.reflectivity = 0.5; // maps to F0 = 0.04 + + this.clearCoat = 0.0; + this.clearCoatRoughness = 0.0; + + this.setValues( parameters ); + + } + + MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); + MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; + + MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true; + + MeshPhysicalMaterial.prototype.copy = function ( source ) { + + MeshStandardMaterial.prototype.copy.call( this, source ); + + this.defines = { 'PHYSICAL': '' }; + + this.reflectivity = source.reflectivity; + + this.clearCoat = source.clearCoat; + this.clearCoatRoughness = source.clearCoatRoughness; + + return this; + + }; + + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * specular: , + * shininess: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * bumpMap: new THREE.Texture( ), + * bumpScale: , + * + * normalMap: new THREE.Texture( ), + * normalScale: , + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: , + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ + + function MeshPhongMaterial( parameters ) { + + Material.call( this ); + + this.type = 'MeshPhongMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + this.specular = new Color( 0x111111 ); + this.shininess = 30; + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.specularMap = null; + + this.alphaMap = null; + + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; + + this.setValues( parameters ); + + } + + MeshPhongMaterial.prototype = Object.create( Material.prototype ); + MeshPhongMaterial.prototype.constructor = MeshPhongMaterial; + + MeshPhongMaterial.prototype.isMeshPhongMaterial = true; + + MeshPhongMaterial.prototype.copy = function ( source ) { + + Material.prototype.copy.call( this, source ); + + this.color.copy( source.color ); + this.specular.copy( source.specular ); + this.shininess = source.shininess; + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; + + return this; + + }; + + /** + * @author takahirox / http://github.com/takahirox + * + * parameters = { + * gradientMap: new THREE.Texture( ) + * } + */ + + function MeshToonMaterial( parameters ) { + + MeshPhongMaterial.call( this ); + + this.defines = { 'TOON': '' }; + + this.type = 'MeshToonMaterial'; + + this.gradientMap = null; + + this.setValues( parameters ); + + } + + MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype ); + MeshToonMaterial.prototype.constructor = MeshToonMaterial; + + MeshToonMaterial.prototype.isMeshToonMaterial = true; + + MeshToonMaterial.prototype.copy = function ( source ) { + + MeshPhongMaterial.prototype.copy.call( this, source ); + + this.gradientMap = source.gradientMap; + + return this; + + }; + + /** + * @author mrdoob / http://mrdoob.com/ + * @author WestLangley / http://github.com/WestLangley + * + * parameters = { + * opacity: , + * + * bumpMap: new THREE.Texture( ), + * bumpScale: , + * + * normalMap: new THREE.Texture( ), + * normalScale: , + * + * displacementMap: new THREE.Texture( ), + * displacementScale: , + * displacementBias: , + * + * wireframe: , + * wireframeLinewidth: + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ + + function MeshNormalMaterial( parameters ) { + + Material.call( this ); + + this.type = 'MeshNormalMaterial'; + + this.bumpMap = null; + this.bumpScale = 1; + + this.normalMap = null; + this.normalScale = new Vector2( 1, 1 ); + + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + + this.wireframe = false; + this.wireframeLinewidth = 1; + + this.fog = false; + this.lights = false; + + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; + + this.setValues( parameters ); + + } + + MeshNormalMaterial.prototype = Object.create( Material.prototype ); + MeshNormalMaterial.prototype.constructor = MeshNormalMaterial; + + MeshNormalMaterial.prototype.isMeshNormalMaterial = true; + + MeshNormalMaterial.prototype.copy = function ( source ) { + + Material.prototype.copy.call( this, source ); + + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + + this.normalMap = source.normalMap; + this.normalScale.copy( source.normalScale ); + + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; + + return this; + + }; + + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * map: new THREE.Texture( ), + * + * lightMap: new THREE.Texture( ), + * lightMapIntensity: + * + * aoMap: new THREE.Texture( ), + * aoMapIntensity: + * + * emissive: , + * emissiveIntensity: + * emissiveMap: new THREE.Texture( ), + * + * specularMap: new THREE.Texture( ), + * + * alphaMap: new THREE.Texture( ), + * + * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), + * combine: THREE.Multiply, + * reflectivity: , + * refractionRatio: , + * + * wireframe: , + * wireframeLinewidth: , + * + * skinning: , + * morphTargets: , + * morphNormals: + * } + */ + + function MeshLambertMaterial( parameters ) { + + Material.call( this ); + + this.type = 'MeshLambertMaterial'; + + this.color = new Color( 0xffffff ); // diffuse + + this.map = null; + + this.lightMap = null; + this.lightMapIntensity = 1.0; + + this.aoMap = null; + this.aoMapIntensity = 1.0; + + this.emissive = new Color( 0x000000 ); + this.emissiveIntensity = 1.0; + this.emissiveMap = null; + + this.specularMap = null; + + this.alphaMap = null; + + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.skinning = false; + this.morphTargets = false; + this.morphNormals = false; + + this.setValues( parameters ); + + } + + MeshLambertMaterial.prototype = Object.create( Material.prototype ); + MeshLambertMaterial.prototype.constructor = MeshLambertMaterial; + + MeshLambertMaterial.prototype.isMeshLambertMaterial = true; + + MeshLambertMaterial.prototype.copy = function ( source ) { + + Material.prototype.copy.call( this, source ); + + this.color.copy( source.color ); + + this.map = source.map; + + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + + this.emissive.copy( source.emissive ); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + + this.specularMap = source.specularMap; + + this.alphaMap = source.alphaMap; + + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.skinning = source.skinning; + this.morphTargets = source.morphTargets; + this.morphNormals = source.morphNormals; + + return this; + + }; + + /** + * @author alteredq / http://alteredqualia.com/ + * + * parameters = { + * color: , + * opacity: , + * + * linewidth: , + * + * scale: , + * dashSize: , + * gapSize: + * } + */ + + function LineDashedMaterial( parameters ) { + + LineBasicMaterial.call( this ); + + this.type = 'LineDashedMaterial'; + + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; + + this.setValues( parameters ); + + } + + LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype ); + LineDashedMaterial.prototype.constructor = LineDashedMaterial; + + LineDashedMaterial.prototype.isLineDashedMaterial = true; + + LineDashedMaterial.prototype.copy = function ( source ) { + + LineBasicMaterial.prototype.copy.call( this, source ); + + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; + + return this; + + }; + + + + var Materials = Object.freeze({ + ShadowMaterial: ShadowMaterial, + SpriteMaterial: SpriteMaterial, + RawShaderMaterial: RawShaderMaterial, + ShaderMaterial: ShaderMaterial, + PointsMaterial: PointsMaterial, + MeshPhysicalMaterial: MeshPhysicalMaterial, + MeshStandardMaterial: MeshStandardMaterial, + MeshPhongMaterial: MeshPhongMaterial, + MeshToonMaterial: MeshToonMaterial, + MeshNormalMaterial: MeshNormalMaterial, + MeshLambertMaterial: MeshLambertMaterial, + MeshDepthMaterial: MeshDepthMaterial, + MeshDistanceMaterial: MeshDistanceMaterial, + MeshBasicMaterial: MeshBasicMaterial, + LineDashedMaterial: LineDashedMaterial, + LineBasicMaterial: LineBasicMaterial, + Material: Material + }); + + /** + * @author mrdoob / http://mrdoob.com/ + */ + + var Cache = { + + enabled: false, + + files: {}, + + add: function ( key, file ) { + + if ( this.enabled === false ) return; + + // console.log( 'THREE.Cache', 'Adding key:', key ); + + this.files[ key ] = file; + + }, + + get: function ( key ) { + + if ( this.enabled === false ) return; + + // console.log( 'THREE.Cache', 'Checking key:', key ); + + return this.files[ key ]; + + }, + + remove: function ( key ) { + + delete this.files[ key ]; + + }, + + clear: function () { + + this.files = {}; + + } + + }; + + /** + * @author mrdoob / http://mrdoob.com/ + */ + + function LoadingManager( onLoad, onProgress, onError ) { + + var scope = this; + + var isLoading = false; + var itemsLoaded = 0; + var itemsTotal = 0; + var urlModifier = undefined; + + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; + + this.itemStart = function ( url ) { + + itemsTotal ++; + + if ( isLoading === false ) { + + if ( scope.onStart !== undefined ) { + + scope.onStart( url, itemsLoaded, itemsTotal ); + + } + + } + + isLoading = true; + + }; + + this.itemEnd = function ( url ) { + + itemsLoaded ++; + + if ( scope.onProgress !== undefined ) { + + scope.onProgress( url, itemsLoaded, itemsTotal ); + + } + + if ( itemsLoaded === itemsTotal ) { + + isLoading = false; + + if ( scope.onLoad !== undefined ) { + + scope.onLoad(); + + } + + } + + }; + + this.itemError = function ( url ) { + + if ( scope.onError !== undefined ) { + + scope.onError( url ); + + } + + }; + + this.resolveURL = function ( url ) { + + if ( urlModifier ) { + + return urlModifier( url ); + + } + + return url; + + }; + + this.setURLModifier = function ( transform ) { + + urlModifier = transform; + return this; + + }; + + } + + var DefaultLoadingManager = new LoadingManager(); + + /** + * @author mrdoob / http://mrdoob.com/ + */ + + var loading = {}; + + function FileLoader( manager ) { + + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + + } + + Object.assign( FileLoader.prototype, { + + load: function ( url, onLoad, onProgress, onError ) { + + if ( url === undefined ) url = ''; + + if ( this.path !== undefined ) url = this.path + url; + + url = this.manager.resolveURL( url ); + + var scope = this; + + var cached = Cache.get( url ); + + if ( cached !== undefined ) { + + scope.manager.itemStart( url ); + + setTimeout( function () { + + if ( onLoad ) onLoad( cached ); + + scope.manager.itemEnd( url ); + + }, 0 ); + + return cached; + + } + + // Check if request is duplicate + + if ( loading[ url ] !== undefined ) { + + loading[ url ].push( { + + onLoad: onLoad, + onProgress: onProgress, + onError: onError + + } ); + + return; + + } + + // Check for data: URI + var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/; + var dataUriRegexResult = url.match( dataUriRegex ); + + // Safari can not handle Data URIs through XMLHttpRequest so process manually + if ( dataUriRegexResult ) { + + var mimeType = dataUriRegexResult[ 1 ]; + var isBase64 = !! dataUriRegexResult[ 2 ]; + var data = dataUriRegexResult[ 3 ]; + + data = window.decodeURIComponent( data ); + + if ( isBase64 ) data = window.atob( data ); + + try { + + var response; + var responseType = ( this.responseType || '' ).toLowerCase(); + + switch ( responseType ) { + + case 'arraybuffer': + case 'blob': + + var view = new Uint8Array( data.length ); + + for ( var i = 0; i < data.length; i ++ ) { + + view[ i ] = data.charCodeAt( i ); + + } + + if ( responseType === 'blob' ) { + + response = new Blob( [ view.buffer ], { type: mimeType } ); + + } else { + + response = view.buffer; + + } + + break; + + case 'document': + + var parser = new DOMParser(); + response = parser.parseFromString( data, mimeType ); + + break; + + case 'json': + + response = JSON.parse( data ); + + break; + + default: // 'text' or other + + response = data; + + break; + + } + + // Wait for next browser tick like standard XMLHttpRequest event dispatching does + window.setTimeout( function () { + + if ( onLoad ) onLoad( response ); + + scope.manager.itemEnd( url ); + + }, 0 ); + + } catch ( error ) { + + // Wait for next browser tick like standard XMLHttpRequest event dispatching does + window.setTimeout( function () { + + if ( onError ) onError( error ); + + scope.manager.itemEnd( url ); + scope.manager.itemError( url ); + + }, 0 ); + + } + + } else { + + // Initialise array for duplicate requests + + loading[ url ] = []; + + loading[ url ].push( { + + onLoad: onLoad, + onProgress: onProgress, + onError: onError + + } ); + + var request = new XMLHttpRequest(); + + request.open( 'GET', url, true ); + + request.addEventListener( 'load', function ( event ) { + + var response = this.response; + + Cache.add( url, response ); + + var callbacks = loading[ url ]; + + delete loading[ url ]; + + if ( this.status === 200 ) { + + for ( var i = 0, il = callbacks.length; i < il; i ++ ) { + + var callback = callbacks[ i ]; + if ( callback.onLoad ) callback.onLoad( response ); + + } + + scope.manager.itemEnd( url ); + + } else if ( this.status === 0 ) { + + // Some browsers return HTTP Status 0 when using non-http protocol + // e.g. 'file://' or 'data://'. Handle as success. + + console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); + + for ( var i = 0, il = callbacks.length; i < il; i ++ ) { + + var callback = callbacks[ i ]; + if ( callback.onLoad ) callback.onLoad( response ); + + } + + scope.manager.itemEnd( url ); + + } else { + + for ( var i = 0, il = callbacks.length; i < il; i ++ ) { + + var callback = callbacks[ i ]; + if ( callback.onError ) callback.onError( event ); + + } + + scope.manager.itemEnd( url ); + scope.manager.itemError( url ); + + } + + }, false ); + + request.addEventListener( 'progress', function ( event ) { + + var callbacks = loading[ url ]; + + for ( var i = 0, il = callbacks.length; i < il; i ++ ) { + + var callback = callbacks[ i ]; + if ( callback.onProgress ) callback.onProgress( event ); + + } + + }, false ); + + request.addEventListener( 'error', function ( event ) { + + var callbacks = loading[ url ]; + + delete loading[ url ]; + + for ( var i = 0, il = callbacks.length; i < il; i ++ ) { + + var callback = callbacks[ i ]; + if ( callback.onError ) callback.onError( event ); + + } + + scope.manager.itemEnd( url ); + scope.manager.itemError( url ); + + }, false ); + + if ( this.responseType !== undefined ) request.responseType = this.responseType; + if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials; + + if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' ); + + for ( var header in this.requestHeader ) { + + request.setRequestHeader( header, this.requestHeader[ header ] ); + + } + + request.send( null ); + + } + + scope.manager.itemStart( url ); + + return request; + + }, + + setPath: function ( value ) { + + this.path = value; + return this; + + }, + + setResponseType: function ( value ) { + + this.responseType = value; + return this; + + }, + + setWithCredentials: function ( value ) { + + this.withCredentials = value; + return this; + + }, + + setMimeType: function ( value ) { + + this.mimeType = value; + return this; + + }, + + setRequestHeader: function ( value ) { + + this.requestHeader = value; + return this; + + } + + } ); + + /** + * @author mrdoob / http://mrdoob.com/ + * + * Abstract Base class to block based textures loader (dds, pvr, ...) + */ + + function CompressedTextureLoader( manager ) { + + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + + // override in sub classes + this._parser = null; + + } + + Object.assign( CompressedTextureLoader.prototype, { + + load: function ( url, onLoad, onProgress, onError ) { + + var scope = this; + + var images = []; + + var texture = new CompressedTexture(); + texture.image = images; + + var loader = new FileLoader( this.manager ); + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); + + function loadTexture( i ) { + + loader.load( url[ i ], function ( buffer ) { + + var texDatas = scope._parser( buffer, true ); + + images[ i ] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; + + loaded += 1; + + if ( loaded === 6 ) { + + if ( texDatas.mipmapCount === 1 ) + texture.minFilter = LinearFilter; + + texture.format = texDatas.format; + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + } + + }, onProgress, onError ); + + } + + if ( Array.isArray( url ) ) { + + var loaded = 0; + + for ( var i = 0, il = url.length; i < il; ++ i ) { + + loadTexture( i ); + + } + + } else { + + // compressed cubemap texture stored in a single DDS file + + loader.load( url, function ( buffer ) { + + var texDatas = scope._parser( buffer, true ); + + if ( texDatas.isCubemap ) { + + var faces = texDatas.mipmaps.length / texDatas.mipmapCount; + + for ( var f = 0; f < faces; f ++ ) { + + images[ f ] = { mipmaps: [] }; + + for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { + + images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] ); + images[ f ].format = texDatas.format; + images[ f ].width = texDatas.width; + images[ f ].height = texDatas.height; + + } + + } + + } else { + + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; + + } + + if ( texDatas.mipmapCount === 1 ) { + + texture.minFilter = LinearFilter; + + } + + texture.format = texDatas.format; + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture ); + + }, onProgress, onError ); + + } + + return texture; + + }, + + setPath: function ( value ) { + + this.path = value; + return this; + + } + + } ); + + /** + * @author Nikos M. / https://github.com/foo123/ * - * parameters = { - * opacity: - * } + * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) */ - function ShadowMaterial( parameters ) { + function DataTextureLoader( manager ) { + + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + + // override in sub classes + this._parser = null; + + } + + Object.assign( DataTextureLoader.prototype, { + + load: function ( url, onLoad, onProgress, onError ) { + + var scope = this; + + var texture = new DataTexture(); + + var loader = new FileLoader( this.manager ); + loader.setResponseType( 'arraybuffer' ); + + loader.load( url, function ( buffer ) { + + var texData = scope._parser( buffer ); + + if ( ! texData ) return; + + if ( undefined !== texData.image ) { + + texture.image = texData.image; + + } else if ( undefined !== texData.data ) { + + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; - ShaderMaterial.call( this, { - uniforms: UniformsUtils.merge( [ - UniformsLib.lights, - { - opacity: { value: 1.0 } } - ] ), - vertexShader: ShaderChunk[ 'shadow_vert' ], - fragmentShader: ShaderChunk[ 'shadow_frag' ] - } ); - this.lights = true; - this.transparent = true; + texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping; + + texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter; + texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter; + + texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; + + if ( undefined !== texData.format ) { + + texture.format = texData.format; - Object.defineProperties( this, { - opacity: { - enumerable: true, - get: function () { - return this.uniforms.opacity.value; - }, - set: function ( value ) { - this.uniforms.opacity.value = value; } - } - } ); + if ( undefined !== texData.type ) { - this.setValues( parameters ); + texture.type = texData.type; - } + } - ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype ); - ShadowMaterial.prototype.constructor = ShadowMaterial; + if ( undefined !== texData.mipmaps ) { - ShadowMaterial.prototype.isShadowMaterial = true; + texture.mipmaps = texData.mipmaps; + + } + + if ( 1 === texData.mipmapCount ) { + + texture.minFilter = LinearFilter; + + } + + texture.needsUpdate = true; + + if ( onLoad ) onLoad( texture, texData ); + + }, onProgress, onError ); + + + return texture; + + } + + } ); /** * @author mrdoob / http://mrdoob.com/ */ - function RawShaderMaterial( parameters ) { - - ShaderMaterial.call( this, parameters ); + function ImageLoader( manager ) { - this.type = 'RawShaderMaterial'; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; } - RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype ); - RawShaderMaterial.prototype.constructor = RawShaderMaterial; + Object.assign( ImageLoader.prototype, { - RawShaderMaterial.prototype.isRawShaderMaterial = true; + crossOrigin: 'Anonymous', - /** - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * color: , - * roughness: , - * metalness: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * roughnessMap: new THREE.Texture( ), - * - * metalnessMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), - * envMapIntensity: - * - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + load: function ( url, onLoad, onProgress, onError ) { - function MeshStandardMaterial( parameters ) { + if ( url === undefined ) url = ''; - Material.call( this ); + if ( this.path !== undefined ) url = this.path + url; - this.defines = { 'STANDARD': '' }; + url = this.manager.resolveURL( url ); - this.type = 'MeshStandardMaterial'; + var scope = this; - this.color = new Color( 0xffffff ); // diffuse - this.roughness = 0.5; - this.metalness = 0.5; + var cached = Cache.get( url ); - this.map = null; + if ( cached !== undefined ) { - this.lightMap = null; - this.lightMapIntensity = 1.0; + scope.manager.itemStart( url ); - this.aoMap = null; - this.aoMapIntensity = 1.0; + setTimeout( function () { - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + if ( onLoad ) onLoad( cached ); - this.bumpMap = null; - this.bumpScale = 1; + scope.manager.itemEnd( url ); - this.normalMap = null; - this.normalScale = new Vector2( 1, 1 ); + }, 0 ); - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + return cached; - this.roughnessMap = null; + } - this.metalnessMap = null; + var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); - this.alphaMap = null; + image.addEventListener( 'load', function () { - this.envMap = null; - this.envMapIntensity = 1.0; + Cache.add( url, this ); - this.refractionRatio = 0.98; + if ( onLoad ) onLoad( this ); - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + scope.manager.itemEnd( url ); - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + }, false ); - this.setValues( parameters ); + /* + image.addEventListener( 'progress', function ( event ) { + + if ( onProgress ) onProgress( event ); + + }, false ); + */ + + image.addEventListener( 'error', function ( event ) { + + if ( onError ) onError( event ); + + scope.manager.itemEnd( url ); + scope.manager.itemError( url ); + + }, false ); + + if ( url.substr( 0, 5 ) !== 'data:' ) { + + if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; + + } + + scope.manager.itemStart( url ); + + image.src = url; + + return image; + + }, + + setCrossOrigin: function ( value ) { + + this.crossOrigin = value; + return this; + + }, + + setPath: function ( value ) { + + this.path = value; + return this; + + } + + } ); + + /** + * @author mrdoob / http://mrdoob.com/ + */ + + function CubeTextureLoader( manager ) { + + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; } - MeshStandardMaterial.prototype = Object.create( Material.prototype ); - MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; + Object.assign( CubeTextureLoader.prototype, { - MeshStandardMaterial.prototype.isMeshStandardMaterial = true; + crossOrigin: 'Anonymous', - MeshStandardMaterial.prototype.copy = function ( source ) { + load: function ( urls, onLoad, onProgress, onError ) { - Material.prototype.copy.call( this, source ); + var texture = new CubeTexture(); - this.defines = { 'STANDARD': '' }; + var loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); - this.color.copy( source.color ); - this.roughness = source.roughness; - this.metalness = source.metalness; + var loaded = 0; - this.map = source.map; + function loadTexture( i ) { - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + loader.load( urls[ i ], function ( image ) { - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + texture.images[ i ] = image; - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + loaded ++; - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + if ( loaded === 6 ) { - this.normalMap = source.normalMap; - this.normalScale.copy( source.normalScale ); + texture.needsUpdate = true; - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + if ( onLoad ) onLoad( texture ); - this.roughnessMap = source.roughnessMap; + } - this.metalnessMap = source.metalnessMap; + }, undefined, onError ); - this.alphaMap = source.alphaMap; + } - this.envMap = source.envMap; - this.envMapIntensity = source.envMapIntensity; + for ( var i = 0; i < urls.length; ++ i ) { - this.refractionRatio = source.refractionRatio; + loadTexture( i ); - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + } - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + return texture; - return this; + }, - }; + setCrossOrigin: function ( value ) { + + this.crossOrigin = value; + return this; + + }, + + setPath: function ( value ) { + + this.path = value; + return this; + + } + + } ); /** - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * reflectivity: - * } + * @author mrdoob / http://mrdoob.com/ */ - function MeshPhysicalMaterial( parameters ) { + function TextureLoader( manager ) { - MeshStandardMaterial.call( this ); + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; - this.defines = { 'PHYSICAL': '' }; + } - this.type = 'MeshPhysicalMaterial'; + Object.assign( TextureLoader.prototype, { - this.reflectivity = 0.5; // maps to F0 = 0.04 + crossOrigin: 'Anonymous', - this.clearCoat = 0.0; - this.clearCoatRoughness = 0.0; + load: function ( url, onLoad, onProgress, onError ) { - this.setValues( parameters ); + var texture = new Texture(); - } + var loader = new ImageLoader( this.manager ); + loader.setCrossOrigin( this.crossOrigin ); + loader.setPath( this.path ); - MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); - MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; + loader.load( url, function ( image ) { - MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true; + texture.image = image; - MeshPhysicalMaterial.prototype.copy = function ( source ) { + // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. + var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; - MeshStandardMaterial.prototype.copy.call( this, source ); + texture.format = isJPEG ? RGBFormat : RGBAFormat; + texture.needsUpdate = true; - this.defines = { 'PHYSICAL': '' }; + if ( onLoad !== undefined ) { - this.reflectivity = source.reflectivity; + onLoad( texture ); - this.clearCoat = source.clearCoat; - this.clearCoatRoughness = source.clearCoatRoughness; + } - return this; + }, onProgress, onError ); - }; + return texture; + + }, + + setCrossOrigin: function ( value ) { + + this.crossOrigin = value; + return this; + + }, + + setPath: function ( value ) { + + this.path = value; + return this; + + } + + } ); /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * specular: , - * shininess: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , + * @author zz85 / http://www.lab4games.net/zz85/blog + * Extensible curve object * - * specularMap: new THREE.Texture( ), + * Some common of curve methods: + * .getPoint( t, optionalTarget ), .getTangent( t ) + * .getPointAt( u, optionalTarget ), .getTangentAt( u ) + * .getPoints(), .getSpacedPoints() + * .getLength() + * .updateArcLengths() * - * alphaMap: new THREE.Texture( ), + * This following curves inherit from THREE.Curve: * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , + * -- 2D curves -- + * THREE.ArcCurve + * THREE.CubicBezierCurve + * THREE.EllipseCurve + * THREE.LineCurve + * THREE.QuadraticBezierCurve + * THREE.SplineCurve * - * wireframe: , - * wireframeLinewidth: , + * -- 3D curves -- + * THREE.CatmullRomCurve3 + * THREE.CubicBezierCurve3 + * THREE.LineCurve3 + * THREE.QuadraticBezierCurve3 * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + * A series of curves can be represented as a THREE.CurvePath. + * + **/ - function MeshPhongMaterial( parameters ) { + /************************************************************** + * Abstract Curve base class + **************************************************************/ - Material.call( this ); + function Curve() { - this.type = 'MeshPhongMaterial'; + this.type = 'Curve'; - this.color = new Color( 0xffffff ); // diffuse - this.specular = new Color( 0x111111 ); - this.shininess = 30; + this.arcLengthDivisions = 200; - this.map = null; + } - this.lightMap = null; - this.lightMapIntensity = 1.0; + Object.assign( Curve.prototype, { - this.aoMap = null; - this.aoMapIntensity = 1.0; + // Virtual base class method to overwrite and implement in subclasses + // - t [0 .. 1] - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + getPoint: function ( /* t, optionalTarget */ ) { - this.bumpMap = null; - this.bumpScale = 1; + console.warn( 'THREE.Curve: .getPoint() not implemented.' ); + return null; - this.normalMap = null; - this.normalScale = new Vector2( 1, 1 ); + }, - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + // Get point at relative position in curve according to arc length + // - u [0 .. 1] - this.specularMap = null; + getPointAt: function ( u, optionalTarget ) { - this.alphaMap = null; + var t = this.getUtoTmapping( u ); + return this.getPoint( t, optionalTarget ); - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + }, - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + // Get sequence of points using getPoint( t ) - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + getPoints: function ( divisions ) { - this.setValues( parameters ); + if ( divisions === undefined ) divisions = 5; - } + var points = []; - MeshPhongMaterial.prototype = Object.create( Material.prototype ); - MeshPhongMaterial.prototype.constructor = MeshPhongMaterial; + for ( var d = 0; d <= divisions; d ++ ) { - MeshPhongMaterial.prototype.isMeshPhongMaterial = true; + points.push( this.getPoint( d / divisions ) ); - MeshPhongMaterial.prototype.copy = function ( source ) { + } - Material.prototype.copy.call( this, source ); + return points; - this.color.copy( source.color ); - this.specular.copy( source.specular ); - this.shininess = source.shininess; + }, - this.map = source.map; + // Get sequence of points using getPointAt( u ) - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + getSpacedPoints: function ( divisions ) { - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + if ( divisions === undefined ) divisions = 5; - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + var points = []; - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + for ( var d = 0; d <= divisions; d ++ ) { - this.normalMap = source.normalMap; - this.normalScale.copy( source.normalScale ); + points.push( this.getPointAt( d / divisions ) ); - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + } - this.specularMap = source.specularMap; + return points; - this.alphaMap = source.alphaMap; + }, - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + // Get total curve arc length - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + getLength: function () { - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + var lengths = this.getLengths(); + return lengths[ lengths.length - 1 ]; - return this; + }, - }; + // Get list of cumulative segment lengths - /** - * @author takahirox / http://github.com/takahirox - * - * parameters = { - * gradientMap: new THREE.Texture( ) - * } - */ + getLengths: function ( divisions ) { - function MeshToonMaterial( parameters ) { + if ( divisions === undefined ) divisions = this.arcLengthDivisions; - MeshPhongMaterial.call( this ); + if ( this.cacheArcLengths && + ( this.cacheArcLengths.length === divisions + 1 ) && + ! this.needsUpdate ) { - this.defines = { 'TOON': '' }; + return this.cacheArcLengths; - this.type = 'MeshToonMaterial'; + } - this.gradientMap = null; + this.needsUpdate = false; - this.setValues( parameters ); + var cache = []; + var current, last = this.getPoint( 0 ); + var p, sum = 0; - } + cache.push( 0 ); - MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype ); - MeshToonMaterial.prototype.constructor = MeshToonMaterial; + for ( p = 1; p <= divisions; p ++ ) { - MeshToonMaterial.prototype.isMeshToonMaterial = true; + current = this.getPoint( p / divisions ); + sum += current.distanceTo( last ); + cache.push( sum ); + last = current; - MeshToonMaterial.prototype.copy = function ( source ) { + } - MeshPhongMaterial.prototype.copy.call( this, source ); + this.cacheArcLengths = cache; - this.gradientMap = source.gradientMap; + return cache; // { sums: cache, sum: sum }; Sum is in the last element. - return this; + }, - }; + updateArcLengths: function () { - /** - * @author mrdoob / http://mrdoob.com/ - * @author WestLangley / http://github.com/WestLangley - * - * parameters = { - * opacity: , - * - * bumpMap: new THREE.Texture( ), - * bumpScale: , - * - * normalMap: new THREE.Texture( ), - * normalScale: , - * - * displacementMap: new THREE.Texture( ), - * displacementScale: , - * displacementBias: , - * - * wireframe: , - * wireframeLinewidth: - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + this.needsUpdate = true; + this.getLengths(); - function MeshNormalMaterial( parameters ) { + }, - Material.call( this ); + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant - this.type = 'MeshNormalMaterial'; + getUtoTmapping: function ( u, distance ) { - this.bumpMap = null; - this.bumpScale = 1; + var arcLengths = this.getLengths(); - this.normalMap = null; - this.normalScale = new Vector2( 1, 1 ); + var i = 0, il = arcLengths.length; - this.displacementMap = null; - this.displacementScale = 1; - this.displacementBias = 0; + var targetArcLength; // The targeted u distance value to get - this.wireframe = false; - this.wireframeLinewidth = 1; + if ( distance ) { - this.fog = false; - this.lights = false; + targetArcLength = distance; - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + } else { - this.setValues( parameters ); + targetArcLength = u * arcLengths[ il - 1 ]; - } + } - MeshNormalMaterial.prototype = Object.create( Material.prototype ); - MeshNormalMaterial.prototype.constructor = MeshNormalMaterial; + // binary search for the index with largest value smaller than target u distance - MeshNormalMaterial.prototype.isMeshNormalMaterial = true; + var low = 0, high = il - 1, comparison; - MeshNormalMaterial.prototype.copy = function ( source ) { + while ( low <= high ) { - Material.prototype.copy.call( this, source ); + i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats - this.bumpMap = source.bumpMap; - this.bumpScale = source.bumpScale; + comparison = arcLengths[ i ] - targetArcLength; - this.normalMap = source.normalMap; - this.normalScale.copy( source.normalScale ); + if ( comparison < 0 ) { - this.displacementMap = source.displacementMap; - this.displacementScale = source.displacementScale; - this.displacementBias = source.displacementBias; + low = i + 1; - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; + } else if ( comparison > 0 ) { - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + high = i - 1; - return this; + } else { - }; + high = i; + break; - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * map: new THREE.Texture( ), - * - * lightMap: new THREE.Texture( ), - * lightMapIntensity: - * - * aoMap: new THREE.Texture( ), - * aoMapIntensity: - * - * emissive: , - * emissiveIntensity: - * emissiveMap: new THREE.Texture( ), - * - * specularMap: new THREE.Texture( ), - * - * alphaMap: new THREE.Texture( ), - * - * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), - * combine: THREE.Multiply, - * reflectivity: , - * refractionRatio: , - * - * wireframe: , - * wireframeLinewidth: , - * - * skinning: , - * morphTargets: , - * morphNormals: - * } - */ + // DONE - function MeshLambertMaterial( parameters ) { + } - Material.call( this ); + } - this.type = 'MeshLambertMaterial'; + i = high; - this.color = new Color( 0xffffff ); // diffuse + if ( arcLengths[ i ] === targetArcLength ) { - this.map = null; + return i / ( il - 1 ); - this.lightMap = null; - this.lightMapIntensity = 1.0; + } - this.aoMap = null; - this.aoMapIntensity = 1.0; + // we could get finer grain at lengths, or use simple interpolation between two points - this.emissive = new Color( 0x000000 ); - this.emissiveIntensity = 1.0; - this.emissiveMap = null; + var lengthBefore = arcLengths[ i ]; + var lengthAfter = arcLengths[ i + 1 ]; - this.specularMap = null; + var segmentLength = lengthAfter - lengthBefore; - this.alphaMap = null; + // determine where we are between the 'before' and 'after' points - this.envMap = null; - this.combine = MultiplyOperation; - this.reflectivity = 1; - this.refractionRatio = 0.98; + var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; - this.wireframe = false; - this.wireframeLinewidth = 1; - this.wireframeLinecap = 'round'; - this.wireframeLinejoin = 'round'; + // add that fractional amount to t - this.skinning = false; - this.morphTargets = false; - this.morphNormals = false; + var t = ( i + segmentFraction ) / ( il - 1 ); - this.setValues( parameters ); + return t; - } + }, - MeshLambertMaterial.prototype = Object.create( Material.prototype ); - MeshLambertMaterial.prototype.constructor = MeshLambertMaterial; + // Returns a unit vector tangent at t + // In case any sub curve does not implement its tangent derivation, + // 2 points a small delta apart will be used to find its gradient + // which seems to give a reasonable approximation - MeshLambertMaterial.prototype.isMeshLambertMaterial = true; + getTangent: function ( t ) { - MeshLambertMaterial.prototype.copy = function ( source ) { + var delta = 0.0001; + var t1 = t - delta; + var t2 = t + delta; - Material.prototype.copy.call( this, source ); + // Capping in case of danger - this.color.copy( source.color ); + if ( t1 < 0 ) t1 = 0; + if ( t2 > 1 ) t2 = 1; - this.map = source.map; + var pt1 = this.getPoint( t1 ); + var pt2 = this.getPoint( t2 ); - this.lightMap = source.lightMap; - this.lightMapIntensity = source.lightMapIntensity; + var vec = pt2.clone().sub( pt1 ); + return vec.normalize(); - this.aoMap = source.aoMap; - this.aoMapIntensity = source.aoMapIntensity; + }, - this.emissive.copy( source.emissive ); - this.emissiveMap = source.emissiveMap; - this.emissiveIntensity = source.emissiveIntensity; + getTangentAt: function ( u ) { - this.specularMap = source.specularMap; + var t = this.getUtoTmapping( u ); + return this.getTangent( t ); - this.alphaMap = source.alphaMap; + }, - this.envMap = source.envMap; - this.combine = source.combine; - this.reflectivity = source.reflectivity; - this.refractionRatio = source.refractionRatio; + computeFrenetFrames: function ( segments, closed ) { - this.wireframe = source.wireframe; - this.wireframeLinewidth = source.wireframeLinewidth; - this.wireframeLinecap = source.wireframeLinecap; - this.wireframeLinejoin = source.wireframeLinejoin; + // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf - this.skinning = source.skinning; - this.morphTargets = source.morphTargets; - this.morphNormals = source.morphNormals; + var normal = new Vector3(); - return this; + var tangents = []; + var normals = []; + var binormals = []; - }; + var vec = new Vector3(); + var mat = new Matrix4(); - /** - * @author alteredq / http://alteredqualia.com/ - * - * parameters = { - * color: , - * opacity: , - * - * linewidth: , - * - * scale: , - * dashSize: , - * gapSize: - * } - */ + var i, u, theta; - function LineDashedMaterial( parameters ) { + // compute the tangent vectors for each segment on the curve - Material.call( this ); + for ( i = 0; i <= segments; i ++ ) { - this.type = 'LineDashedMaterial'; + u = i / segments; - this.color = new Color( 0xffffff ); + tangents[ i ] = this.getTangentAt( u ); + tangents[ i ].normalize(); - this.linewidth = 1; + } - this.scale = 1; - this.dashSize = 3; - this.gapSize = 1; + // select an initial normal vector perpendicular to the first tangent vector, + // and in the direction of the minimum tangent xyz component - this.lights = false; + normals[ 0 ] = new Vector3(); + binormals[ 0 ] = new Vector3(); + var min = Number.MAX_VALUE; + var tx = Math.abs( tangents[ 0 ].x ); + var ty = Math.abs( tangents[ 0 ].y ); + var tz = Math.abs( tangents[ 0 ].z ); - this.setValues( parameters ); + if ( tx <= min ) { - } + min = tx; + normal.set( 1, 0, 0 ); - LineDashedMaterial.prototype = Object.create( Material.prototype ); - LineDashedMaterial.prototype.constructor = LineDashedMaterial; + } - LineDashedMaterial.prototype.isLineDashedMaterial = true; + if ( ty <= min ) { - LineDashedMaterial.prototype.copy = function ( source ) { + min = ty; + normal.set( 0, 1, 0 ); - Material.prototype.copy.call( this, source ); + } - this.color.copy( source.color ); + if ( tz <= min ) { - this.linewidth = source.linewidth; + normal.set( 0, 0, 1 ); - this.scale = source.scale; - this.dashSize = source.dashSize; - this.gapSize = source.gapSize; + } - return this; + vec.crossVectors( tangents[ 0 ], normal ).normalize(); - }; + normals[ 0 ].crossVectors( tangents[ 0 ], vec ); + binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); + // compute the slowly-varying normal and binormal vectors for each segment on the curve - var Materials = Object.freeze({ - ShadowMaterial: ShadowMaterial, - SpriteMaterial: SpriteMaterial, - RawShaderMaterial: RawShaderMaterial, - ShaderMaterial: ShaderMaterial, - PointsMaterial: PointsMaterial, - MeshPhysicalMaterial: MeshPhysicalMaterial, - MeshStandardMaterial: MeshStandardMaterial, - MeshPhongMaterial: MeshPhongMaterial, - MeshToonMaterial: MeshToonMaterial, - MeshNormalMaterial: MeshNormalMaterial, - MeshLambertMaterial: MeshLambertMaterial, - MeshDepthMaterial: MeshDepthMaterial, - MeshBasicMaterial: MeshBasicMaterial, - LineDashedMaterial: LineDashedMaterial, - LineBasicMaterial: LineBasicMaterial, - Material: Material - }); + for ( i = 1; i <= segments; i ++ ) { + + normals[ i ] = normals[ i - 1 ].clone(); + + binormals[ i ] = binormals[ i - 1 ].clone(); + + vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + + if ( vec.length() > Number.EPSILON ) { + + vec.normalize(); + + theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + + normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + + } + + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + + } + + // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + + if ( closed === true ) { + + theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) ); + theta /= segments; + + if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) { + + theta = - theta; + + } + + for ( i = 1; i <= segments; i ++ ) { + + // twist a little... + normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); + binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + } - var Cache = { + return { + tangents: tangents, + normals: normals, + binormals: binormals + }; - enabled: false, + }, - files: {}, + clone: function () { - add: function ( key, file ) { + return new this.constructor().copy( this ); - if ( this.enabled === false ) return; + }, - // console.log( 'THREE.Cache', 'Adding key:', key ); + copy: function ( source ) { - this.files[ key ] = file; + this.arcLengthDivisions = source.arcLengthDivisions; + + return this; }, - get: function ( key ) { + toJSON: function () { - if ( this.enabled === false ) return; + var data = { + metadata: { + version: 4.5, + type: 'Curve', + generator: 'Curve.toJSON' + } + }; - // console.log( 'THREE.Cache', 'Checking key:', key ); + data.arcLengthDivisions = this.arcLengthDivisions; + data.type = this.type; - return this.files[ key ]; + return data; }, - remove: function ( key ) { + fromJSON: function ( json ) { - delete this.files[ key ]; + this.arcLengthDivisions = json.arcLengthDivisions; - }, + return this; - clear: function () { + } - this.files = {}; + } ); - } + function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - }; + Curve.call( this ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + this.type = 'EllipseCurve'; - function LoadingManager( onLoad, onProgress, onError ) { + this.aX = aX || 0; + this.aY = aY || 0; - var scope = this; + this.xRadius = xRadius || 1; + this.yRadius = yRadius || 1; - var isLoading = false, itemsLoaded = 0, itemsTotal = 0; + this.aStartAngle = aStartAngle || 0; + this.aEndAngle = aEndAngle || 2 * Math.PI; - this.onStart = undefined; - this.onLoad = onLoad; - this.onProgress = onProgress; - this.onError = onError; + this.aClockwise = aClockwise || false; - this.itemStart = function ( url ) { + this.aRotation = aRotation || 0; - itemsTotal ++; + } - if ( isLoading === false ) { + EllipseCurve.prototype = Object.create( Curve.prototype ); + EllipseCurve.prototype.constructor = EllipseCurve; - if ( scope.onStart !== undefined ) { + EllipseCurve.prototype.isEllipseCurve = true; - scope.onStart( url, itemsLoaded, itemsTotal ); + EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) { - } + var point = optionalTarget || new Vector2(); - } + var twoPi = Math.PI * 2; + var deltaAngle = this.aEndAngle - this.aStartAngle; + var samePoints = Math.abs( deltaAngle ) < Number.EPSILON; - isLoading = true; + // ensures that deltaAngle is 0 .. 2 PI + while ( deltaAngle < 0 ) deltaAngle += twoPi; + while ( deltaAngle > twoPi ) deltaAngle -= twoPi; - }; + if ( deltaAngle < Number.EPSILON ) { - this.itemEnd = function ( url ) { + if ( samePoints ) { - itemsLoaded ++; + deltaAngle = 0; - if ( scope.onProgress !== undefined ) { + } else { - scope.onProgress( url, itemsLoaded, itemsTotal ); + deltaAngle = twoPi; } - if ( itemsLoaded === itemsTotal ) { + } - isLoading = false; + if ( this.aClockwise === true && ! samePoints ) { - if ( scope.onLoad !== undefined ) { + if ( deltaAngle === twoPi ) { - scope.onLoad(); + deltaAngle = - twoPi; - } + } else { + + deltaAngle = deltaAngle - twoPi; } - }; + } - this.itemError = function ( url ) { + var angle = this.aStartAngle + t * deltaAngle; + var x = this.aX + this.xRadius * Math.cos( angle ); + var y = this.aY + this.yRadius * Math.sin( angle ); - if ( scope.onError !== undefined ) { + if ( this.aRotation !== 0 ) { - scope.onError( url ); + var cos = Math.cos( this.aRotation ); + var sin = Math.sin( this.aRotation ); - } + var tx = x - this.aX; + var ty = y - this.aY; - }; + // Rotate the point about the center of the ellipse. + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; - } + } - var DefaultLoadingManager = new LoadingManager(); + return point.set( x, y ); - /** - * @author mrdoob / http://mrdoob.com/ - */ + }; - function FileLoader( manager ) { + EllipseCurve.prototype.copy = function ( source ) { - this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + Curve.prototype.copy.call( this, source ); - } + this.aX = source.aX; + this.aY = source.aY; - Object.assign( FileLoader.prototype, { + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; - load: function ( url, onLoad, onProgress, onError ) { + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; - if ( url === undefined ) url = ''; + this.aClockwise = source.aClockwise; - if ( this.path !== undefined ) url = this.path + url; + this.aRotation = source.aRotation; - var scope = this; + return this; - var cached = Cache.get( url ); + }; - if ( cached !== undefined ) { - scope.manager.itemStart( url ); + EllipseCurve.prototype.toJSON = function () { - setTimeout( function () { + var data = Curve.prototype.toJSON.call( this ); - if ( onLoad ) onLoad( cached ); + data.aX = this.aX; + data.aY = this.aY; - scope.manager.itemEnd( url ); + data.xRadius = this.xRadius; + data.yRadius = this.yRadius; - }, 0 ); + data.aStartAngle = this.aStartAngle; + data.aEndAngle = this.aEndAngle; - return cached; + data.aClockwise = this.aClockwise; - } + data.aRotation = this.aRotation; - // Check for data: URI - var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/; - var dataUriRegexResult = url.match( dataUriRegex ); + return data; - // Safari can not handle Data URIs through XMLHttpRequest so process manually - if ( dataUriRegexResult ) { + }; - var mimeType = dataUriRegexResult[ 1 ]; - var isBase64 = !! dataUriRegexResult[ 2 ]; - var data = dataUriRegexResult[ 3 ]; + EllipseCurve.prototype.fromJSON = function ( json ) { - data = window.decodeURIComponent( data ); + Curve.prototype.fromJSON.call( this, json ); - if ( isBase64 ) data = window.atob( data ); + this.aX = json.aX; + this.aY = json.aY; - try { + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; - var response; - var responseType = ( this.responseType || '' ).toLowerCase(); + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; - switch ( responseType ) { + this.aClockwise = json.aClockwise; - case 'arraybuffer': - case 'blob': + this.aRotation = json.aRotation; - response = new ArrayBuffer( data.length ); + return this; - var view = new Uint8Array( response ); + }; - for ( var i = 0; i < data.length; i ++ ) { + function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - view[ i ] = data.charCodeAt( i ); + EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - } + this.type = 'ArcCurve'; - if ( responseType === 'blob' ) { + } - response = new Blob( [ response ], { type: mimeType } ); + ArcCurve.prototype = Object.create( EllipseCurve.prototype ); + ArcCurve.prototype.constructor = ArcCurve; - } + ArcCurve.prototype.isArcCurve = true; - break; + /** + * @author zz85 https://github.com/zz85 + * + * Centripetal CatmullRom Curve - which is useful for avoiding + * cusps and self-intersections in non-uniform catmull rom curves. + * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf + * + * curve.type accepts centripetal(default), chordal and catmullrom + * curve.tension is used for catmullrom which defaults to 0.5 + */ - case 'document': - var parser = new DOMParser(); - response = parser.parseFromString( data, mimeType ); + /* + Based on an optimized c++ solution in + - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/ + - http://ideone.com/NoEbVM - break; + This CubicPoly class could be used for reusing some variables and calculations, + but for three.js curve use, it could be possible inlined and flatten into a single function call + which can be placed in CurveUtils. + */ - case 'json': + function CubicPoly() { - response = JSON.parse( data ); + var c0 = 0, c1 = 0, c2 = 0, c3 = 0; - break; + /* + * Compute coefficients for a cubic polynomial + * p(s) = c0 + c1*s + c2*s^2 + c3*s^3 + * such that + * p(0) = x0, p(1) = x1 + * and + * p'(0) = t0, p'(1) = t1. + */ + function init( x0, x1, t0, t1 ) { - default: // 'text' or other + c0 = x0; + c1 = t0; + c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; - response = data; + } - break; + return { - } + initCatmullRom: function ( x0, x1, x2, x3, tension ) { - // Wait for next browser tick - window.setTimeout( function () { + init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); - if ( onLoad ) onLoad( response ); + }, - scope.manager.itemEnd( url ); + initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) { - }, 0 ); + // compute tangents when parameterized in [t1,t2] + var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; + var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; - } catch ( error ) { + // rescale tangents for parametrization in [0,1] + t1 *= dt1; + t2 *= dt1; - // Wait for next browser tick - window.setTimeout( function () { + init( x1, x2, t1, t2 ); - if ( onError ) onError( error ); + }, - scope.manager.itemEnd( url ); - scope.manager.itemError( url ); + calc: function ( t ) { - }, 0 ); + var t2 = t * t; + var t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; - } + } - } else { + }; - var request = new XMLHttpRequest(); - request.open( 'GET', url, true ); + } - request.addEventListener( 'load', function ( event ) { + // + + var tmp = new Vector3(); + var px = new CubicPoly(); + var py = new CubicPoly(); + var pz = new CubicPoly(); - var response = event.target.response; + function CatmullRomCurve3( points, closed, curveType, tension ) { - Cache.add( url, response ); + Curve.call( this ); - if ( this.status === 200 ) { + this.type = 'CatmullRomCurve3'; - if ( onLoad ) onLoad( response ); + this.points = points || []; + this.closed = closed || false; + this.curveType = curveType || 'centripetal'; + this.tension = tension || 0.5; - scope.manager.itemEnd( url ); + } - } else if ( this.status === 0 ) { + CatmullRomCurve3.prototype = Object.create( Curve.prototype ); + CatmullRomCurve3.prototype.constructor = CatmullRomCurve3; - // Some browsers return HTTP Status 0 when using non-http protocol - // e.g. 'file://' or 'data://'. Handle as success. + CatmullRomCurve3.prototype.isCatmullRomCurve3 = true; - console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); + CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) { - if ( onLoad ) onLoad( response ); + var point = optionalTarget || new Vector3(); - scope.manager.itemEnd( url ); + var points = this.points; + var l = points.length; - } else { + var p = ( l - ( this.closed ? 0 : 1 ) ) * t; + var intPoint = Math.floor( p ); + var weight = p - intPoint; - if ( onError ) onError( event ); + if ( this.closed ) { - scope.manager.itemEnd( url ); - scope.manager.itemError( url ); + intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length; - } + } else if ( weight === 0 && intPoint === l - 1 ) { - }, false ); + intPoint = l - 2; + weight = 1; - if ( onProgress !== undefined ) { + } - request.addEventListener( 'progress', function ( event ) { + var p0, p1, p2, p3; // 4 points - onProgress( event ); + if ( this.closed || intPoint > 0 ) { - }, false ); + p0 = points[ ( intPoint - 1 ) % l ]; - } + } else { - request.addEventListener( 'error', function ( event ) { + // extrapolate first point + tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); + p0 = tmp; - if ( onError ) onError( event ); + } - scope.manager.itemEnd( url ); - scope.manager.itemError( url ); + p1 = points[ intPoint % l ]; + p2 = points[ ( intPoint + 1 ) % l ]; - }, false ); + if ( this.closed || intPoint + 2 < l ) { - if ( this.responseType !== undefined ) request.responseType = this.responseType; - if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials; + p3 = points[ ( intPoint + 2 ) % l ]; - if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' ); + } else { - for ( var header in this.requestHeader ) { + // extrapolate last point + tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); + p3 = tmp; - request.setRequestHeader( header, this.requestHeader[ header ] ); + } - } + if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) { - request.send( null ); + // init Centripetal / Chordal Catmull-Rom + var pow = this.curveType === 'chordal' ? 0.5 : 0.25; + var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); + var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); + var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); - } + // safety check for repeated points + if ( dt1 < 1e-4 ) dt1 = 1.0; + if ( dt0 < 1e-4 ) dt0 = dt1; + if ( dt2 < 1e-4 ) dt2 = dt1; - scope.manager.itemStart( url ); + px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 ); + py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 ); + pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 ); - return request; + } else if ( this.curveType === 'catmullrom' ) { - }, + px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension ); + py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension ); + pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension ); - setPath: function ( value ) { + } - this.path = value; - return this; + point.set( + px.calc( weight ), + py.calc( weight ), + pz.calc( weight ) + ); - }, + return point; - setResponseType: function ( value ) { + }; - this.responseType = value; - return this; + CatmullRomCurve3.prototype.copy = function ( source ) { - }, + Curve.prototype.copy.call( this, source ); - setWithCredentials: function ( value ) { + this.points = []; - this.withCredentials = value; - return this; + for ( var i = 0, l = source.points.length; i < l; i ++ ) { - }, + var point = source.points[ i ]; - setMimeType: function ( value ) { + this.points.push( point.clone() ); - this.mimeType = value; - return this; + } - }, + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; - setRequestHeader: function ( value ) { + return this; - this.requestHeader = value; - return this; + }; + + CatmullRomCurve3.prototype.toJSON = function () { + + var data = Curve.prototype.toJSON.call( this ); + + data.points = []; + + for ( var i = 0, l = this.points.length; i < l; i ++ ) { + + var point = this.points[ i ]; + data.points.push( point.toArray() ); } - } ); + data.closed = this.closed; + data.curveType = this.curveType; + data.tension = this.tension; - /** - * @author mrdoob / http://mrdoob.com/ - * - * Abstract Base class to block based textures loader (dds, pvr, ...) - */ + return data; - function CompressedTextureLoader( manager ) { + }; - this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + CatmullRomCurve3.prototype.fromJSON = function ( json ) { - // override in sub classes - this._parser = null; + Curve.prototype.fromJSON.call( this, json ); - } + this.points = []; - Object.assign( CompressedTextureLoader.prototype, { + for ( var i = 0, l = json.points.length; i < l; i ++ ) { - load: function ( url, onLoad, onProgress, onError ) { + var point = json.points[ i ]; + this.points.push( new Vector3().fromArray( point ) ); - var scope = this; + } - var images = []; + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; - var texture = new CompressedTexture(); - texture.image = images; + return this; - var loader = new FileLoader( this.manager ); - loader.setPath( this.path ); - loader.setResponseType( 'arraybuffer' ); + }; - function loadTexture( i ) { + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + * Bezier Curves formulas obtained from + * http://en.wikipedia.org/wiki/Bézier_curve + */ - loader.load( url[ i ], function ( buffer ) { + function CatmullRom( t, p0, p1, p2, p3 ) { - var texDatas = scope._parser( buffer, true ); + var v0 = ( p2 - p0 ) * 0.5; + var v1 = ( p3 - p1 ) * 0.5; + var t2 = t * t; + var t3 = t * t2; + return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; - images[ i ] = { - width: texDatas.width, - height: texDatas.height, - format: texDatas.format, - mipmaps: texDatas.mipmaps - }; + } - loaded += 1; + // - if ( loaded === 6 ) { + function QuadraticBezierP0( t, p ) { - if ( texDatas.mipmapCount === 1 ) - texture.minFilter = LinearFilter; + var k = 1 - t; + return k * k * p; - texture.format = texDatas.format; - texture.needsUpdate = true; + } - if ( onLoad ) onLoad( texture ); + function QuadraticBezierP1( t, p ) { - } + return 2 * ( 1 - t ) * t * p; - }, onProgress, onError ); + } - } + function QuadraticBezierP2( t, p ) { - if ( Array.isArray( url ) ) { + return t * t * p; - var loaded = 0; + } - for ( var i = 0, il = url.length; i < il; ++ i ) { + function QuadraticBezier( t, p0, p1, p2 ) { - loadTexture( i ); + return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) + + QuadraticBezierP2( t, p2 ); - } + } - } else { + // - // compressed cubemap texture stored in a single DDS file + function CubicBezierP0( t, p ) { - loader.load( url, function ( buffer ) { + var k = 1 - t; + return k * k * k * p; - var texDatas = scope._parser( buffer, true ); + } - if ( texDatas.isCubemap ) { + function CubicBezierP1( t, p ) { - var faces = texDatas.mipmaps.length / texDatas.mipmapCount; + var k = 1 - t; + return 3 * k * k * t * p; - for ( var f = 0; f < faces; f ++ ) { + } - images[ f ] = { mipmaps : [] }; + function CubicBezierP2( t, p ) { - for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { + return 3 * ( 1 - t ) * t * t * p; - images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] ); - images[ f ].format = texDatas.format; - images[ f ].width = texDatas.width; - images[ f ].height = texDatas.height; + } - } + function CubicBezierP3( t, p ) { - } + return t * t * t * p; - } else { + } - texture.image.width = texDatas.width; - texture.image.height = texDatas.height; - texture.mipmaps = texDatas.mipmaps; + function CubicBezier( t, p0, p1, p2, p3 ) { - } + return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) + + CubicBezierP3( t, p3 ); - if ( texDatas.mipmapCount === 1 ) { + } - texture.minFilter = LinearFilter; + function CubicBezierCurve( v0, v1, v2, v3 ) { - } + Curve.call( this ); - texture.format = texDatas.format; - texture.needsUpdate = true; + this.type = 'CubicBezierCurve'; - if ( onLoad ) onLoad( texture ); + this.v0 = v0 || new Vector2(); + this.v1 = v1 || new Vector2(); + this.v2 = v2 || new Vector2(); + this.v3 = v3 || new Vector2(); - }, onProgress, onError ); + } - } + CubicBezierCurve.prototype = Object.create( Curve.prototype ); + CubicBezierCurve.prototype.constructor = CubicBezierCurve; - return texture; + CubicBezierCurve.prototype.isCubicBezierCurve = true; - }, + CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) { - setPath: function ( value ) { + var point = optionalTarget || new Vector2(); - this.path = value; - return this; + var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; - } + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ) + ); - } ); + return point; - /** - * @author Nikos M. / https://github.com/foo123/ - * - * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) - */ + }; + + CubicBezierCurve.prototype.copy = function ( source ) { + + Curve.prototype.copy.call( this, source ); + + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); + + return this; - function DataTextureLoader( manager ) { + }; - this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + CubicBezierCurve.prototype.toJSON = function () { - // override in sub classes - this._parser = null; + var data = Curve.prototype.toJSON.call( this ); - } + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); - Object.assign( DataTextureLoader.prototype, { + return data; - load: function ( url, onLoad, onProgress, onError ) { + }; - var scope = this; + CubicBezierCurve.prototype.fromJSON = function ( json ) { - var texture = new DataTexture(); + Curve.prototype.fromJSON.call( this, json ); - var loader = new FileLoader( this.manager ); - loader.setResponseType( 'arraybuffer' ); + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); - loader.load( url, function ( buffer ) { + return this; - var texData = scope._parser( buffer ); + }; - if ( ! texData ) return; + function CubicBezierCurve3( v0, v1, v2, v3 ) { - if ( undefined !== texData.image ) { + Curve.call( this ); - texture.image = texData.image; + this.type = 'CubicBezierCurve3'; - } else if ( undefined !== texData.data ) { + this.v0 = v0 || new Vector3(); + this.v1 = v1 || new Vector3(); + this.v2 = v2 || new Vector3(); + this.v3 = v3 || new Vector3(); - texture.image.width = texData.width; - texture.image.height = texData.height; - texture.image.data = texData.data; + } - } + CubicBezierCurve3.prototype = Object.create( Curve.prototype ); + CubicBezierCurve3.prototype.constructor = CubicBezierCurve3; - texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping; - texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping; + CubicBezierCurve3.prototype.isCubicBezierCurve3 = true; - texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter; - texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter; + CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) { - texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1; + var point = optionalTarget || new Vector3(); - if ( undefined !== texData.format ) { + var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; - texture.format = texData.format; + point.set( + CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), + CubicBezier( t, v0.y, v1.y, v2.y, v3.y ), + CubicBezier( t, v0.z, v1.z, v2.z, v3.z ) + ); - } - if ( undefined !== texData.type ) { + return point; - texture.type = texData.type; + }; - } + CubicBezierCurve3.prototype.copy = function ( source ) { - if ( undefined !== texData.mipmaps ) { + Curve.prototype.copy.call( this, source ); - texture.mipmaps = texData.mipmaps; + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); + this.v3.copy( source.v3 ); - } + return this; - if ( 1 === texData.mipmapCount ) { + }; - texture.minFilter = LinearFilter; + CubicBezierCurve3.prototype.toJSON = function () { - } + var data = Curve.prototype.toJSON.call( this ); - texture.needsUpdate = true; + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); - if ( onLoad ) onLoad( texture, texData ); + return data; - }, onProgress, onError ); + }; + CubicBezierCurve3.prototype.fromJSON = function ( json ) { - return texture; + Curve.prototype.fromJSON.call( this, json ); - } + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); + this.v3.fromArray( json.v3 ); - } ); + return this; - /** - * @author mrdoob / http://mrdoob.com/ - */ + }; - function ImageLoader( manager ) { + function LineCurve( v1, v2 ) { - this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + Curve.call( this ); - } + this.type = 'LineCurve'; - Object.assign( ImageLoader.prototype, { + this.v1 = v1 || new Vector2(); + this.v2 = v2 || new Vector2(); - load: function ( url, onLoad, onProgress, onError ) { + } - if ( url === undefined ) url = ''; + LineCurve.prototype = Object.create( Curve.prototype ); + LineCurve.prototype.constructor = LineCurve; - if ( this.path !== undefined ) url = this.path + url; + LineCurve.prototype.isLineCurve = true; - var scope = this; + LineCurve.prototype.getPoint = function ( t, optionalTarget ) { - var cached = Cache.get( url ); + var point = optionalTarget || new Vector2(); - if ( cached !== undefined ) { + if ( t === 1 ) { - scope.manager.itemStart( url ); + point.copy( this.v2 ); - setTimeout( function () { + } else { - if ( onLoad ) onLoad( cached ); + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); - scope.manager.itemEnd( url ); + } - }, 0 ); + return point; - return cached; + }; - } + // Line curve is linear, so we can overwrite default getPointAt - var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); + LineCurve.prototype.getPointAt = function ( u, optionalTarget ) { - image.addEventListener( 'load', function () { + return this.getPoint( u, optionalTarget ); - Cache.add( url, this ); + }; - if ( onLoad ) onLoad( this ); + LineCurve.prototype.getTangent = function ( /* t */ ) { - scope.manager.itemEnd( url ); + var tangent = this.v2.clone().sub( this.v1 ); - }, false ); + return tangent.normalize(); - /* - image.addEventListener( 'progress', function ( event ) { + }; - if ( onProgress ) onProgress( event ); + LineCurve.prototype.copy = function ( source ) { - }, false ); - */ + Curve.prototype.copy.call( this, source ); - image.addEventListener( 'error', function ( event ) { + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); - if ( onError ) onError( event ); + return this; - scope.manager.itemEnd( url ); - scope.manager.itemError( url ); + }; - }, false ); + LineCurve.prototype.toJSON = function () { - if ( url.substr( 0, 5 ) !== 'data:' ) { + var data = Curve.prototype.toJSON.call( this ); - if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin; + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); - } + return data; - scope.manager.itemStart( url ); + }; - image.src = url; + LineCurve.prototype.fromJSON = function ( json ) { - return image; + Curve.prototype.fromJSON.call( this, json ); - }, + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); - setCrossOrigin: function ( value ) { + return this; - this.crossOrigin = value; - return this; + }; - }, + function LineCurve3( v1, v2 ) { - setPath: function ( value ) { + Curve.call( this ); - this.path = value; - return this; + this.type = 'LineCurve3'; - } + this.v1 = v1 || new Vector3(); + this.v2 = v2 || new Vector3(); - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + LineCurve3.prototype = Object.create( Curve.prototype ); + LineCurve3.prototype.constructor = LineCurve3; - function CubeTextureLoader( manager ) { + LineCurve3.prototype.isLineCurve3 = true; - this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + LineCurve3.prototype.getPoint = function ( t, optionalTarget ) { - } + var point = optionalTarget || new Vector3(); - Object.assign( CubeTextureLoader.prototype, { + if ( t === 1 ) { - load: function ( urls, onLoad, onProgress, onError ) { + point.copy( this.v2 ); - var texture = new CubeTexture(); + } else { - var loader = new ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setPath( this.path ); + point.copy( this.v2 ).sub( this.v1 ); + point.multiplyScalar( t ).add( this.v1 ); - var loaded = 0; + } - function loadTexture( i ) { + return point; - loader.load( urls[ i ], function ( image ) { + }; - texture.images[ i ] = image; + // Line curve is linear, so we can overwrite default getPointAt - loaded ++; + LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) { - if ( loaded === 6 ) { + return this.getPoint( u, optionalTarget ); - texture.needsUpdate = true; + }; - if ( onLoad ) onLoad( texture ); + LineCurve3.prototype.copy = function ( source ) { - } + Curve.prototype.copy.call( this, source ); - }, undefined, onError ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); - } + return this; - for ( var i = 0; i < urls.length; ++ i ) { + }; - loadTexture( i ); + LineCurve3.prototype.toJSON = function () { - } + var data = Curve.prototype.toJSON.call( this ); - return texture; + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); - }, + return data; - setCrossOrigin: function ( value ) { + }; - this.crossOrigin = value; - return this; + LineCurve3.prototype.fromJSON = function ( json ) { - }, + Curve.prototype.fromJSON.call( this, json ); - setPath: function ( value ) { + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); - this.path = value; - return this; + return this; - } + }; - } ); + function QuadraticBezierCurve( v0, v1, v2 ) { - /** - * @author mrdoob / http://mrdoob.com/ - */ + Curve.call( this ); - function TextureLoader( manager ) { + this.type = 'QuadraticBezierCurve'; - this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + this.v0 = v0 || new Vector2(); + this.v1 = v1 || new Vector2(); + this.v2 = v2 || new Vector2(); } - Object.assign( TextureLoader.prototype, { + QuadraticBezierCurve.prototype = Object.create( Curve.prototype ); + QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve; - load: function ( url, onLoad, onProgress, onError ) { + QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true; - var loader = new ImageLoader( this.manager ); - loader.setCrossOrigin( this.crossOrigin ); - loader.setPath( this.path ); + QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) { - var texture = new Texture(); - texture.image = loader.load( url, function () { + var point = optionalTarget || new Vector2(); - // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. - var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; + var v0 = this.v0, v1 = this.v1, v2 = this.v2; - texture.format = isJPEG ? RGBFormat : RGBAFormat; - texture.needsUpdate = true; + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ) + ); - if ( onLoad !== undefined ) { + return point; - onLoad( texture ); + }; - } + QuadraticBezierCurve.prototype.copy = function ( source ) { - }, onProgress, onError ); + Curve.prototype.copy.call( this, source ); - return texture; + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); - }, + return this; - setCrossOrigin: function ( value ) { + }; - this.crossOrigin = value; - return this; + QuadraticBezierCurve.prototype.toJSON = function () { - }, + var data = Curve.prototype.toJSON.call( this ); - setPath: function ( value ) { + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); - this.path = value; - return this; + return data; - } + }; - } ); + QuadraticBezierCurve.prototype.fromJSON = function ( json ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + Curve.prototype.fromJSON.call( this, json ); - function Light( color, intensity ) { + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); - Object3D.call( this ); + return this; - this.type = 'Light'; + }; - this.color = new Color( color ); - this.intensity = intensity !== undefined ? intensity : 1; + function QuadraticBezierCurve3( v0, v1, v2 ) { - this.receiveShadow = undefined; + Curve.call( this ); + + this.type = 'QuadraticBezierCurve3'; + + this.v0 = v0 || new Vector3(); + this.v1 = v1 || new Vector3(); + this.v2 = v2 || new Vector3(); } - Light.prototype = Object.assign( Object.create( Object3D.prototype ), { + QuadraticBezierCurve3.prototype = Object.create( Curve.prototype ); + QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3; - constructor: Light, + QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true; - isLight: true, + QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) { - copy: function ( source ) { + var point = optionalTarget || new Vector3(); - Object3D.prototype.copy.call( this, source ); + var v0 = this.v0, v1 = this.v1, v2 = this.v2; - this.color.copy( source.color ); - this.intensity = source.intensity; + point.set( + QuadraticBezier( t, v0.x, v1.x, v2.x ), + QuadraticBezier( t, v0.y, v1.y, v2.y ), + QuadraticBezier( t, v0.z, v1.z, v2.z ) + ); - return this; + return point; - }, + }; - toJSON: function ( meta ) { + QuadraticBezierCurve3.prototype.copy = function ( source ) { - var data = Object3D.prototype.toJSON.call( this, meta ); + Curve.prototype.copy.call( this, source ); - data.object.color = this.color.getHex(); - data.object.intensity = this.intensity; + this.v0.copy( source.v0 ); + this.v1.copy( source.v1 ); + this.v2.copy( source.v2 ); - if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); + return this; - if ( this.distance !== undefined ) data.object.distance = this.distance; - if ( this.angle !== undefined ) data.object.angle = this.angle; - if ( this.decay !== undefined ) data.object.decay = this.decay; - if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra; + }; - if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON(); + QuadraticBezierCurve3.prototype.toJSON = function () { - return data; + var data = Curve.prototype.toJSON.call( this ); - } + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); - } ); + return data; - /** - * @author alteredq / http://alteredqualia.com/ - */ + }; - function HemisphereLight( skyColor, groundColor, intensity ) { + QuadraticBezierCurve3.prototype.fromJSON = function ( json ) { - Light.call( this, skyColor, intensity ); + Curve.prototype.fromJSON.call( this, json ); - this.type = 'HemisphereLight'; + this.v0.fromArray( json.v0 ); + this.v1.fromArray( json.v1 ); + this.v2.fromArray( json.v2 ); - this.castShadow = undefined; + return this; - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + }; - this.groundColor = new Color( groundColor ); + function SplineCurve( points /* array of Vector2 */ ) { + + Curve.call( this ); + + this.type = 'SplineCurve'; + + this.points = points || []; } - HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), { + SplineCurve.prototype = Object.create( Curve.prototype ); + SplineCurve.prototype.constructor = SplineCurve; - constructor: HemisphereLight, + SplineCurve.prototype.isSplineCurve = true; - isHemisphereLight: true, + SplineCurve.prototype.getPoint = function ( t, optionalTarget ) { - copy: function ( source ) { + var point = optionalTarget || new Vector2(); - Light.prototype.copy.call( this, source ); + var points = this.points; + var p = ( points.length - 1 ) * t; - this.groundColor.copy( source.groundColor ); + var intPoint = Math.floor( p ); + var weight = p - intPoint; - return this; + var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; + var p1 = points[ intPoint ]; + var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; + var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; - } + point.set( + CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ), + CatmullRom( weight, p0.y, p1.y, p2.y, p3.y ) + ); - } ); + return point; - /** - * @author mrdoob / http://mrdoob.com/ - */ + }; - function LightShadow( camera ) { + SplineCurve.prototype.copy = function ( source ) { - this.camera = camera; + Curve.prototype.copy.call( this, source ); - this.bias = 0; - this.radius = 1; + this.points = []; - this.mapSize = new Vector2( 512, 512 ); + for ( var i = 0, l = source.points.length; i < l; i ++ ) { - this.map = null; - this.matrix = new Matrix4(); + var point = source.points[ i ]; - } + this.points.push( point.clone() ); - Object.assign( LightShadow.prototype, { + } - copy: function ( source ) { + return this; - this.camera = source.camera.clone(); + }; - this.bias = source.bias; - this.radius = source.radius; + SplineCurve.prototype.toJSON = function () { - this.mapSize.copy( source.mapSize ); + var data = Curve.prototype.toJSON.call( this ); - return this; + data.points = []; - }, + for ( var i = 0, l = this.points.length; i < l; i ++ ) { - clone: function () { + var point = this.points[ i ]; + data.points.push( point.toArray() ); - return new this.constructor().copy( this ); + } - }, + return data; - toJSON: function () { + }; - var object = {}; + SplineCurve.prototype.fromJSON = function ( json ) { - if ( this.bias !== 0 ) object.bias = this.bias; - if ( this.radius !== 1 ) object.radius = this.radius; - if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray(); + Curve.prototype.fromJSON.call( this, json ); - object.camera = this.camera.toJSON( false ).object; - delete object.camera.matrix; + this.points = []; - return object; + for ( var i = 0, l = json.points.length; i < l; i ++ ) { - } + var point = json.points[ i ]; + this.points.push( new Vector2().fromArray( point ) ); - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + return this; - function SpotLightShadow() { + }; - LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) ); - } - SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { + var Curves = Object.freeze({ + ArcCurve: ArcCurve, + CatmullRomCurve3: CatmullRomCurve3, + CubicBezierCurve: CubicBezierCurve, + CubicBezierCurve3: CubicBezierCurve3, + EllipseCurve: EllipseCurve, + LineCurve: LineCurve, + LineCurve3: LineCurve3, + QuadraticBezierCurve: QuadraticBezierCurve, + QuadraticBezierCurve3: QuadraticBezierCurve3, + SplineCurve: SplineCurve + }); - constructor: SpotLightShadow, + /** + * @author zz85 / http://www.lab4games.net/zz85/blog + * + **/ - isSpotLightShadow: true, + /************************************************************** + * Curved Path - a curve path is simply a array of connected + * curves, but retains the api of a curve + **************************************************************/ - update: function ( light ) { + function CurvePath() { - var camera = this.camera; + Curve.call( this ); - var fov = _Math.RAD2DEG * 2 * light.angle; - var aspect = this.mapSize.width / this.mapSize.height; - var far = light.distance || camera.far; + this.type = 'CurvePath'; - if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { + this.curves = []; + this.autoClose = false; // Automatically closes the path - camera.fov = fov; - camera.aspect = aspect; - camera.far = far; - camera.updateProjectionMatrix(); + } - } + CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), { - } + constructor: CurvePath, - } ); + add: function ( curve ) { - /** - * @author alteredq / http://alteredqualia.com/ - */ + this.curves.push( curve ); - function SpotLight( color, intensity, distance, angle, penumbra, decay ) { + }, - Light.call( this, color, intensity ); + closePath: function () { - this.type = 'SpotLight'; + // Add a line curve if start and end of lines are not connected + var startPoint = this.curves[ 0 ].getPoint( 0 ); + var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); - this.position.copy( Object3D.DefaultUp ); - this.updateMatrix(); + if ( ! startPoint.equals( endPoint ) ) { - this.target = new Object3D(); + this.curves.push( new LineCurve( endPoint, startPoint ) ); - Object.defineProperty( this, 'power', { - get: function () { - // intensity = power per solid angle. - // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf - return this.intensity * Math.PI; - }, - set: function ( power ) { - // intensity = power per solid angle. - // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf - this.intensity = power / Math.PI; } - } ); - this.distance = ( distance !== undefined ) ? distance : 0; - this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; - this.penumbra = ( penumbra !== undefined ) ? penumbra : 0; - this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. + }, - this.shadow = new SpotLightShadow(); + // To get accurate point with reference to + // entire path distance at time t, + // following has to be done: - } + // 1. Length of each sub path have to be known + // 2. Locate and identify type of curve + // 3. Get t for the curve + // 4. Return curve.getPointAt(t') - SpotLight.prototype = Object.assign( Object.create( Light.prototype ), { + getPoint: function ( t ) { - constructor: SpotLight, + var d = t * this.getLength(); + var curveLengths = this.getCurveLengths(); + var i = 0; - isSpotLight: true, + // To think about boundaries points. - copy: function ( source ) { + while ( i < curveLengths.length ) { - Light.prototype.copy.call( this, source ); + if ( curveLengths[ i ] >= d ) { - this.distance = source.distance; - this.angle = source.angle; - this.penumbra = source.penumbra; - this.decay = source.decay; + var diff = curveLengths[ i ] - d; + var curve = this.curves[ i ]; - this.target = source.target.clone(); + var segmentLength = curve.getLength(); + var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; - this.shadow = source.shadow.clone(); + return curve.getPointAt( u ); - return this; + } - } + i ++; - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + return null; + // loop where sum != 0, sum > d , sum+1 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) { - this.type = 'AmbientLight'; + points.push( points[ 0 ] ); - this.castShadow = undefined; + } - } + return points; - AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), { + }, - constructor: AmbientLight, + copy: function ( source ) { - isAmbientLight: true + Curve.prototype.copy.call( this, source ); - } ); + this.curves = []; - /** - * @author abelnation / http://github.com/abelnation - */ + for ( var i = 0, l = source.curves.length; i < l; i ++ ) { - function RectAreaLight( color, intensity, width, height ) { + var curve = source.curves[ i ]; - Light.call( this, color, intensity ); + this.curves.push( curve.clone() ); - this.type = 'RectAreaLight'; + } - this.position.set( 0, 1, 0 ); - this.updateMatrix(); + this.autoClose = source.autoClose; - this.width = ( width !== undefined ) ? width : 10; - this.height = ( height !== undefined ) ? height : 10; + return this; - // TODO (abelnation): distance/decay + }, - // TODO (abelnation): update method for RectAreaLight to update transform to lookat target + toJSON: function () { - // TODO (abelnation): shadows + var data = Curve.prototype.toJSON.call( this ); - } + data.autoClose = this.autoClose; + data.curves = []; - // TODO (abelnation): RectAreaLight update when light shape is changed - RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), { + for ( var i = 0, l = this.curves.length; i < l; i ++ ) { - constructor: RectAreaLight, + var curve = this.curves[ i ]; + data.curves.push( curve.toJSON() ); - isRectAreaLight: true, + } - copy: function ( source ) { + return data; - Light.prototype.copy.call( this, source ); + }, - this.width = source.width; - this.height = source.height; + fromJSON: function ( json ) { - return this; + Curve.prototype.fromJSON.call( this, json ); - }, + this.autoClose = json.autoClose; + this.curves = []; - toJSON: function ( meta ) { + for ( var i = 0, l = json.curves.length; i < l; i ++ ) { - var data = Light.prototype.toJSON.call( this, meta ); + var curve = json.curves[ i ]; + this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) ); - data.object.width = this.width; - data.object.height = this.height; + } - return data; + return this; } } ); /** - * @author tschw - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - */ + * @author zz85 / http://www.lab4games.net/zz85/blog + * Creates free form 2d path using series of points, lines or curves. + **/ - var AnimationUtils = { + function Path( points ) { - // same as Array.prototype.slice, but also works on typed arrays - arraySlice: function ( array, from, to ) { + CurvePath.call( this ); - if ( AnimationUtils.isTypedArray( array ) ) { + this.type = 'Path'; - // in ios9 array.subarray(from, undefined) will return empty array - // but array.subarray(from) or array.subarray(from, len) is correct - return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) ); + this.currentPoint = new Vector2(); - } + if ( points ) { - return array.slice( from, to ); + this.setFromPoints( points ); - }, + } - // converts an array to a specific type - convertArray: function ( array, type, forceClone ) { + } - if ( ! array || // let 'undefined' and 'null' pass - ! forceClone && array.constructor === type ) return array; + Path.prototype = Object.assign( Object.create( CurvePath.prototype ), { - if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { + constructor: Path, - return new type( array ); // create typed array + setFromPoints: function ( points ) { - } + this.moveTo( points[ 0 ].x, points[ 0 ].y ); - return Array.prototype.slice.call( array ); // create Array + for ( var i = 1, l = points.length; i < l; i ++ ) { + + this.lineTo( points[ i ].x, points[ i ].y ); + + } }, - isTypedArray: function ( object ) { + moveTo: function ( x, y ) { - return ArrayBuffer.isView( object ) && - ! ( object instanceof DataView ); + this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? }, - // returns an array by which times and values can be sorted - getKeyframeOrder: function ( times ) { + lineTo: function ( x, y ) { - function compareTime( i, j ) { + var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); + this.curves.push( curve ); - return times[ i ] - times[ j ]; + this.currentPoint.set( x, y ); - } + }, - var n = times.length; - var result = new Array( n ); - for ( var i = 0; i !== n; ++ i ) result[ i ] = i; + quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { - result.sort( compareTime ); + var curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2( aCPx, aCPy ), + new Vector2( aX, aY ) + ); - return result; + this.curves.push( curve ); + + this.currentPoint.set( aX, aY ); }, - // uses the array previously returned by 'getKeyframeOrder' to sort data - sortedArray: function ( values, stride, order ) { + bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - var nValues = values.length; - var result = new values.constructor( nValues ); + var curve = new CubicBezierCurve( + this.currentPoint.clone(), + new Vector2( aCP1x, aCP1y ), + new Vector2( aCP2x, aCP2y ), + new Vector2( aX, aY ) + ); - for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { + this.curves.push( curve ); - var srcOffset = order[ i ] * stride; + this.currentPoint.set( aX, aY ); - for ( var j = 0; j !== stride; ++ j ) { + }, - result[ dstOffset ++ ] = values[ srcOffset + j ]; + splineThru: function ( pts /*Array of Vector*/ ) { - } + var npts = [ this.currentPoint.clone() ].concat( pts ); - } + var curve = new SplineCurve( npts ); + this.curves.push( curve ); - return result; + this.currentPoint.copy( pts[ pts.length - 1 ] ); }, - // function for parsing AOS keyframe formats - flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) { + arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - var i = 1, key = jsonKeys[ 0 ]; + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; - while ( key !== undefined && key[ valuePropertyName ] === undefined ) { + this.absarc( aX + x0, aY + y0, aRadius, + aStartAngle, aEndAngle, aClockwise ); - key = jsonKeys[ i ++ ]; + }, - } + absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - if ( key === undefined ) return; // no data + this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - var value = key[ valuePropertyName ]; - if ( value === undefined ) return; // no data + }, - if ( Array.isArray( value ) ) { + ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - do { + var x0 = this.currentPoint.x; + var y0 = this.currentPoint.y; - value = key[ valuePropertyName ]; + this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - if ( value !== undefined ) { + }, - times.push( key.time ); - values.push.apply( values, value ); // push all elements + absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - } + var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - key = jsonKeys[ i ++ ]; + if ( this.curves.length > 0 ) { - } while ( key !== undefined ); + // if a previous curve is present, attempt to join + var firstPoint = curve.getPoint( 0 ); - } else if ( value.toArray !== undefined ) { + if ( ! firstPoint.equals( this.currentPoint ) ) { - // ...assume THREE.Math-ish + this.lineTo( firstPoint.x, firstPoint.y ); - do { + } - value = key[ valuePropertyName ]; + } - if ( value !== undefined ) { + this.curves.push( curve ); - times.push( key.time ); - value.toArray( values, values.length ); + var lastPoint = curve.getPoint( 1 ); + this.currentPoint.copy( lastPoint ); - } + }, - key = jsonKeys[ i ++ ]; + copy: function ( source ) { - } while ( key !== undefined ); + CurvePath.prototype.copy.call( this, source ); - } else { + this.currentPoint.copy( source.currentPoint ); - // otherwise push as-is + return this; - do { + }, - value = key[ valuePropertyName ]; + toJSON: function () { - if ( value !== undefined ) { + var data = CurvePath.prototype.toJSON.call( this ); - times.push( key.time ); - values.push( value ); + data.currentPoint = this.currentPoint.toArray(); - } + return data; - key = jsonKeys[ i ++ ]; + }, - } while ( key !== undefined ); + fromJSON: function ( json ) { - } + CurvePath.prototype.fromJSON.call( this, json ); + + this.currentPoint.fromArray( json.currentPoint ); + + return this; } - }; + } ); /** - * Abstract base class of interpolants over parametric samples. - * - * The parameter domain is one dimensional, typically the time or a path - * along a curve defined by the data. - * - * The sample values can have any dimensionality and derived classes may - * apply special interpretations to the data. - * - * This class provides the interval seek in a Template Method, deferring - * the actual interpolation to derived classes. - * - * Time complexity is O(1) for linear access crossing at most two points - * and O(log N) for random access, where N is the number of positions. - * - * References: - * - * http://www.oodesign.com/template-method-pattern.html - * - * @author tschw - */ + * @author zz85 / http://www.lab4games.net/zz85/blog + * Defines a 2d shape plane using paths. + **/ - function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + // STEP 1 Create a path. + // STEP 2 Turn path into shape. + // STEP 3 ExtrudeGeometry takes in Shape/Shapes + // STEP 3a - Extract points from each shape, turn to vertices + // STEP 3b - Triangulate each shape, add faces. - this.parameterPositions = parameterPositions; - this._cachedIndex = 0; + function Shape( points ) { - this.resultBuffer = resultBuffer !== undefined ? - resultBuffer : new sampleValues.constructor( sampleSize ); - this.sampleValues = sampleValues; - this.valueSize = sampleSize; + Path.call( this, points ); - } + this.uuid = _Math.generateUUID(); - Object.assign( Interpolant.prototype, { + this.type = 'Shape'; - evaluate: function( t ) { + this.holes = []; - var pp = this.parameterPositions, - i1 = this._cachedIndex, + } - t1 = pp[ i1 ], - t0 = pp[ i1 - 1 ]; + Shape.prototype = Object.assign( Object.create( Path.prototype ), { - validate_interval: { + constructor: Shape, - seek: { + getPointsHoles: function ( divisions ) { - var right; + var holesPts = []; - linear_scan: { - //- See http://jsperf.com/comparison-to-undefined/3 - //- slower code: - //- - //- if ( t >= t1 || t1 === undefined ) { - forward_scan: if ( ! ( t < t1 ) ) { + for ( var i = 0, l = this.holes.length; i < l; i ++ ) { - for ( var giveUpAt = i1 + 2; ;) { + holesPts[ i ] = this.holes[ i ].getPoints( divisions ); - if ( t1 === undefined ) { + } - if ( t < t0 ) break forward_scan; + return holesPts; - // after end + }, - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t, t0 ); + // get points of shape and holes (keypoints based on segments parameter) - } + extractPoints: function ( divisions ) { - if ( i1 === giveUpAt ) break; // this loop + return { - t0 = t1; - t1 = pp[ ++ i1 ]; + shape: this.getPoints( divisions ), + holes: this.getPointsHoles( divisions ) - if ( t < t1 ) { + }; - // we have arrived at the sought interval - break seek; + }, - } + copy: function ( source ) { - } + Path.prototype.copy.call( this, source ); - // prepare binary search on the right side of the index - right = pp.length; - break linear_scan; + this.holes = []; - } + for ( var i = 0, l = source.holes.length; i < l; i ++ ) { - //- slower code: - //- if ( t < t0 || t0 === undefined ) { - if ( ! ( t >= t0 ) ) { + var hole = source.holes[ i ]; - // looping? + this.holes.push( hole.clone() ); - var t1global = pp[ 1 ]; + } - if ( t < t1global ) { + return this; - i1 = 2; // + 1, using the scan for the details - t0 = t1global; + }, - } + toJSON: function () { - // linear reverse scan + var data = Path.prototype.toJSON.call( this ); - for ( var giveUpAt = i1 - 2; ;) { + data.uuid = this.uuid; + data.holes = []; - if ( t0 === undefined ) { + for ( var i = 0, l = this.holes.length; i < l; i ++ ) { - // before start + var hole = this.holes[ i ]; + data.holes.push( hole.toJSON() ); - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + } - } + return data; - if ( i1 === giveUpAt ) break; // this loop + }, - t1 = t0; - t0 = pp[ -- i1 - 1 ]; + fromJSON: function ( json ) { - if ( t >= t0 ) { + Path.prototype.fromJSON.call( this, json ); - // we have arrived at the sought interval - break seek; + this.uuid = json.uuid; + this.holes = []; - } + for ( var i = 0, l = json.holes.length; i < l; i ++ ) { - } + var hole = json.holes[ i ]; + this.holes.push( new Path().fromJSON( hole ) ); - // prepare binary search on the left side of the index - right = i1; - i1 = 0; - break linear_scan; + } - } + return this; - // the interval is valid + } - break validate_interval; + } ); - } // linear scan + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - // binary search + function Light( color, intensity ) { - while ( i1 < right ) { + Object3D.call( this ); - var mid = ( i1 + right ) >>> 1; + this.type = 'Light'; - if ( t < pp[ mid ] ) { + this.color = new Color( color ); + this.intensity = intensity !== undefined ? intensity : 1; - right = mid; + this.receiveShadow = undefined; - } else { + } - i1 = mid + 1; + Light.prototype = Object.assign( Object.create( Object3D.prototype ), { - } + constructor: Light, - } + isLight: true, - t1 = pp[ i1 ]; - t0 = pp[ i1 - 1 ]; + copy: function ( source ) { - // check boundary cases, again + Object3D.prototype.copy.call( this, source ); - if ( t0 === undefined ) { + this.color.copy( source.color ); + this.intensity = source.intensity; - this._cachedIndex = 0; - return this.beforeStart_( 0, t, t1 ); + return this; - } + }, - if ( t1 === undefined ) { + toJSON: function ( meta ) { - i1 = pp.length; - this._cachedIndex = i1; - return this.afterEnd_( i1 - 1, t0, t ); + var data = Object3D.prototype.toJSON.call( this, meta ); - } + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; - } // seek + if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex(); - this._cachedIndex = i1; + if ( this.distance !== undefined ) data.object.distance = this.distance; + if ( this.angle !== undefined ) data.object.angle = this.angle; + if ( this.decay !== undefined ) data.object.decay = this.decay; + if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra; - this.intervalChanged_( i1, t0, t1 ); + if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON(); - } // validate_interval + return data; - return this.interpolate_( i1, t0, t, t1 ); + } - }, + } ); - settings: null, // optional, subclass-specific settings structure - // Note: The indirection allows central control of many interpolants. + /** + * @author alteredq / http://alteredqualia.com/ + */ - // --- Protected interface + function HemisphereLight( skyColor, groundColor, intensity ) { - DefaultSettings_: {}, + Light.call( this, skyColor, intensity ); + + this.type = 'HemisphereLight'; - getSettings_: function() { + this.castShadow = undefined; - return this.settings || this.DefaultSettings_; + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - }, + this.groundColor = new Color( groundColor ); + + } - copySampleValue_: function( index ) { + HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), { - // copies a sample value to the result buffer + constructor: HemisphereLight, - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, - offset = index * stride; + isHemisphereLight: true, - for ( var i = 0; i !== stride; ++ i ) { + copy: function ( source ) { - result[ i ] = values[ offset + i ]; + Light.prototype.copy.call( this, source ); - } + this.groundColor.copy( source.groundColor ); - return result; + return this; - }, + } - // Template methods for derived classes: + } ); - interpolate_: function( i1, t0, t, t1 ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - throw new Error( "call to abstract method" ); - // implementations shall return this.resultBuffer + function LightShadow( camera ) { - }, + this.camera = camera; - intervalChanged_: function( i1, t0, t1 ) { + this.bias = 0; + this.radius = 1; - // empty + this.mapSize = new Vector2( 512, 512 ); - } + this.map = null; + this.matrix = new Matrix4(); - } ); + } - //!\ DECLARE ALIAS AFTER assign prototype ! - Object.assign( Interpolant.prototype, { + Object.assign( LightShadow.prototype, { - //( 0, t, t0 ), returns this.resultBuffer - beforeStart_: Interpolant.prototype.copySampleValue_, + copy: function ( source ) { - //( N-1, tN-1, t ), returns this.resultBuffer - afterEnd_: Interpolant.prototype.copySampleValue_, + this.camera = source.camera.clone(); - } ); + this.bias = source.bias; + this.radius = source.radius; - /** - * Fast and simple cubic spline interpolant. - * - * It was derived from a Hermitian construction setting the first derivative - * at each sample position to the linear slope between neighboring positions - * over their parameter interval. - * - * @author tschw - */ + this.mapSize.copy( source.mapSize ); - function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + return this; - Interpolant.call( - this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + }, - this._weightPrev = -0; - this._offsetPrev = -0; - this._weightNext = -0; - this._offsetNext = -0; + clone: function () { - } + return new this.constructor().copy( this ); - CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { + }, - constructor: CubicInterpolant, + toJSON: function () { - DefaultSettings_: { + var object = {}; + + if ( this.bias !== 0 ) object.bias = this.bias; + if ( this.radius !== 1 ) object.radius = this.radius; + if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray(); - endingStart: ZeroCurvatureEnding, - endingEnd: ZeroCurvatureEnding + object.camera = this.camera.toJSON( false ).object; + delete object.camera.matrix; - }, + return object; - intervalChanged_: function( i1, t0, t1 ) { + } - var pp = this.parameterPositions, - iPrev = i1 - 2, - iNext = i1 + 1, + } ); - tPrev = pp[ iPrev ], - tNext = pp[ iNext ]; + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( tPrev === undefined ) { + function SpotLightShadow() { - switch ( this.getSettings_().endingStart ) { + LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) ); - case ZeroSlopeEnding: + } - // f'(t0) = 0 - iPrev = i1; - tPrev = 2 * t0 - t1; + SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - break; + constructor: SpotLightShadow, - case WrapAroundEnding: + isSpotLightShadow: true, - // use the other end of the curve - iPrev = pp.length - 2; - tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; + update: function ( light ) { - break; + var camera = this.camera; - default: // ZeroCurvatureEnding + var fov = _Math.RAD2DEG * 2 * light.angle; + var aspect = this.mapSize.width / this.mapSize.height; + var far = light.distance || camera.far; - // f''(t0) = 0 a.k.a. Natural Spline - iPrev = i1; - tPrev = t1; + if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { - } + camera.fov = fov; + camera.aspect = aspect; + camera.far = far; + camera.updateProjectionMatrix(); } - if ( tNext === undefined ) { - - switch ( this.getSettings_().endingEnd ) { + } - case ZeroSlopeEnding: + } ); - // f'(tN) = 0 - iNext = i1; - tNext = 2 * t1 - t0; + /** + * @author alteredq / http://alteredqualia.com/ + */ - break; + function SpotLight( color, intensity, distance, angle, penumbra, decay ) { - case WrapAroundEnding: + Light.call( this, color, intensity ); - // use the other end of the curve - iNext = 1; - tNext = t1 + pp[ 1 ] - pp[ 0 ]; + this.type = 'SpotLight'; - break; + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - default: // ZeroCurvatureEnding + this.target = new Object3D(); - // f''(tN) = 0, a.k.a. Natural Spline - iNext = i1 - 1; - tNext = t0; + Object.defineProperty( this, 'power', { + get: function () { - } + // intensity = power per solid angle. + // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf + return this.intensity * Math.PI; - } + }, + set: function ( power ) { - var halfDt = ( t1 - t0 ) * 0.5, - stride = this.valueSize; + // intensity = power per solid angle. + // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf + this.intensity = power / Math.PI; - this._weightPrev = halfDt / ( t0 - tPrev ); - this._weightNext = halfDt / ( tNext - t1 ); - this._offsetPrev = iPrev * stride; - this._offsetNext = iNext * stride; + } + } ); - }, + this.distance = ( distance !== undefined ) ? distance : 0; + this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; + this.penumbra = ( penumbra !== undefined ) ? penumbra : 0; + this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - interpolate_: function( i1, t0, t, t1 ) { + this.shadow = new SpotLightShadow(); - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + } - o1 = i1 * stride, o0 = o1 - stride, - oP = this._offsetPrev, oN = this._offsetNext, - wP = this._weightPrev, wN = this._weightNext, + SpotLight.prototype = Object.assign( Object.create( Light.prototype ), { - p = ( t - t0 ) / ( t1 - t0 ), - pp = p * p, - ppp = pp * p; + constructor: SpotLight, - // evaluate polynomials + isSpotLight: true, - var sP = - wP * ppp + 2 * wP * pp - wP * p; - var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1; - var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; - var sN = wN * ppp - wN * pp; + copy: function ( source ) { - // combine data linearly + Light.prototype.copy.call( this, source ); - for ( var i = 0; i !== stride; ++ i ) { + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; - result[ i ] = - sP * values[ oP + i ] + - s0 * values[ o0 + i ] + - s1 * values[ o1 + i ] + - sN * values[ oN + i ]; + this.target = source.target.clone(); - } + this.shadow = source.shadow.clone(); - return result; + return this; } } ); /** - * @author tschw + * @author mrdoob / http://mrdoob.com/ */ - function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - - } - - LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { - constructor: LinearInterpolant, + function PointLight( color, intensity, distance, decay ) { - interpolate_: function( i1, t0, t, t1 ) { + Light.call( this, color, intensity ); - var result = this.resultBuffer, - values = this.sampleValues, - stride = this.valueSize, + this.type = 'PointLight'; - offset1 = i1 * stride, - offset0 = offset1 - stride, + Object.defineProperty( this, 'power', { + get: function () { - weight1 = ( t - t0 ) / ( t1 - t0 ), - weight0 = 1 - weight1; + // intensity = power per solid angle. + // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf + return this.intensity * 4 * Math.PI; - for ( var i = 0; i !== stride; ++ i ) { + }, + set: function ( power ) { - result[ i ] = - values[ offset0 + i ] * weight0 + - values[ offset1 + i ] * weight1; + // intensity = power per solid angle. + // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf + this.intensity = power / ( 4 * Math.PI ); } + } ); - return result; + this.distance = ( distance !== undefined ) ? distance : 0; + this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. - } + this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) ); - } ); + } - /** - * - * Interpolant that evaluates to the sample value at the position preceeding - * the parameter. - * - * @author tschw - */ + PointLight.prototype = Object.assign( Object.create( Light.prototype ), { - function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + constructor: PointLight, - Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); + isPointLight: true, - } + copy: function ( source ) { - DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { + Light.prototype.copy.call( this, source ); - constructor: DiscreteInterpolant, + this.distance = source.distance; + this.decay = source.decay; - interpolate_: function( i1, t0, t, t1 ) { + this.shadow = source.shadow.clone(); - return this.copySampleValue_( i1 - 1 ); + return this; } } ); - var KeyframeTrackPrototype; + /** + * @author mrdoob / http://mrdoob.com/ + */ - KeyframeTrackPrototype = { + function DirectionalLightShadow( ) { - TimeBufferType: Float32Array, - ValueBufferType: Float32Array, + LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); - DefaultInterpolation: InterpolateLinear, + } - InterpolantFactoryMethodDiscrete: function ( result ) { + DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { - return new DiscreteInterpolant( - this.times, this.values, this.getValueSize(), result ); + constructor: DirectionalLightShadow - }, + } ); - InterpolantFactoryMethodLinear: function ( result ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - return new LinearInterpolant( - this.times, this.values, this.getValueSize(), result ); + function DirectionalLight( color, intensity ) { - }, + Light.call( this, color, intensity ); - InterpolantFactoryMethodSmooth: function ( result ) { + this.type = 'DirectionalLight'; - return new CubicInterpolant( - this.times, this.values, this.getValueSize(), result ); + this.position.copy( Object3D.DefaultUp ); + this.updateMatrix(); - }, + this.target = new Object3D(); - setInterpolation: function ( interpolation ) { + this.shadow = new DirectionalLightShadow(); - var factoryMethod; + } - switch ( interpolation ) { + DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), { - case InterpolateDiscrete: + constructor: DirectionalLight, - factoryMethod = this.InterpolantFactoryMethodDiscrete; + isDirectionalLight: true, - break; + copy: function ( source ) { - case InterpolateLinear: + Light.prototype.copy.call( this, source ); - factoryMethod = this.InterpolantFactoryMethodLinear; + this.target = source.target.clone(); - break; + this.shadow = source.shadow.clone(); - case InterpolateSmooth: + return this; - factoryMethod = this.InterpolantFactoryMethodSmooth; + } - break; + } ); - } + /** + * @author mrdoob / http://mrdoob.com/ + */ - if ( factoryMethod === undefined ) { + function AmbientLight( color, intensity ) { - var message = "unsupported interpolation for " + - this.ValueTypeName + " keyframe track named " + this.name; + Light.call( this, color, intensity ); - if ( this.createInterpolant === undefined ) { + this.type = 'AmbientLight'; - // fall back to default, unless the default itself is messed up - if ( interpolation !== this.DefaultInterpolation ) { + this.castShadow = undefined; - this.setInterpolation( this.DefaultInterpolation ); + } - } else { + AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), { - throw new Error( message ); // fatal, in this case + constructor: AmbientLight, - } + isAmbientLight: true - } + } ); - console.warn( 'THREE.KeyframeTrackPrototype:', message ); - return; + /** + * @author abelnation / http://github.com/abelnation + */ - } + function RectAreaLight( color, intensity, width, height ) { - this.createInterpolant = factoryMethod; + Light.call( this, color, intensity ); - }, + this.type = 'RectAreaLight'; - getInterpolation: function () { + this.width = ( width !== undefined ) ? width : 10; + this.height = ( height !== undefined ) ? height : 10; - switch ( this.createInterpolant ) { + } - case this.InterpolantFactoryMethodDiscrete: + RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), { - return InterpolateDiscrete; + constructor: RectAreaLight, - case this.InterpolantFactoryMethodLinear: + isRectAreaLight: true, - return InterpolateLinear; + copy: function ( source ) { - case this.InterpolantFactoryMethodSmooth: + Light.prototype.copy.call( this, source ); - return InterpolateSmooth; + this.width = source.width; + this.height = source.height; - } + return this; }, - getValueSize: function () { + toJSON: function ( meta ) { - return this.values.length / this.times.length; + var data = Light.prototype.toJSON.call( this, meta ); - }, + data.object.width = this.width; + data.object.height = this.height; - // move all keyframes either forwards or backwards in time - shift: function ( timeOffset ) { + return data; - if ( timeOffset !== 0.0 ) { + } - var times = this.times; + } ); - for ( var i = 0, n = times.length; i !== n; ++ i ) { + /** + * + * A Track that interpolates Strings + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - times[ i ] += timeOffset; + function StringKeyframeTrack( name, times, values, interpolation ) { - } + KeyframeTrack.call( this, name, times, values, interpolation ); - } + } - return this; + StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { - }, + constructor: StringKeyframeTrack, - // scale all keyframe times by a factor (useful for frame <-> seconds conversions) - scale: function ( timeScale ) { + ValueTypeName: 'string', + ValueBufferType: Array, - if ( timeScale !== 1.0 ) { + DefaultInterpolation: InterpolateDiscrete, - var times = this.times; + InterpolantFactoryMethodLinear: undefined, - for ( var i = 0, n = times.length; i !== n; ++ i ) { + InterpolantFactoryMethodSmooth: undefined - times[ i ] *= timeScale; + } ); - } + /** + * + * A Track of Boolean keyframe values. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - } + function BooleanKeyframeTrack( name, times, values ) { - return this; + KeyframeTrack.call( this, name, times, values ); - }, + } - // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. - // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values - trim: function ( startTime, endTime ) { + BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { - var times = this.times, - nKeys = times.length, - from = 0, - to = nKeys - 1; + constructor: BooleanKeyframeTrack, - while ( from !== nKeys && times[ from ] < startTime ) ++ from; - while ( to !== - 1 && times[ to ] > endTime ) -- to; + ValueTypeName: 'bool', + ValueBufferType: Array, - ++ to; // inclusive -> exclusive bound + DefaultInterpolation: InterpolateDiscrete, - if ( from !== 0 || to !== nKeys ) { + InterpolantFactoryMethodLinear: undefined, + InterpolantFactoryMethodSmooth: undefined - // empty tracks are forbidden, so keep at least one keyframe - if ( from >= to ) to = Math.max( to, 1 ), from = to - 1; + // Note: Actually this track could have a optimized / compressed + // representation of a single value and a custom interpolant that + // computes "firstValue ^ isOdd( index )". - var stride = this.getValueSize(); - this.times = AnimationUtils.arraySlice( times, from, to ); - this.values = AnimationUtils. - arraySlice( this.values, from * stride, to * stride ); + } ); - } + /** + * Abstract base class of interpolants over parametric samples. + * + * The parameter domain is one dimensional, typically the time or a path + * along a curve defined by the data. + * + * The sample values can have any dimensionality and derived classes may + * apply special interpretations to the data. + * + * This class provides the interval seek in a Template Method, deferring + * the actual interpolation to derived classes. + * + * Time complexity is O(1) for linear access crossing at most two points + * and O(log N) for random access, where N is the number of positions. + * + * References: + * + * http://www.oodesign.com/template-method-pattern.html + * + * @author tschw + */ - return this; + function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - }, + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; - // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable - validate: function () { + this.resultBuffer = resultBuffer !== undefined ? + resultBuffer : new sampleValues.constructor( sampleSize ); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; - var valid = true; + } - var valueSize = this.getValueSize(); - if ( valueSize - Math.floor( valueSize ) !== 0 ) { + Object.assign( Interpolant.prototype, { - console.error( 'THREE.KeyframeTrackPrototype: Invalid value size in track.', this ); - valid = false; + evaluate: function ( t ) { - } + var pp = this.parameterPositions, + i1 = this._cachedIndex, - var times = this.times, - values = this.values, + t1 = pp[ i1 ], + t0 = pp[ i1 - 1 ]; - nKeys = times.length; + validate_interval: { - if ( nKeys === 0 ) { + seek: { - console.error( 'THREE.KeyframeTrackPrototype: Track is empty.', this ); - valid = false; + var right; - } + linear_scan: { - var prevTime = null; + //- See http://jsperf.com/comparison-to-undefined/3 + //- slower code: + //- + //- if ( t >= t1 || t1 === undefined ) { + forward_scan: if ( ! ( t < t1 ) ) { - for ( var i = 0; i !== nKeys; i ++ ) { + for ( var giveUpAt = i1 + 2; ; ) { - var currTime = times[ i ]; + if ( t1 === undefined ) { - if ( typeof currTime === 'number' && isNaN( currTime ) ) { + if ( t < t0 ) break forward_scan; + + // after end - console.error( 'THREE.KeyframeTrackPrototype: Time is not a valid number.', this, i, currTime ); - valid = false; - break; + i1 = pp.length; + this._cachedIndex = i1; + return this.afterEnd_( i1 - 1, t, t0 ); - } + } - if ( prevTime !== null && prevTime > currTime ) { + if ( i1 === giveUpAt ) break; // this loop - console.error( 'THREE.KeyframeTrackPrototype: Out of order keys.', this, i, currTime, prevTime ); - valid = false; - break; + t0 = t1; + t1 = pp[ ++ i1 ]; - } + if ( t < t1 ) { - prevTime = currTime; + // we have arrived at the sought interval + break seek; - } + } - if ( values !== undefined ) { + } - if ( AnimationUtils.isTypedArray( values ) ) { + // prepare binary search on the right side of the index + right = pp.length; + break linear_scan; - for ( var i = 0, n = values.length; i !== n; ++ i ) { + } - var value = values[ i ]; + //- slower code: + //- if ( t < t0 || t0 === undefined ) { + if ( ! ( t >= t0 ) ) { - if ( isNaN( value ) ) { + // looping? - console.error( 'THREE.KeyframeTrackPrototype: Value is not a valid number.', this, i, value ); - valid = false; - break; + var t1global = pp[ 1 ]; - } + if ( t < t1global ) { - } + i1 = 2; // + 1, using the scan for the details + t0 = t1global; - } + } - } + // linear reverse scan - return valid; + for ( var giveUpAt = i1 - 2; ; ) { - }, + if ( t0 === undefined ) { - // removes equivalent sequential keys as common in morph target sequences - // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) - optimize: function () { + // before start - var times = this.times, - values = this.values, - stride = this.getValueSize(), + this._cachedIndex = 0; + return this.beforeStart_( 0, t, t1 ); - smoothInterpolation = this.getInterpolation() === InterpolateSmooth, + } - writeIndex = 1, - lastIndex = times.length - 1; + if ( i1 === giveUpAt ) break; // this loop - for ( var i = 1; i < lastIndex; ++ i ) { + t1 = t0; + t0 = pp[ -- i1 - 1 ]; - var keep = false; + if ( t >= t0 ) { - var time = times[ i ]; - var timeNext = times[ i + 1 ]; + // we have arrived at the sought interval + break seek; - // remove adjacent keyframes scheduled at the same time + } - if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { + } - if ( ! smoothInterpolation ) { + // prepare binary search on the left side of the index + right = i1; + i1 = 0; + break linear_scan; - // remove unnecessary keyframes same as their neighbors + } - var offset = i * stride, - offsetP = offset - stride, - offsetN = offset + stride; + // the interval is valid - for ( var j = 0; j !== stride; ++ j ) { + break validate_interval; - var value = values[ offset + j ]; + } // linear scan - if ( value !== values[ offsetP + j ] || - value !== values[ offsetN + j ] ) { + // binary search - keep = true; - break; + while ( i1 < right ) { - } + var mid = ( i1 + right ) >>> 1; - } + if ( t < pp[ mid ] ) { - } else keep = true; + right = mid; - } + } else { - // in-place compaction + i1 = mid + 1; - if ( keep ) { + } - if ( i !== writeIndex ) { + } - times[ writeIndex ] = times[ i ]; + t1 = pp[ i1 ]; + t0 = pp[ i1 - 1 ]; - var readOffset = i * stride, - writeOffset = writeIndex * stride; + // check boundary cases, again - for ( var j = 0; j !== stride; ++ j ) + if ( t0 === undefined ) { - values[ writeOffset + j ] = values[ readOffset + j ]; + this._cachedIndex = 0; + return this.beforeStart_( 0, t, t1 ); } - ++ writeIndex; - - } + if ( t1 === undefined ) { - } + i1 = pp.length; + this._cachedIndex = i1; + return this.afterEnd_( i1 - 1, t0, t ); - // flush last keyframe (compaction looks ahead) + } - if ( lastIndex > 0 ) { + } // seek - times[ writeIndex ] = times[ lastIndex ]; + this._cachedIndex = i1; - for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) + this.intervalChanged_( i1, t0, t1 ); - values[ writeOffset + j ] = values[ readOffset + j ]; + } // validate_interval - ++ writeIndex; + return this.interpolate_( i1, t0, t, t1 ); - } + }, - if ( writeIndex !== times.length ) { + settings: null, // optional, subclass-specific settings structure + // Note: The indirection allows central control of many interpolants. - this.times = AnimationUtils.arraySlice( times, 0, writeIndex ); - this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride ); + // --- Protected interface - } + DefaultSettings_: {}, - return this; + getSettings_: function () { - } + return this.settings || this.DefaultSettings_; - }; + }, - function KeyframeTrackConstructor( name, times, values, interpolation ) { + copySampleValue_: function ( index ) { - if ( name === undefined ) throw new Error( "track name is undefined" ); + // copies a sample value to the result buffer - if ( times === undefined || times.length === 0 ) { + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, + offset = index * stride; - throw new Error( "no keyframes in track named " + name ); + for ( var i = 0; i !== stride; ++ i ) { - } + result[ i ] = values[ offset + i ]; - this.name = name; + } - this.times = AnimationUtils.convertArray( times, this.TimeBufferType ); - this.values = AnimationUtils.convertArray( values, this.ValueBufferType ); + return result; - this.setInterpolation( interpolation || this.DefaultInterpolation ); + }, - this.validate(); - this.optimize(); + // Template methods for derived classes: - } + interpolate_: function ( /* i1, t0, t, t1 */ ) { - /** - * - * A Track of vectored keyframe values. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ + throw new Error( 'call to abstract method' ); + // implementations shall return this.resultBuffer - function VectorKeyframeTrack( name, times, values, interpolation ) { + }, - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); + intervalChanged_: function ( /* i1, t0, t1 */ ) { - } + // empty - VectorKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + } - constructor: VectorKeyframeTrack, + } ); - ValueTypeName: 'vector' + //!\ DECLARE ALIAS AFTER assign prototype ! + Object.assign( Interpolant.prototype, { - // ValueBufferType is inherited + //( 0, t, t0 ), returns this.resultBuffer + beforeStart_: Interpolant.prototype.copySampleValue_, - // DefaultInterpolation is inherited + //( N-1, tN-1, t ), returns this.resultBuffer + afterEnd_: Interpolant.prototype.copySampleValue_, } ); @@ -31908,7 +34153,7 @@ constructor: QuaternionLinearInterpolant, - interpolate_: function( i1, t0, t, t1 ) { + interpolate_: function ( i1, t0, t, t1 ) { var result = this.resultBuffer, values = this.sampleValues, @@ -31920,8 +34165,7 @@ for ( var end = offset + stride; offset !== end; offset += 4 ) { - Quaternion.slerpFlat( result, 0, - values, offset - stride, values, offset, alpha ); + Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); } @@ -31942,12 +34186,11 @@ function QuaternionKeyframeTrack( name, times, values, interpolation ) { - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); + KeyframeTrack.call( this, name, times, values, interpolation ); } - QuaternionKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { constructor: QuaternionKeyframeTrack, @@ -31957,10 +34200,9 @@ DefaultInterpolation: InterpolateLinear, - InterpolantFactoryMethodLinear: function( result ) { + InterpolantFactoryMethodLinear: function ( result ) { - return new QuaternionLinearInterpolant( - this.times, this.values, this.getValueSize(), result ); + return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result ); }, @@ -31970,1760 +34212,1504 @@ /** * - * A Track of numeric keyframe values. + * A Track of keyframe values that represent color. + * * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ * @author tschw */ - function NumberKeyframeTrack( name, times, values, interpolation ) { + function ColorKeyframeTrack( name, times, values, interpolation ) { - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); + KeyframeTrack.call( this, name, times, values, interpolation ); } - NumberKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { - constructor: NumberKeyframeTrack, + constructor: ColorKeyframeTrack, - ValueTypeName: 'number' + ValueTypeName: 'color' // ValueBufferType is inherited // DefaultInterpolation is inherited - } ); - - /** - * - * A Track that interpolates Strings - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ - - function StringKeyframeTrack( name, times, values, interpolation ) { - - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); - - } - - StringKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { - - constructor: StringKeyframeTrack, - - ValueTypeName: 'string', - ValueBufferType: Array, - - DefaultInterpolation: InterpolateDiscrete, - - InterpolantFactoryMethodLinear: undefined, - - InterpolantFactoryMethodSmooth: undefined - - } ); - - /** - * - * A Track of Boolean keyframe values. - * - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ - * @author tschw - */ - - function BooleanKeyframeTrack( name, times, values ) { - - KeyframeTrackConstructor.call( this, name, times, values ); - - } - - BooleanKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { - - constructor: BooleanKeyframeTrack, - - ValueTypeName: 'bool', - ValueBufferType: Array, - - DefaultInterpolation: InterpolateDiscrete, - - InterpolantFactoryMethodLinear: undefined, - InterpolantFactoryMethodSmooth: undefined - - // Note: Actually this track could have a optimized / compressed - // representation of a single value and a custom interpolant that - // computes "firstValue ^ isOdd( index )". + // Note: Very basic implementation and nothing special yet. + // However, this is the place for color space parameterization. } ); /** * - * A Track of keyframe values that represent color. - * + * A Track of numeric keyframe values. * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ * @author tschw */ - function ColorKeyframeTrack( name, times, values, interpolation ) { + function NumberKeyframeTrack( name, times, values, interpolation ) { - KeyframeTrackConstructor.call( this, name, times, values, interpolation ); + KeyframeTrack.call( this, name, times, values, interpolation ); } - ColorKeyframeTrack.prototype = - Object.assign( Object.create( KeyframeTrackPrototype ), { + NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { - constructor: ColorKeyframeTrack, + constructor: NumberKeyframeTrack, - ValueTypeName: 'color' + ValueTypeName: 'number' // ValueBufferType is inherited // DefaultInterpolation is inherited - - // Note: Very basic implementation and nothing special yet. - // However, this is the place for color space parameterization. - } ); /** + * Fast and simple cubic spline interpolant. * - * A timed sequence of keyframes for a specific property. - * + * It was derived from a Hermitian construction setting the first derivative + * at each sample position to the linear slope between neighboring positions + * over their parameter interval. * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ * @author tschw */ - function KeyframeTrack( name, times, values, interpolation ) { - - KeyframeTrackConstructor.apply( this, arguments ); + function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - } + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - KeyframeTrack.prototype = KeyframeTrackPrototype; - KeyframeTrackPrototype.constructor = KeyframeTrack; + this._weightPrev = - 0; + this._offsetPrev = - 0; + this._weightNext = - 0; + this._offsetNext = - 0; - // Static methods: + } - Object.assign( KeyframeTrack, { + CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { - // Serialization (in static context, because of constructor invocation - // and automatic invocation of .toJSON): + constructor: CubicInterpolant, - parse: function( json ) { + DefaultSettings_: { - if( json.type === undefined ) { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding - throw new Error( "track type undefined, can not parse" ); + }, - } + intervalChanged_: function ( i1, t0, t1 ) { - var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type ); + var pp = this.parameterPositions, + iPrev = i1 - 2, + iNext = i1 + 1, - if ( json.times === undefined ) { + tPrev = pp[ iPrev ], + tNext = pp[ iNext ]; - var times = [], values = []; + if ( tPrev === undefined ) { - AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); + switch ( this.getSettings_().endingStart ) { - json.times = times; - json.values = values; + case ZeroSlopeEnding: - } + // f'(t0) = 0 + iPrev = i1; + tPrev = 2 * t0 - t1; - // derived classes can define a static parse method - if ( trackType.parse !== undefined ) { + break; - return trackType.parse( json ); + case WrapAroundEnding: - } else { + // use the other end of the curve + iPrev = pp.length - 2; + tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; - // by default, we asssume a constructor compatible with the base - return new trackType( - json.name, json.times, json.values, json.interpolation ); + break; - } + default: // ZeroCurvatureEnding - }, + // f''(t0) = 0 a.k.a. Natural Spline + iPrev = i1; + tPrev = t1; - toJSON: function( track ) { + } - var trackType = track.constructor; + } - var json; + if ( tNext === undefined ) { - // derived classes can define a static toJSON method - if ( trackType.toJSON !== undefined ) { + switch ( this.getSettings_().endingEnd ) { - json = trackType.toJSON( track ); + case ZeroSlopeEnding: - } else { + // f'(tN) = 0 + iNext = i1; + tNext = 2 * t1 - t0; - // by default, we assume the data can be serialized as-is - json = { + break; - 'name': track.name, - 'times': AnimationUtils.convertArray( track.times, Array ), - 'values': AnimationUtils.convertArray( track.values, Array ) + case WrapAroundEnding: - }; + // use the other end of the curve + iNext = 1; + tNext = t1 + pp[ 1 ] - pp[ 0 ]; - var interpolation = track.getInterpolation(); + break; - if ( interpolation !== track.DefaultInterpolation ) { + default: // ZeroCurvatureEnding - json.interpolation = interpolation; + // f''(tN) = 0, a.k.a. Natural Spline + iNext = i1 - 1; + tNext = t0; } } - json.type = track.ValueTypeName; // mandatory + var halfDt = ( t1 - t0 ) * 0.5, + stride = this.valueSize; - return json; + this._weightPrev = halfDt / ( t0 - tPrev ); + this._weightNext = halfDt / ( tNext - t1 ); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; }, - _getTrackTypeForValueTypeName: function( typeName ) { - - switch( typeName.toLowerCase() ) { - - case "scalar": - case "double": - case "float": - case "number": - case "integer": - - return NumberKeyframeTrack; - - case "vector": - case "vector2": - case "vector3": - case "vector4": - - return VectorKeyframeTrack; + interpolate_: function ( i1, t0, t, t1 ) { - case "color": + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - return ColorKeyframeTrack; + o1 = i1 * stride, o0 = o1 - stride, + oP = this._offsetPrev, oN = this._offsetNext, + wP = this._weightPrev, wN = this._weightNext, - case "quaternion": + p = ( t - t0 ) / ( t1 - t0 ), + pp = p * p, + ppp = pp * p; - return QuaternionKeyframeTrack; + // evaluate polynomials - case "bool": - case "boolean": + var sP = - wP * ppp + 2 * wP * pp - wP * p; + var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1; + var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; + var sN = wN * ppp - wN * pp; - return BooleanKeyframeTrack; + // combine data linearly - case "string": + for ( var i = 0; i !== stride; ++ i ) { - return StringKeyframeTrack; + result[ i ] = + sP * values[ oP + i ] + + s0 * values[ o0 + i ] + + s1 * values[ o1 + i ] + + sN * values[ oN + i ]; } - throw new Error( "Unsupported typeName: " + typeName ); + return result; } } ); /** - * - * Reusable set of Tracks that represent an animation. - * - * @author Ben Houston / http://clara.io/ - * @author David Sarno / http://lighthaus.us/ + * @author tschw */ - function AnimationClip( name, duration, tracks ) { - - this.name = name; - this.tracks = tracks; - this.duration = ( duration !== undefined ) ? duration : - 1; - - this.uuid = _Math.generateUUID(); - - // this means it should figure out its duration by scanning the tracks - if ( this.duration < 0 ) { - - this.resetDuration(); - - } + function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - this.optimize(); + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); } - Object.assign( AnimationClip, { - - parse: function ( json ) { - - var tracks = [], - jsonTracks = json.tracks, - frameTime = 1.0 / ( json.fps || 1.0 ); + LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { - for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { + constructor: LinearInterpolant, - tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) ); + interpolate_: function ( i1, t0, t, t1 ) { - } + var result = this.resultBuffer, + values = this.sampleValues, + stride = this.valueSize, - return new AnimationClip( json.name, json.duration, tracks ); + offset1 = i1 * stride, + offset0 = offset1 - stride, - }, + weight1 = ( t - t0 ) / ( t1 - t0 ), + weight0 = 1 - weight1; - toJSON: function ( clip ) { + for ( var i = 0; i !== stride; ++ i ) { - var tracks = [], - clipTracks = clip.tracks; + result[ i ] = + values[ offset0 + i ] * weight0 + + values[ offset1 + i ] * weight1; - var json = { + } - 'name': clip.name, - 'duration': clip.duration, - 'tracks': tracks + return result; - }; + } - for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { + } ); - tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); + /** + * + * Interpolant that evaluates to the sample value at the position preceeding + * the parameter. + * + * @author tschw + */ - } + function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { - return json; + Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); - }, + } - CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) { + DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { - var numMorphTargets = morphTargetSequence.length; - var tracks = []; + constructor: DiscreteInterpolant, - for ( var i = 0; i < numMorphTargets; i ++ ) { + interpolate_: function ( i1 /*, t0, t, t1 */ ) { - var times = []; - var values = []; + return this.copySampleValue_( i1 - 1 ); - times.push( - ( i + numMorphTargets - 1 ) % numMorphTargets, - i, - ( i + 1 ) % numMorphTargets ); + } - values.push( 0, 1, 0 ); + } ); - var order = AnimationUtils.getKeyframeOrder( times ); - times = AnimationUtils.sortedArray( times, 1, order ); - values = AnimationUtils.sortedArray( values, 1, order ); + /** + * @author tschw + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + */ - // if there is a key at the first frame, duplicate it as the - // last frame as well for perfect loop. - if ( ! noLoop && times[ 0 ] === 0 ) { + var AnimationUtils = { - times.push( numMorphTargets ); - values.push( values[ 0 ] ); + // same as Array.prototype.slice, but also works on typed arrays + arraySlice: function ( array, from, to ) { - } + if ( AnimationUtils.isTypedArray( array ) ) { - tracks.push( - new NumberKeyframeTrack( - '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', - times, values - ).scale( 1.0 / fps ) ); + // in ios9 array.subarray(from, undefined) will return empty array + // but array.subarray(from) or array.subarray(from, len) is correct + return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) ); } - return new AnimationClip( name, - 1, tracks ); + return array.slice( from, to ); }, - findByName: function ( objectOrClipArray, name ) { + // converts an array to a specific type + convertArray: function ( array, type, forceClone ) { - var clipArray = objectOrClipArray; + if ( ! array || // let 'undefined' and 'null' pass + ! forceClone && array.constructor === type ) return array; - if ( ! Array.isArray( objectOrClipArray ) ) { + if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { - var o = objectOrClipArray; - clipArray = o.geometry && o.geometry.animations || o.animations; + return new type( array ); // create typed array } - for ( var i = 0; i < clipArray.length; i ++ ) { - - if ( clipArray[ i ].name === name ) { - - return clipArray[ i ]; + return Array.prototype.slice.call( array ); // create Array - } + }, - } + isTypedArray: function ( object ) { - return null; + return ArrayBuffer.isView( object ) && + ! ( object instanceof DataView ); }, - CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) { - - var animationToMorphTargets = {}; + // returns an array by which times and values can be sorted + getKeyframeOrder: function ( times ) { - // tested with https://regex101.com/ on trick sequences - // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 - var pattern = /^([\w-]*?)([\d]+)$/; + function compareTime( i, j ) { - // sort morph target names into animation groups based - // patterns like Walk_001, Walk_002, Run_001, Run_002 - for ( var i = 0, il = morphTargets.length; i < il; i ++ ) { + return times[ i ] - times[ j ]; - var morphTarget = morphTargets[ i ]; - var parts = morphTarget.name.match( pattern ); + } - if ( parts && parts.length > 1 ) { + var n = times.length; + var result = new Array( n ); + for ( var i = 0; i !== n; ++ i ) result[ i ] = i; - var name = parts[ 1 ]; + result.sort( compareTime ); - var animationMorphTargets = animationToMorphTargets[ name ]; - if ( ! animationMorphTargets ) { + return result; - animationToMorphTargets[ name ] = animationMorphTargets = []; + }, - } + // uses the array previously returned by 'getKeyframeOrder' to sort data + sortedArray: function ( values, stride, order ) { - animationMorphTargets.push( morphTarget ); + var nValues = values.length; + var result = new values.constructor( nValues ); - } + for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { - } + var srcOffset = order[ i ] * stride; - var clips = []; + for ( var j = 0; j !== stride; ++ j ) { - for ( var name in animationToMorphTargets ) { + result[ dstOffset ++ ] = values[ srcOffset + j ]; - clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); + } } - return clips; + return result; }, - // parse the animation.hierarchy format - parseAnimation: function ( animation, bones ) { + // function for parsing AOS keyframe formats + flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) { - if ( ! animation ) { + var i = 1, key = jsonKeys[ 0 ]; - console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' ); - return null; + while ( key !== undefined && key[ valuePropertyName ] === undefined ) { + + key = jsonKeys[ i ++ ]; } - var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) { + if ( key === undefined ) return; // no data - // only return track if there are actually keys. - if ( animationKeys.length !== 0 ) { + var value = key[ valuePropertyName ]; + if ( value === undefined ) return; // no data - var times = []; - var values = []; + if ( Array.isArray( value ) ) { - AnimationUtils.flattenJSON( animationKeys, times, values, propertyName ); + do { - // empty keys are filtered out, so check again - if ( times.length !== 0 ) { + value = key[ valuePropertyName ]; - destTracks.push( new trackType( trackName, times, values ) ); + if ( value !== undefined ) { + + times.push( key.time ); + values.push.apply( values, value ); // push all elements } - } + key = jsonKeys[ i ++ ]; - }; + } while ( key !== undefined ); - var tracks = []; + } else if ( value.toArray !== undefined ) { - var clipName = animation.name || 'default'; - // automatic length determination in AnimationClip. - var duration = animation.length || - 1; - var fps = animation.fps || 30; + // ...assume THREE.Math-ish - var hierarchyTracks = animation.hierarchy || []; + do { - for ( var h = 0; h < hierarchyTracks.length; h ++ ) { + value = key[ valuePropertyName ]; - var animationKeys = hierarchyTracks[ h ].keys; + if ( value !== undefined ) { - // skip empty tracks - if ( ! animationKeys || animationKeys.length === 0 ) continue; + times.push( key.time ); + value.toArray( values, values.length ); - // process morph targets - if ( animationKeys[ 0 ].morphTargets ) { + } - // figure out all morph targets used in this track - var morphTargetNames = {}; + key = jsonKeys[ i ++ ]; - for ( var k = 0; k < animationKeys.length; k ++ ) { + } while ( key !== undefined ); - if ( animationKeys[ k ].morphTargets ) { + } else { - for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) { + // otherwise push as-is - morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1; + do { - } + value = key[ valuePropertyName ]; - } + if ( value !== undefined ) { + + times.push( key.time ); + values.push( value ); } - // create a track for each morph target with all zero - // morphTargetInfluences except for the keys in which - // the morphTarget is named. - for ( var morphTargetName in morphTargetNames ) { + key = jsonKeys[ i ++ ]; - var times = []; - var values = []; + } while ( key !== undefined ); - for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) { + } - var animationKey = animationKeys[ k ]; + } - times.push( animationKey.time ); - values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); + }; - } + /** + * + * A timed sequence of keyframes for a specific property. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); + function KeyframeTrack( name, times, values, interpolation ) { - } + if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); + if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); - duration = morphTargetNames.length * ( fps || 1.0 ); + this.name = name; - } else { + this.times = AnimationUtils.convertArray( times, this.TimeBufferType ); + this.values = AnimationUtils.convertArray( values, this.ValueBufferType ); - // ...assume skeletal animation + this.setInterpolation( interpolation || this.DefaultInterpolation ); - var boneName = '.bones[' + bones[ h ].name + ']'; + this.validate(); + this.optimize(); - addNonemptyTrack( - VectorKeyframeTrack, boneName + '.position', - animationKeys, 'pos', tracks ); + } - addNonemptyTrack( - QuaternionKeyframeTrack, boneName + '.quaternion', - animationKeys, 'rot', tracks ); + // Static methods: - addNonemptyTrack( - VectorKeyframeTrack, boneName + '.scale', - animationKeys, 'scl', tracks ); + Object.assign( KeyframeTrack, { - } + // Serialization (in static context, because of constructor invocation + // and automatic invocation of .toJSON): - } + parse: function ( json ) { - if ( tracks.length === 0 ) { + if ( json.type === undefined ) { - return null; + throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' ); } - var clip = new AnimationClip( clipName, duration, tracks ); + var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type ); - return clip; + if ( json.times === undefined ) { - } + var times = [], values = []; - } ); + AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); - Object.assign( AnimationClip.prototype, { + json.times = times; + json.values = values; - resetDuration: function () { + } - var tracks = this.tracks, duration = 0; + // derived classes can define a static parse method + if ( trackType.parse !== undefined ) { - for ( var i = 0, n = tracks.length; i !== n; ++ i ) { + return trackType.parse( json ); - var track = this.tracks[ i ]; + } else { - duration = Math.max( duration, track.times[ track.times.length - 1 ] ); + // by default, we assume a constructor compatible with the base + return new trackType( json.name, json.times, json.values, json.interpolation ); } - this.duration = duration; - }, - trim: function () { - - for ( var i = 0; i < this.tracks.length; i ++ ) { - - this.tracks[ i ].trim( 0, this.duration ); - - } + toJSON: function ( track ) { - return this; + var trackType = track.constructor; - }, + var json; - optimize: function () { + // derived classes can define a static toJSON method + if ( trackType.toJSON !== undefined ) { - for ( var i = 0; i < this.tracks.length; i ++ ) { + json = trackType.toJSON( track ); - this.tracks[ i ].optimize(); + } else { - } + // by default, we assume the data can be serialized as-is + json = { - return this; + 'name': track.name, + 'times': AnimationUtils.convertArray( track.times, Array ), + 'values': AnimationUtils.convertArray( track.values, Array ) - } + }; - } ); + var interpolation = track.getInterpolation(); - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( interpolation !== track.DefaultInterpolation ) { - function MaterialLoader( manager ) { + json.interpolation = interpolation; - this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; - this.textures = {}; + } - } + } - Object.assign( MaterialLoader.prototype, { + json.type = track.ValueTypeName; // mandatory - load: function ( url, onLoad, onProgress, onError ) { + return json; - var scope = this; + }, - var loader = new FileLoader( scope.manager ); - loader.load( url, function ( text ) { + _getTrackTypeForValueTypeName: function ( typeName ) { - onLoad( scope.parse( JSON.parse( text ) ) ); + switch ( typeName.toLowerCase() ) { - }, onProgress, onError ); + case 'scalar': + case 'double': + case 'float': + case 'number': + case 'integer': - }, + return NumberKeyframeTrack; - setTextures: function ( value ) { + case 'vector': + case 'vector2': + case 'vector3': + case 'vector4': - this.textures = value; + return VectorKeyframeTrack; - }, + case 'color': - parse: function ( json ) { + return ColorKeyframeTrack; - var textures = this.textures; + case 'quaternion': - function getTexture( name ) { + return QuaternionKeyframeTrack; - if ( textures[ name ] === undefined ) { + case 'bool': + case 'boolean': - console.warn( 'THREE.MaterialLoader: Undefined texture', name ); + return BooleanKeyframeTrack; - } + case 'string': - return textures[ name ]; + return StringKeyframeTrack; } - var material = new Materials[ json.type ](); + throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName ); - if ( json.uuid !== undefined ) material.uuid = json.uuid; - if ( json.name !== undefined ) material.name = json.name; - if ( json.color !== undefined ) material.color.setHex( json.color ); - if ( json.roughness !== undefined ) material.roughness = json.roughness; - if ( json.metalness !== undefined ) material.metalness = json.metalness; - if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive ); - if ( json.specular !== undefined ) material.specular.setHex( json.specular ); - if ( json.shininess !== undefined ) material.shininess = json.shininess; - if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat; - if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness; - if ( json.uniforms !== undefined ) material.uniforms = json.uniforms; - if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; - if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; - if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors; - if ( json.fog !== undefined ) material.fog = json.fog; - if ( json.shading !== undefined ) material.shading = json.shading; - if ( json.blending !== undefined ) material.blending = json.blending; - if ( json.side !== undefined ) material.side = json.side; - if ( json.opacity !== undefined ) material.opacity = json.opacity; - if ( json.transparent !== undefined ) material.transparent = json.transparent; - if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest; - if ( json.depthTest !== undefined ) material.depthTest = json.depthTest; - if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite; - if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite; - if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; - if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; - if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap; - if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin; - if ( json.skinning !== undefined ) material.skinning = json.skinning; - if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets; + } - // for PointsMaterial + } ); - if ( json.size !== undefined ) material.size = json.size; - if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; + Object.assign( KeyframeTrack.prototype, { - // maps + constructor: KeyframeTrack, - if ( json.map !== undefined ) material.map = getTexture( json.map ); + TimeBufferType: Float32Array, - if ( json.alphaMap !== undefined ) { + ValueBufferType: Float32Array, - material.alphaMap = getTexture( json.alphaMap ); - material.transparent = true; + DefaultInterpolation: InterpolateLinear, - } + InterpolantFactoryMethodDiscrete: function ( result ) { - if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap ); - if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; + return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result ); - if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap ); - if ( json.normalScale !== undefined ) { + }, - var normalScale = json.normalScale; + InterpolantFactoryMethodLinear: function ( result ) { - if ( Array.isArray( normalScale ) === false ) { + return new LinearInterpolant( this.times, this.values, this.getValueSize(), result ); - // Blender exporter used to export a scalar. See #7459 + }, - normalScale = [ normalScale, normalScale ]; + InterpolantFactoryMethodSmooth: function ( result ) { - } + return new CubicInterpolant( this.times, this.values, this.getValueSize(), result ); - material.normalScale = new Vector2().fromArray( normalScale ); + }, - } + setInterpolation: function ( interpolation ) { - if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap ); - if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale; - if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias; + var factoryMethod; - if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap ); - if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap ); + switch ( interpolation ) { - if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap ); - if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; + case InterpolateDiscrete: - if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap ); + factoryMethod = this.InterpolantFactoryMethodDiscrete; - if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap ); + break; - if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; + case InterpolateLinear: - if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap ); - if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; + factoryMethod = this.InterpolantFactoryMethodLinear; - if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap ); - if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; + break; - if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap ); + case InterpolateSmooth: - return material; + factoryMethod = this.InterpolantFactoryMethodSmooth; - } + break; - } ); + } - /** - * @author mrdoob / http://mrdoob.com/ - */ + if ( factoryMethod === undefined ) { - function BufferGeometryLoader( manager ) { + var message = "unsupported interpolation for " + + this.ValueTypeName + " keyframe track named " + this.name; - this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + if ( this.createInterpolant === undefined ) { - } + // fall back to default, unless the default itself is messed up + if ( interpolation !== this.DefaultInterpolation ) { - Object.assign( BufferGeometryLoader.prototype, { + this.setInterpolation( this.DefaultInterpolation ); - load: function ( url, onLoad, onProgress, onError ) { + } else { - var scope = this; + throw new Error( message ); // fatal, in this case - var loader = new FileLoader( scope.manager ); - loader.load( url, function ( text ) { + } - onLoad( scope.parse( JSON.parse( text ) ) ); + } - }, onProgress, onError ); + console.warn( 'THREE.KeyframeTrack:', message ); + return; - }, + } - parse: function ( json ) { + this.createInterpolant = factoryMethod; - var geometry = new BufferGeometry(); + }, - var index = json.data.index; + getInterpolation: function () { - if ( index !== undefined ) { + switch ( this.createInterpolant ) { - var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); - geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); + case this.InterpolantFactoryMethodDiscrete: - } + return InterpolateDiscrete; - var attributes = json.data.attributes; + case this.InterpolantFactoryMethodLinear: - for ( var key in attributes ) { + return InterpolateLinear; - var attribute = attributes[ key ]; - var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); + case this.InterpolantFactoryMethodSmooth: - geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); + return InterpolateSmooth; } - var groups = json.data.groups || json.data.drawcalls || json.data.offsets; - - if ( groups !== undefined ) { - - for ( var i = 0, n = groups.length; i !== n; ++ i ) { - - var group = groups[ i ]; + }, - geometry.addGroup( group.start, group.count, group.materialIndex ); + getValueSize: function () { - } + return this.values.length / this.times.length; - } + }, - var boundingSphere = json.data.boundingSphere; + // move all keyframes either forwards or backwards in time + shift: function ( timeOffset ) { - if ( boundingSphere !== undefined ) { + if ( timeOffset !== 0.0 ) { - var center = new Vector3(); + var times = this.times; - if ( boundingSphere.center !== undefined ) { + for ( var i = 0, n = times.length; i !== n; ++ i ) { - center.fromArray( boundingSphere.center ); + times[ i ] += timeOffset; } - geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); - } - return geometry; - - } - - } ); + return this; - var TYPED_ARRAYS = { - Int8Array: Int8Array, - Uint8Array: Uint8Array, - // Workaround for IE11 pre KB2929437. See #11440 - Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array, - Int16Array: Int16Array, - Uint16Array: Uint16Array, - Int32Array: Int32Array, - Uint32Array: Uint32Array, - Float32Array: Float32Array, - Float64Array: Float64Array - }; + }, - /** - * @author alteredq / http://alteredqualia.com/ - */ + // scale all keyframe times by a factor (useful for frame <-> seconds conversions) + scale: function ( timeScale ) { - function Loader() { + if ( timeScale !== 1.0 ) { - this.onLoadStart = function () {}; - this.onLoadProgress = function () {}; - this.onLoadComplete = function () {}; + var times = this.times; - } + for ( var i = 0, n = times.length; i !== n; ++ i ) { - Loader.Handlers = { + times[ i ] *= timeScale; - handlers: [], + } - add: function ( regex, loader ) { + } - this.handlers.push( regex, loader ); + return this; }, - get: function ( file ) { + // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. + // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values + trim: function ( startTime, endTime ) { - var handlers = this.handlers; + var times = this.times, + nKeys = times.length, + from = 0, + to = nKeys - 1; - for ( var i = 0, l = handlers.length; i < l; i += 2 ) { + while ( from !== nKeys && times[ from ] < startTime ) { - var regex = handlers[ i ]; - var loader = handlers[ i + 1 ]; + ++ from; - if ( regex.test( file ) ) { + } - return loader; + while ( to !== - 1 && times[ to ] > endTime ) { - } + -- to; } - return null; + ++ to; // inclusive -> exclusive bound + + if ( from !== 0 || to !== nKeys ) { - } + // empty tracks are forbidden, so keep at least one keyframe + if ( from >= to ) to = Math.max( to, 1 ), from = to - 1; - }; + var stride = this.getValueSize(); + this.times = AnimationUtils.arraySlice( times, from, to ); + this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride ); - Object.assign( Loader.prototype, { + } - crossOrigin: undefined, + return this; - extractUrlBase: function ( url ) { + }, - var parts = url.split( '/' ); + // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable + validate: function () { - if ( parts.length === 1 ) return './'; + var valid = true; - parts.pop(); + var valueSize = this.getValueSize(); + if ( valueSize - Math.floor( valueSize ) !== 0 ) { - return parts.join( '/' ) + '/'; + console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this ); + valid = false; - }, + } - initMaterials: function ( materials, texturePath, crossOrigin ) { + var times = this.times, + values = this.values, - var array = []; + nKeys = times.length; - for ( var i = 0; i < materials.length; ++ i ) { + if ( nKeys === 0 ) { - array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin ); + console.error( 'THREE.KeyframeTrack: Track is empty.', this ); + valid = false; } - return array; - - }, + var prevTime = null; - createMaterial: ( function () { + for ( var i = 0; i !== nKeys; i ++ ) { - var BlendingMode = { - NoBlending: NoBlending, - NormalBlending: NormalBlending, - AdditiveBlending: AdditiveBlending, - SubtractiveBlending: SubtractiveBlending, - MultiplyBlending: MultiplyBlending, - CustomBlending: CustomBlending - }; + var currTime = times[ i ]; - var color = new Color(); - var textureLoader = new TextureLoader(); - var materialLoader = new MaterialLoader(); + if ( typeof currTime === 'number' && isNaN( currTime ) ) { - return function createMaterial( m, texturePath, crossOrigin ) { + console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime ); + valid = false; + break; - // convert from old material format + } - var textures = {}; + if ( prevTime !== null && prevTime > currTime ) { - function loadTexture( path, repeat, offset, wrap, anisotropy ) { + console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime ); + valid = false; + break; - var fullPath = texturePath + path; - var loader = Loader.Handlers.get( fullPath ); + } - var texture; + prevTime = currTime; - if ( loader !== null ) { + } - texture = loader.load( fullPath ); + if ( values !== undefined ) { - } else { + if ( AnimationUtils.isTypedArray( values ) ) { - textureLoader.setCrossOrigin( crossOrigin ); - texture = textureLoader.load( fullPath ); + for ( var i = 0, n = values.length; i !== n; ++ i ) { - } + var value = values[ i ]; - if ( repeat !== undefined ) { + if ( isNaN( value ) ) { - texture.repeat.fromArray( repeat ); + console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value ); + valid = false; + break; - if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping; - if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping; + } } - if ( offset !== undefined ) { + } - texture.offset.fromArray( offset ); + } - } + return valid; - if ( wrap !== undefined ) { + }, - if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping; - if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping; + // removes equivalent sequential keys as common in morph target sequences + // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) + optimize: function () { - if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping; - if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping; + var times = this.times, + values = this.values, + stride = this.getValueSize(), - } + smoothInterpolation = this.getInterpolation() === InterpolateSmooth, - if ( anisotropy !== undefined ) { + writeIndex = 1, + lastIndex = times.length - 1; - texture.anisotropy = anisotropy; + for ( var i = 1; i < lastIndex; ++ i ) { - } + var keep = false; - var uuid = _Math.generateUUID(); + var time = times[ i ]; + var timeNext = times[ i + 1 ]; - textures[ uuid ] = texture; + // remove adjacent keyframes scheduled at the same time - return uuid; + if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { - } + if ( ! smoothInterpolation ) { - // + // remove unnecessary keyframes same as their neighbors - var json = { - uuid: _Math.generateUUID(), - type: 'MeshLambertMaterial' - }; + var offset = i * stride, + offsetP = offset - stride, + offsetN = offset + stride; - for ( var name in m ) { + for ( var j = 0; j !== stride; ++ j ) { - var value = m[ name ]; + var value = values[ offset + j ]; - switch ( name ) { + if ( value !== values[ offsetP + j ] || + value !== values[ offsetN + j ] ) { - case 'DbgColor': - case 'DbgIndex': - case 'opticalDensity': - case 'illumination': - break; - case 'DbgName': - json.name = value; - break; - case 'blending': - json.blending = BlendingMode[ value ]; - break; - case 'colorAmbient': - case 'mapAmbient': - console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' ); - break; - case 'colorDiffuse': - json.color = color.fromArray( value ).getHex(); - break; - case 'colorSpecular': - json.specular = color.fromArray( value ).getHex(); - break; - case 'colorEmissive': - json.emissive = color.fromArray( value ).getHex(); - break; - case 'specularCoef': - json.shininess = value; - break; - case 'shading': - if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial'; - if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial'; - if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial'; - break; - case 'mapDiffuse': - json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy ); - break; - case 'mapDiffuseRepeat': - case 'mapDiffuseOffset': - case 'mapDiffuseWrap': - case 'mapDiffuseAnisotropy': - break; - case 'mapEmissive': - json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy ); - break; - case 'mapEmissiveRepeat': - case 'mapEmissiveOffset': - case 'mapEmissiveWrap': - case 'mapEmissiveAnisotropy': - break; - case 'mapLight': - json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy ); - break; - case 'mapLightRepeat': - case 'mapLightOffset': - case 'mapLightWrap': - case 'mapLightAnisotropy': - break; - case 'mapAO': - json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy ); - break; - case 'mapAORepeat': - case 'mapAOOffset': - case 'mapAOWrap': - case 'mapAOAnisotropy': - break; - case 'mapBump': - json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy ); - break; - case 'mapBumpScale': - json.bumpScale = value; - break; - case 'mapBumpRepeat': - case 'mapBumpOffset': - case 'mapBumpWrap': - case 'mapBumpAnisotropy': - break; - case 'mapNormal': - json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy ); - break; - case 'mapNormalFactor': - json.normalScale = [ value, value ]; - break; - case 'mapNormalRepeat': - case 'mapNormalOffset': - case 'mapNormalWrap': - case 'mapNormalAnisotropy': - break; - case 'mapSpecular': - json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy ); - break; - case 'mapSpecularRepeat': - case 'mapSpecularOffset': - case 'mapSpecularWrap': - case 'mapSpecularAnisotropy': - break; - case 'mapMetalness': - json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy ); - break; - case 'mapMetalnessRepeat': - case 'mapMetalnessOffset': - case 'mapMetalnessWrap': - case 'mapMetalnessAnisotropy': - break; - case 'mapRoughness': - json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy ); - break; - case 'mapRoughnessRepeat': - case 'mapRoughnessOffset': - case 'mapRoughnessWrap': - case 'mapRoughnessAnisotropy': - break; - case 'mapAlpha': - json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy ); - break; - case 'mapAlphaRepeat': - case 'mapAlphaOffset': - case 'mapAlphaWrap': - case 'mapAlphaAnisotropy': - break; - case 'flipSided': - json.side = BackSide; - break; - case 'doubleSided': - json.side = DoubleSide; - break; - case 'transparency': - console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' ); - json.opacity = value; - break; - case 'depthTest': - case 'depthWrite': - case 'colorWrite': - case 'opacity': - case 'reflectivity': - case 'transparent': - case 'visible': - case 'wireframe': - json[ name ] = value; - break; - case 'vertexColors': - if ( value === true ) json.vertexColors = VertexColors; - if ( value === 'face' ) json.vertexColors = FaceColors; - break; - default: - console.error( 'THREE.Loader.createMaterial: Unsupported', name, value ); - break; + keep = true; + break; - } + } - } + } - if ( json.type === 'MeshBasicMaterial' ) delete json.emissive; - if ( json.type !== 'MeshPhongMaterial' ) delete json.specular; + } else { - if ( json.opacity < 1 ) json.transparent = true; + keep = true; - materialLoader.setTextures( textures ); + } - return materialLoader.parse( json ); + } - }; + // in-place compaction - } )() + if ( keep ) { - } ); + if ( i !== writeIndex ) { - /** - * @author mrdoob / http://mrdoob.com/ - * @author alteredq / http://alteredqualia.com/ - */ + times[ writeIndex ] = times[ i ]; - function JSONLoader( manager ) { + var readOffset = i * stride, + writeOffset = writeIndex * stride; - if ( typeof manager === 'boolean' ) { + for ( var j = 0; j !== stride; ++ j ) { - console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' ); - manager = undefined; + values[ writeOffset + j ] = values[ readOffset + j ]; - } + } - this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + } - this.withCredentials = false; + ++ writeIndex; - } + } - Object.assign( JSONLoader.prototype, { + } - load: function ( url, onLoad, onProgress, onError ) { + // flush last keyframe (compaction looks ahead) - var scope = this; + if ( lastIndex > 0 ) { - var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url ); + times[ writeIndex ] = times[ lastIndex ]; - var loader = new FileLoader( this.manager ); - loader.setWithCredentials( this.withCredentials ); - loader.load( url, function ( text ) { + for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) { - var json = JSON.parse( text ); - var metadata = json.metadata; + values[ writeOffset + j ] = values[ readOffset + j ]; - if ( metadata !== undefined ) { + } - var type = metadata.type; + ++ writeIndex; - if ( type !== undefined ) { + } - if ( type.toLowerCase() === 'object' ) { + if ( writeIndex !== times.length ) { - console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' ); - return; + this.times = AnimationUtils.arraySlice( times, 0, writeIndex ); + this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride ); - } + } - if ( type.toLowerCase() === 'scene' ) { + return this; - console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' ); - return; + } - } + } ); - } + /** + * + * A Track of vectored keyframe values. + * + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + * @author tschw + */ - } + function VectorKeyframeTrack( name, times, values, interpolation ) { - var object = scope.parse( json, texturePath ); - onLoad( object.geometry, object.materials ); + KeyframeTrack.call( this, name, times, values, interpolation ); - }, onProgress, onError ); + } - }, + VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { - setTexturePath: function ( value ) { + constructor: VectorKeyframeTrack, - this.texturePath = value; + ValueTypeName: 'vector' - }, + // ValueBufferType is inherited - parse: ( function () { + // DefaultInterpolation is inherited - function parseModel( json, geometry ) { + } ); - function isBitSet( value, position ) { + /** + * + * Reusable set of Tracks that represent an animation. + * + * @author Ben Houston / http://clara.io/ + * @author David Sarno / http://lighthaus.us/ + */ - return value & ( 1 << position ); + function AnimationClip( name, duration, tracks ) { - } + this.name = name; + this.tracks = tracks; + this.duration = ( duration !== undefined ) ? duration : - 1; - var i, j, fi, + this.uuid = _Math.generateUUID(); - offset, zLength, + // this means it should figure out its duration by scanning the tracks + if ( this.duration < 0 ) { - colorIndex, normalIndex, uvIndex, materialIndex, + this.resetDuration(); - type, - isQuad, - hasMaterial, - hasFaceVertexUv, - hasFaceNormal, hasFaceVertexNormal, - hasFaceColor, hasFaceVertexColor, + } - vertex, face, faceA, faceB, hex, normal, + this.optimize(); - uvLayer, uv, u, v, + } - faces = json.faces, - vertices = json.vertices, - normals = json.normals, - colors = json.colors, + Object.assign( AnimationClip, { - scale = json.scale, + parse: function ( json ) { - nUvLayers = 0; + var tracks = [], + jsonTracks = json.tracks, + frameTime = 1.0 / ( json.fps || 1.0 ); + for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { - if ( json.uvs !== undefined ) { + tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) ); - // disregard empty arrays + } - for ( i = 0; i < json.uvs.length; i ++ ) { + return new AnimationClip( json.name, json.duration, tracks ); - if ( json.uvs[ i ].length ) nUvLayers ++; + }, - } + toJSON: function ( clip ) { - for ( i = 0; i < nUvLayers; i ++ ) { + var tracks = [], + clipTracks = clip.tracks; - geometry.faceVertexUvs[ i ] = []; + var json = { - } + 'name': clip.name, + 'duration': clip.duration, + 'tracks': tracks - } + }; - offset = 0; - zLength = vertices.length; + for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { - while ( offset < zLength ) { + tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); - vertex = new Vector3(); + } - vertex.x = vertices[ offset ++ ] * scale; - vertex.y = vertices[ offset ++ ] * scale; - vertex.z = vertices[ offset ++ ] * scale; + return json; - geometry.vertices.push( vertex ); + }, - } + CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) { - offset = 0; - zLength = faces.length; + var numMorphTargets = morphTargetSequence.length; + var tracks = []; - while ( offset < zLength ) { + for ( var i = 0; i < numMorphTargets; i ++ ) { - type = faces[ offset ++ ]; + var times = []; + var values = []; - isQuad = isBitSet( type, 0 ); - hasMaterial = isBitSet( type, 1 ); - hasFaceVertexUv = isBitSet( type, 3 ); - hasFaceNormal = isBitSet( type, 4 ); - hasFaceVertexNormal = isBitSet( type, 5 ); - hasFaceColor = isBitSet( type, 6 ); - hasFaceVertexColor = isBitSet( type, 7 ); + times.push( + ( i + numMorphTargets - 1 ) % numMorphTargets, + i, + ( i + 1 ) % numMorphTargets ); - // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); + values.push( 0, 1, 0 ); - if ( isQuad ) { + var order = AnimationUtils.getKeyframeOrder( times ); + times = AnimationUtils.sortedArray( times, 1, order ); + values = AnimationUtils.sortedArray( values, 1, order ); - faceA = new Face3(); - faceA.a = faces[ offset ]; - faceA.b = faces[ offset + 1 ]; - faceA.c = faces[ offset + 3 ]; + // if there is a key at the first frame, duplicate it as the + // last frame as well for perfect loop. + if ( ! noLoop && times[ 0 ] === 0 ) { - faceB = new Face3(); - faceB.a = faces[ offset + 1 ]; - faceB.b = faces[ offset + 2 ]; - faceB.c = faces[ offset + 3 ]; + times.push( numMorphTargets ); + values.push( values[ 0 ] ); - offset += 4; + } - if ( hasMaterial ) { + tracks.push( + new NumberKeyframeTrack( + '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', + times, values + ).scale( 1.0 / fps ) ); - materialIndex = faces[ offset ++ ]; - faceA.materialIndex = materialIndex; - faceB.materialIndex = materialIndex; + } - } + return new AnimationClip( name, - 1, tracks ); - // to get face <=> uv index correspondence + }, - fi = geometry.faces.length; + findByName: function ( objectOrClipArray, name ) { - if ( hasFaceVertexUv ) { + var clipArray = objectOrClipArray; - for ( i = 0; i < nUvLayers; i ++ ) { + if ( ! Array.isArray( objectOrClipArray ) ) { - uvLayer = json.uvs[ i ]; + var o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; - geometry.faceVertexUvs[ i ][ fi ] = []; - geometry.faceVertexUvs[ i ][ fi + 1 ] = []; + } - for ( j = 0; j < 4; j ++ ) { + for ( var i = 0; i < clipArray.length; i ++ ) { - uvIndex = faces[ offset ++ ]; + if ( clipArray[ i ].name === name ) { - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; + return clipArray[ i ]; - uv = new Vector2( u, v ); + } - if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); - if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); + } - } + return null; - } + }, - } + CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) { - if ( hasFaceNormal ) { + var animationToMorphTargets = {}; - normalIndex = faces[ offset ++ ] * 3; + // tested with https://regex101.com/ on trick sequences + // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 + var pattern = /^([\w-]*?)([\d]+)$/; - faceA.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + // sort morph target names into animation groups based + // patterns like Walk_001, Walk_002, Run_001, Run_002 + for ( var i = 0, il = morphTargets.length; i < il; i ++ ) { - faceB.normal.copy( faceA.normal ); + var morphTarget = morphTargets[ i ]; + var parts = morphTarget.name.match( pattern ); - } + if ( parts && parts.length > 1 ) { - if ( hasFaceVertexNormal ) { + var name = parts[ 1 ]; - for ( i = 0; i < 4; i ++ ) { + var animationMorphTargets = animationToMorphTargets[ name ]; + if ( ! animationMorphTargets ) { - normalIndex = faces[ offset ++ ] * 3; + animationToMorphTargets[ name ] = animationMorphTargets = []; - normal = new Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + } + animationMorphTargets.push( morphTarget ); - if ( i !== 2 ) faceA.vertexNormals.push( normal ); - if ( i !== 0 ) faceB.vertexNormals.push( normal ); + } - } + } - } + var clips = []; + for ( var name in animationToMorphTargets ) { - if ( hasFaceColor ) { + clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; + } - faceA.color.setHex( hex ); - faceB.color.setHex( hex ); + return clips; - } + }, + // parse the animation.hierarchy format + parseAnimation: function ( animation, bones ) { - if ( hasFaceVertexColor ) { + if ( ! animation ) { - for ( i = 0; i < 4; i ++ ) { + console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' ); + return null; - colorIndex = faces[ offset ++ ]; - hex = colors[ colorIndex ]; + } - if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) ); - if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) ); + var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) { - } + // only return track if there are actually keys. + if ( animationKeys.length !== 0 ) { - } + var times = []; + var values = []; - geometry.faces.push( faceA ); - geometry.faces.push( faceB ); + AnimationUtils.flattenJSON( animationKeys, times, values, propertyName ); - } else { + // empty keys are filtered out, so check again + if ( times.length !== 0 ) { - face = new Face3(); - face.a = faces[ offset ++ ]; - face.b = faces[ offset ++ ]; - face.c = faces[ offset ++ ]; + destTracks.push( new trackType( trackName, times, values ) ); - if ( hasMaterial ) { + } - materialIndex = faces[ offset ++ ]; - face.materialIndex = materialIndex; + } - } + }; - // to get face <=> uv index correspondence + var tracks = []; - fi = geometry.faces.length; + var clipName = animation.name || 'default'; + // automatic length determination in AnimationClip. + var duration = animation.length || - 1; + var fps = animation.fps || 30; - if ( hasFaceVertexUv ) { + var hierarchyTracks = animation.hierarchy || []; - for ( i = 0; i < nUvLayers; i ++ ) { + for ( var h = 0; h < hierarchyTracks.length; h ++ ) { - uvLayer = json.uvs[ i ]; + var animationKeys = hierarchyTracks[ h ].keys; - geometry.faceVertexUvs[ i ][ fi ] = []; + // skip empty tracks + if ( ! animationKeys || animationKeys.length === 0 ) continue; - for ( j = 0; j < 3; j ++ ) { + // process morph targets + if ( animationKeys[ 0 ].morphTargets ) { - uvIndex = faces[ offset ++ ]; + // figure out all morph targets used in this track + var morphTargetNames = {}; - u = uvLayer[ uvIndex * 2 ]; - v = uvLayer[ uvIndex * 2 + 1 ]; + for ( var k = 0; k < animationKeys.length; k ++ ) { - uv = new Vector2( u, v ); + if ( animationKeys[ k ].morphTargets ) { - geometry.faceVertexUvs[ i ][ fi ].push( uv ); + for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) { - } + morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1; } } - if ( hasFaceNormal ) { + } - normalIndex = faces[ offset ++ ] * 3; + // create a track for each morph target with all zero + // morphTargetInfluences except for the keys in which + // the morphTarget is named. + for ( var morphTargetName in morphTargetNames ) { - face.normal.set( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + var times = []; + var values = []; - } + for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) { - if ( hasFaceVertexNormal ) { + var animationKey = animationKeys[ k ]; - for ( i = 0; i < 3; i ++ ) { + times.push( animationKey.time ); + values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); - normalIndex = faces[ offset ++ ] * 3; + } - normal = new Vector3( - normals[ normalIndex ++ ], - normals[ normalIndex ++ ], - normals[ normalIndex ] - ); + tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); - face.vertexNormals.push( normal ); + } - } + duration = morphTargetNames.length * ( fps || 1.0 ); - } + } else { + // ...assume skeletal animation - if ( hasFaceColor ) { + var boneName = '.bones[' + bones[ h ].name + ']'; - colorIndex = faces[ offset ++ ]; - face.color.setHex( colors[ colorIndex ] ); + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.position', + animationKeys, 'pos', tracks ); - } + addNonemptyTrack( + QuaternionKeyframeTrack, boneName + '.quaternion', + animationKeys, 'rot', tracks ); + addNonemptyTrack( + VectorKeyframeTrack, boneName + '.scale', + animationKeys, 'scl', tracks ); - if ( hasFaceVertexColor ) { + } - for ( i = 0; i < 3; i ++ ) { + } - colorIndex = faces[ offset ++ ]; - face.vertexColors.push( new Color( colors[ colorIndex ] ) ); + if ( tracks.length === 0 ) { - } + return null; - } + } - geometry.faces.push( face ); + var clip = new AnimationClip( clipName, duration, tracks ); - } + return clip; - } + } - } + } ); - function parseSkin( json, geometry ) { + Object.assign( AnimationClip.prototype, { - var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; + resetDuration: function () { - if ( json.skinWeights ) { + var tracks = this.tracks, duration = 0; - for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { + for ( var i = 0, n = tracks.length; i !== n; ++ i ) { - var x = json.skinWeights[ i ]; - var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0; - var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0; - var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0; + var track = this.tracks[ i ]; - geometry.skinWeights.push( new Vector4( x, y, z, w ) ); + duration = Math.max( duration, track.times[ track.times.length - 1 ] ); - } + } - } + this.duration = duration; - if ( json.skinIndices ) { + }, - for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { + trim: function () { - var a = json.skinIndices[ i ]; - var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0; - var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0; - var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0; + for ( var i = 0; i < this.tracks.length; i ++ ) { - geometry.skinIndices.push( new Vector4( a, b, c, d ) ); + this.tracks[ i ].trim( 0, this.duration ); - } + } - } + return this; - geometry.bones = json.bones; + }, - if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { + optimize: function () { - console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + - geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); + for ( var i = 0; i < this.tracks.length; i ++ ) { - } + this.tracks[ i ].optimize(); } - function parseMorphing( json, geometry ) { + return this; - var scale = json.scale; + } - if ( json.morphTargets !== undefined ) { + } ); - for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) { + /** + * @author mrdoob / http://mrdoob.com/ + */ - geometry.morphTargets[ i ] = {}; - geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; - geometry.morphTargets[ i ].vertices = []; + function MaterialLoader( manager ) { - var dstVertices = geometry.morphTargets[ i ].vertices; - var srcVertices = json.morphTargets[ i ].vertices; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + this.textures = {}; - for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) { + } - var vertex = new Vector3(); - vertex.x = srcVertices[ v ] * scale; - vertex.y = srcVertices[ v + 1 ] * scale; - vertex.z = srcVertices[ v + 2 ] * scale; + Object.assign( MaterialLoader.prototype, { - dstVertices.push( vertex ); + load: function ( url, onLoad, onProgress, onError ) { - } + var scope = this; - } + var loader = new FileLoader( scope.manager ); + loader.load( url, function ( text ) { - } + onLoad( scope.parse( JSON.parse( text ) ) ); - if ( json.morphColors !== undefined && json.morphColors.length > 0 ) { + }, onProgress, onError ); - console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' ); + }, - var faces = geometry.faces; - var morphColors = json.morphColors[ 0 ].colors; + setTextures: function ( value ) { - for ( var i = 0, l = faces.length; i < l; i ++ ) { + this.textures = value; - faces[ i ].color.fromArray( morphColors, i * 3 ); + }, - } + parse: function ( json ) { - } + var textures = this.textures; - } + function getTexture( name ) { - function parseAnimations( json, geometry ) { + if ( textures[ name ] === undefined ) { - var outputAnimations = []; + console.warn( 'THREE.MaterialLoader: Undefined texture', name ); - // parse old style Bone/Hierarchy animations - var animations = []; + } - if ( json.animation !== undefined ) { + return textures[ name ]; - animations.push( json.animation ); + } - } + var material = new Materials[ json.type ](); - if ( json.animations !== undefined ) { + if ( json.uuid !== undefined ) material.uuid = json.uuid; + if ( json.name !== undefined ) material.name = json.name; + if ( json.color !== undefined ) material.color.setHex( json.color ); + if ( json.roughness !== undefined ) material.roughness = json.roughness; + if ( json.metalness !== undefined ) material.metalness = json.metalness; + if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive ); + if ( json.specular !== undefined ) material.specular.setHex( json.specular ); + if ( json.shininess !== undefined ) material.shininess = json.shininess; + if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat; + if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness; + if ( json.uniforms !== undefined ) material.uniforms = json.uniforms; + if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; + if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; + if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors; + if ( json.fog !== undefined ) material.fog = json.fog; + if ( json.flatShading !== undefined ) material.flatShading = json.flatShading; + if ( json.blending !== undefined ) material.blending = json.blending; + if ( json.side !== undefined ) material.side = json.side; + if ( json.opacity !== undefined ) material.opacity = json.opacity; + if ( json.transparent !== undefined ) material.transparent = json.transparent; + if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest; + if ( json.depthTest !== undefined ) material.depthTest = json.depthTest; + if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite; + if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite; + if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; + if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; + if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap; + if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin; - if ( json.animations.length ) { + if ( json.rotation !== undefined ) material.rotation = json.rotation; - animations = animations.concat( json.animations ); + if ( json.linewidth !== 1 ) material.linewidth = json.linewidth; + if ( json.dashSize !== undefined ) material.dashSize = json.dashSize; + if ( json.gapSize !== undefined ) material.gapSize = json.gapSize; + if ( json.scale !== undefined ) material.scale = json.scale; - } else { + if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset; + if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor; + if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits; - animations.push( json.animations ); + if ( json.skinning !== undefined ) material.skinning = json.skinning; + if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets; + if ( json.dithering !== undefined ) material.dithering = json.dithering; - } + if ( json.visible !== undefined ) material.visible = json.visible; + if ( json.userData !== undefined ) material.userData = json.userData; - } + // Deprecated - for ( var i = 0; i < animations.length; i ++ ) { + if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading - var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones ); - if ( clip ) outputAnimations.push( clip ); + // for PointsMaterial - } + if ( json.size !== undefined ) material.size = json.size; + if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation; - // parse implicit morph animations - if ( geometry.morphTargets ) { + // maps - // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary. - var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 ); - outputAnimations = outputAnimations.concat( morphAnimationClips ); + if ( json.map !== undefined ) material.map = getTexture( json.map ); - } + if ( json.alphaMap !== undefined ) { - if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations; + material.alphaMap = getTexture( json.alphaMap ); + material.transparent = true; } - return function ( json, texturePath ) { + if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap ); + if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale; - if ( json.data !== undefined ) { + if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap ); + if ( json.normalScale !== undefined ) { - // Geometry 4.0 spec - json = json.data; + var normalScale = json.normalScale; - } + if ( Array.isArray( normalScale ) === false ) { - if ( json.scale !== undefined ) { + // Blender exporter used to export a scalar. See #7459 - json.scale = 1.0 / json.scale; + normalScale = [ normalScale, normalScale ]; - } else { + } - json.scale = 1.0; + material.normalScale = new Vector2().fromArray( normalScale ); - } + } - var geometry = new Geometry(); + if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap ); + if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale; + if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias; - parseModel( json, geometry ); - parseSkin( json, geometry ); - parseMorphing( json, geometry ); - parseAnimations( json, geometry ); + if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap ); + if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap ); - geometry.computeFaceNormals(); - geometry.computeBoundingSphere(); + if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap ); + if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity; - if ( json.materials === undefined || json.materials.length === 0 ) { + if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap ); - return { geometry: geometry }; + if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap ); - } else { + if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity; - var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); + if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap ); + if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity; - return { geometry: geometry, materials: materials }; + if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap ); + if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity; - } + if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap ); - }; + return material; - } )() + } } ); @@ -33731,1879 +35717,1958 @@ * @author mrdoob / http://mrdoob.com/ */ - function ObjectLoader( manager ) { + function BufferGeometryLoader( manager ) { this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; - this.texturePath = ''; } - Object.assign( ObjectLoader.prototype, { + Object.assign( BufferGeometryLoader.prototype, { load: function ( url, onLoad, onProgress, onError ) { - if ( this.texturePath === '' ) { + var scope = this; - this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 ); + var loader = new FileLoader( scope.manager ); + loader.load( url, function ( text ) { + + onLoad( scope.parse( JSON.parse( text ) ) ); + + }, onProgress, onError ); + + }, + + parse: function ( json ) { + + var geometry = new BufferGeometry(); + + var index = json.data.index; + + if ( index !== undefined ) { + + var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); + geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); } - var scope = this; + var attributes = json.data.attributes; - var loader = new FileLoader( scope.manager ); - loader.load( url, function ( text ) { + for ( var key in attributes ) { - var json = null; + var attribute = attributes[ key ]; + var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); - try { + geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) ); - json = JSON.parse( text ); + } - } catch ( error ) { + var groups = json.data.groups || json.data.drawcalls || json.data.offsets; - if ( onError !== undefined ) onError( error ); + if ( groups !== undefined ) { - console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message ); + for ( var i = 0, n = groups.length; i !== n; ++ i ) { - return; + var group = groups[ i ]; + + geometry.addGroup( group.start, group.count, group.materialIndex ); } - var metadata = json.metadata; + } - if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { + var boundingSphere = json.data.boundingSphere; - console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' ); - return; + if ( boundingSphere !== undefined ) { + + var center = new Vector3(); + + if ( boundingSphere.center !== undefined ) { + + center.fromArray( boundingSphere.center ); + + } + + geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); + + } + + return geometry; + + } + + } ); + + var TYPED_ARRAYS = { + Int8Array: Int8Array, + Uint8Array: Uint8Array, + // Workaround for IE11 pre KB2929437. See #11440 + Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array, + Int16Array: Int16Array, + Uint16Array: Uint16Array, + Int32Array: Int32Array, + Uint32Array: Uint32Array, + Float32Array: Float32Array, + Float64Array: Float64Array + }; - } + /** + * @author alteredq / http://alteredqualia.com/ + */ - scope.parse( json, onLoad ); + function Loader() {} - }, onProgress, onError ); + Loader.Handlers = { - }, + handlers: [], - setTexturePath: function ( value ) { + add: function ( regex, loader ) { - this.texturePath = value; + this.handlers.push( regex, loader ); }, - setCrossOrigin: function ( value ) { + get: function ( file ) { - this.crossOrigin = value; + var handlers = this.handlers; - }, + for ( var i = 0, l = handlers.length; i < l; i += 2 ) { - parse: function ( json, onLoad ) { + var regex = handlers[ i ]; + var loader = handlers[ i + 1 ]; - var geometries = this.parseGeometries( json.geometries ); + if ( regex.test( file ) ) { - var images = this.parseImages( json.images, function () { + return loader; - if ( onLoad !== undefined ) onLoad( object ); + } - } ); + } - var textures = this.parseTextures( json.textures, images ); - var materials = this.parseMaterials( json.materials, textures ); + return null; - var object = this.parseObject( json.object, geometries, materials ); + } - if ( json.animations ) { + }; - object.animations = this.parseAnimations( json.animations ); + Object.assign( Loader.prototype, { - } + crossOrigin: undefined, - if ( json.images === undefined || json.images.length === 0 ) { + onLoadStart: function () {}, - if ( onLoad !== undefined ) onLoad( object ); + onLoadProgress: function () {}, - } + onLoadComplete: function () {}, - return object; + initMaterials: function ( materials, texturePath, crossOrigin ) { - }, + var array = []; - parseGeometries: function ( json ) { + for ( var i = 0; i < materials.length; ++ i ) { - var geometries = {}; + array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin ); - if ( json !== undefined ) { + } - var geometryLoader = new JSONLoader(); - var bufferGeometryLoader = new BufferGeometryLoader(); + return array; - for ( var i = 0, l = json.length; i < l; i ++ ) { + }, - var geometry; - var data = json[ i ]; + createMaterial: ( function () { - switch ( data.type ) { + var BlendingMode = { + NoBlending: NoBlending, + NormalBlending: NormalBlending, + AdditiveBlending: AdditiveBlending, + SubtractiveBlending: SubtractiveBlending, + MultiplyBlending: MultiplyBlending, + CustomBlending: CustomBlending + }; - case 'PlaneGeometry': - case 'PlaneBufferGeometry': + var color = new Color(); + var textureLoader = new TextureLoader(); + var materialLoader = new MaterialLoader(); - geometry = new Geometries[ data.type ]( - data.width, - data.height, - data.widthSegments, - data.heightSegments - ); + return function createMaterial( m, texturePath, crossOrigin ) { - break; + // convert from old material format - case 'BoxGeometry': - case 'BoxBufferGeometry': - case 'CubeGeometry': // backwards compatible + var textures = {}; - geometry = new Geometries[ data.type ]( - data.width, - data.height, - data.depth, - data.widthSegments, - data.heightSegments, - data.depthSegments - ); + function loadTexture( path, repeat, offset, wrap, anisotropy ) { - break; + var fullPath = texturePath + path; + var loader = Loader.Handlers.get( fullPath ); - case 'CircleGeometry': - case 'CircleBufferGeometry': + var texture; - geometry = new Geometries[ data.type ]( - data.radius, - data.segments, - data.thetaStart, - data.thetaLength - ); + if ( loader !== null ) { - break; + texture = loader.load( fullPath ); - case 'CylinderGeometry': - case 'CylinderBufferGeometry': + } else { - geometry = new Geometries[ data.type ]( - data.radiusTop, - data.radiusBottom, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + textureLoader.setCrossOrigin( crossOrigin ); + texture = textureLoader.load( fullPath ); - break; + } - case 'ConeGeometry': - case 'ConeBufferGeometry': + if ( repeat !== undefined ) { - geometry = new Geometries[ data.type ]( - data.radius, - data.height, - data.radialSegments, - data.heightSegments, - data.openEnded, - data.thetaStart, - data.thetaLength - ); + texture.repeat.fromArray( repeat ); - break; + if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping; + if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping; - case 'SphereGeometry': - case 'SphereBufferGeometry': + } - geometry = new Geometries[ data.type ]( - data.radius, - data.widthSegments, - data.heightSegments, - data.phiStart, - data.phiLength, - data.thetaStart, - data.thetaLength - ); + if ( offset !== undefined ) { - break; + texture.offset.fromArray( offset ); - case 'DodecahedronGeometry': - case 'IcosahedronGeometry': - case 'OctahedronGeometry': - case 'TetrahedronGeometry': + } - geometry = new Geometries[ data.type ]( - data.radius, - data.detail - ); + if ( wrap !== undefined ) { - break; + if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping; + if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping; - case 'RingGeometry': - case 'RingBufferGeometry': + if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping; + if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping; - geometry = new Geometries[ data.type ]( - data.innerRadius, - data.outerRadius, - data.thetaSegments, - data.phiSegments, - data.thetaStart, - data.thetaLength - ); + } - break; + if ( anisotropy !== undefined ) { - case 'TorusGeometry': - case 'TorusBufferGeometry': + texture.anisotropy = anisotropy; - geometry = new Geometries[ data.type ]( - data.radius, - data.tube, - data.radialSegments, - data.tubularSegments, - data.arc - ); + } - break; + var uuid = _Math.generateUUID(); - case 'TorusKnotGeometry': - case 'TorusKnotBufferGeometry': + textures[ uuid ] = texture; - geometry = new Geometries[ data.type ]( - data.radius, - data.tube, - data.tubularSegments, - data.radialSegments, - data.p, - data.q - ); + return uuid; - break; + } - case 'LatheGeometry': - case 'LatheBufferGeometry': + // - geometry = new Geometries[ data.type ]( - data.points, - data.segments, - data.phiStart, - data.phiLength - ); + var json = { + uuid: _Math.generateUUID(), + type: 'MeshLambertMaterial' + }; - break; + for ( var name in m ) { - case 'BufferGeometry': + var value = m[ name ]; - geometry = bufferGeometryLoader.parse( data ); + switch ( name ) { + case 'DbgColor': + case 'DbgIndex': + case 'opticalDensity': + case 'illumination': break; - - case 'Geometry': - - geometry = geometryLoader.parse( data, this.texturePath ).geometry; - + case 'DbgName': + json.name = value; + break; + case 'blending': + json.blending = BlendingMode[ value ]; + break; + case 'colorAmbient': + case 'mapAmbient': + console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' ); + break; + case 'colorDiffuse': + json.color = color.fromArray( value ).getHex(); + break; + case 'colorSpecular': + json.specular = color.fromArray( value ).getHex(); + break; + case 'colorEmissive': + json.emissive = color.fromArray( value ).getHex(); + break; + case 'specularCoef': + json.shininess = value; + break; + case 'shading': + if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial'; + if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial'; + if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial'; + break; + case 'mapDiffuse': + json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy ); + break; + case 'mapDiffuseRepeat': + case 'mapDiffuseOffset': + case 'mapDiffuseWrap': + case 'mapDiffuseAnisotropy': + break; + case 'mapEmissive': + json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy ); + break; + case 'mapEmissiveRepeat': + case 'mapEmissiveOffset': + case 'mapEmissiveWrap': + case 'mapEmissiveAnisotropy': + break; + case 'mapLight': + json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy ); + break; + case 'mapLightRepeat': + case 'mapLightOffset': + case 'mapLightWrap': + case 'mapLightAnisotropy': + break; + case 'mapAO': + json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy ); + break; + case 'mapAORepeat': + case 'mapAOOffset': + case 'mapAOWrap': + case 'mapAOAnisotropy': + break; + case 'mapBump': + json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy ); + break; + case 'mapBumpScale': + json.bumpScale = value; + break; + case 'mapBumpRepeat': + case 'mapBumpOffset': + case 'mapBumpWrap': + case 'mapBumpAnisotropy': + break; + case 'mapNormal': + json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy ); + break; + case 'mapNormalFactor': + json.normalScale = value; + break; + case 'mapNormalRepeat': + case 'mapNormalOffset': + case 'mapNormalWrap': + case 'mapNormalAnisotropy': + break; + case 'mapSpecular': + json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy ); + break; + case 'mapSpecularRepeat': + case 'mapSpecularOffset': + case 'mapSpecularWrap': + case 'mapSpecularAnisotropy': + break; + case 'mapMetalness': + json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy ); + break; + case 'mapMetalnessRepeat': + case 'mapMetalnessOffset': + case 'mapMetalnessWrap': + case 'mapMetalnessAnisotropy': + break; + case 'mapRoughness': + json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy ); + break; + case 'mapRoughnessRepeat': + case 'mapRoughnessOffset': + case 'mapRoughnessWrap': + case 'mapRoughnessAnisotropy': + break; + case 'mapAlpha': + json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy ); + break; + case 'mapAlphaRepeat': + case 'mapAlphaOffset': + case 'mapAlphaWrap': + case 'mapAlphaAnisotropy': + break; + case 'flipSided': + json.side = BackSide; + break; + case 'doubleSided': + json.side = DoubleSide; + break; + case 'transparency': + console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' ); + json.opacity = value; + break; + case 'depthTest': + case 'depthWrite': + case 'colorWrite': + case 'opacity': + case 'reflectivity': + case 'transparent': + case 'visible': + case 'wireframe': + json[ name ] = value; + break; + case 'vertexColors': + if ( value === true ) json.vertexColors = VertexColors; + if ( value === 'face' ) json.vertexColors = FaceColors; break; - default: - - console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); - - continue; + console.error( 'THREE.Loader.createMaterial: Unsupported', name, value ); + break; } - geometry.uuid = data.uuid; - - if ( data.name !== undefined ) geometry.name = data.name; - - geometries[ data.uuid ] = geometry; - } - } - - return geometries; - - }, - - parseMaterials: function ( json, textures ) { + if ( json.type === 'MeshBasicMaterial' ) delete json.emissive; + if ( json.type !== 'MeshPhongMaterial' ) delete json.specular; - var materials = {}; + if ( json.opacity < 1 ) json.transparent = true; - if ( json !== undefined ) { + materialLoader.setTextures( textures ); - var loader = new MaterialLoader(); - loader.setTextures( textures ); + return materialLoader.parse( json ); - for ( var i = 0, l = json.length; i < l; i ++ ) { + }; - var data = json[ i ]; + } )() - if ( data.type === 'MultiMaterial' ) { + } ); - // Deprecated + /** + * @author Don McCurdy / https://www.donmccurdy.com + */ - var array = []; + var LoaderUtils = { - for ( var j = 0; j < data.materials.length; j ++ ) { + decodeText: function ( array ) { - array.push( loader.parse( data.materials[ j ] ) ); + if ( typeof TextDecoder !== 'undefined' ) { - } + return new TextDecoder().decode( array ); - materials[ data.uuid ] = array; + } - } else { + // Avoid the String.fromCharCode.apply(null, array) shortcut, which + // throws a "maximum call stack size exceeded" error for large arrays. - materials[ data.uuid ] = loader.parse( data ); + var s = ''; - } + for ( var i = 0, il = array.length; i < il; i ++ ) { - } + // Implicitly assumes little-endian. + s += String.fromCharCode( array[ i ] ); } - return materials; + // Merges multi-byte utf-8 characters. + return decodeURIComponent( escape( s ) ); }, - parseAnimations: function ( json ) { - - var animations = []; - - for ( var i = 0; i < json.length; i ++ ) { - - var clip = AnimationClip.parse( json[ i ] ); + extractUrlBase: function ( url ) { - animations.push( clip ); + var parts = url.split( '/' ); - } + if ( parts.length === 1 ) return './'; - return animations; + parts.pop(); - }, + return parts.join( '/' ) + '/'; - parseImages: function ( json, onLoad ) { + } - var scope = this; - var images = {}; + }; - function loadImage( url ) { + /** + * @author mrdoob / http://mrdoob.com/ + * @author alteredq / http://alteredqualia.com/ + */ - scope.manager.itemStart( url ); + function JSONLoader( manager ) { - return loader.load( url, function () { + if ( typeof manager === 'boolean' ) { - scope.manager.itemEnd( url ); + console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' ); + manager = undefined; - }, undefined, function () { + } - scope.manager.itemEnd( url ); - scope.manager.itemError( url ); + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; - } ); + this.withCredentials = false; - } + } - if ( json !== undefined && json.length > 0 ) { + Object.assign( JSONLoader.prototype, { - var manager = new LoadingManager( onLoad ); + load: function ( url, onLoad, onProgress, onError ) { - var loader = new ImageLoader( manager ); - loader.setCrossOrigin( this.crossOrigin ); + var scope = this; - for ( var i = 0, l = json.length; i < l; i ++ ) { + var texturePath = this.texturePath && ( typeof this.texturePath === 'string' ) ? this.texturePath : LoaderUtils.extractUrlBase( url ); - var image = json[ i ]; - var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url; + var loader = new FileLoader( this.manager ); + loader.setWithCredentials( this.withCredentials ); + loader.load( url, function ( text ) { - images[ image.uuid ] = loadImage( path ); + var json = JSON.parse( text ); + var metadata = json.metadata; - } + if ( metadata !== undefined ) { - } + var type = metadata.type; - return images; + if ( type !== undefined ) { - }, + if ( type.toLowerCase() === 'object' ) { - parseTextures: function ( json, images ) { + console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' ); + return; - function parseConstant( value, type ) { + } - if ( typeof( value ) === 'number' ) return value; + } - console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); + } - return type[ value ]; + var object = scope.parse( json, texturePath ); + onLoad( object.geometry, object.materials ); - } + }, onProgress, onError ); - var textures = {}; + }, - if ( json !== undefined ) { + setTexturePath: function ( value ) { - for ( var i = 0, l = json.length; i < l; i ++ ) { + this.texturePath = value; - var data = json[ i ]; + }, - if ( data.image === undefined ) { + parse: ( function () { - console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); + function parseModel( json, geometry ) { - } + function isBitSet( value, position ) { - if ( images[ data.image ] === undefined ) { + return value & ( 1 << position ); - console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); + } - } + var i, j, fi, - var texture = new Texture( images[ data.image ] ); - texture.needsUpdate = true; + offset, zLength, - texture.uuid = data.uuid; + colorIndex, normalIndex, uvIndex, materialIndex, - if ( data.name !== undefined ) texture.name = data.name; + type, + isQuad, + hasMaterial, + hasFaceVertexUv, + hasFaceNormal, hasFaceVertexNormal, + hasFaceColor, hasFaceVertexColor, - if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); + vertex, face, faceA, faceB, hex, normal, - if ( data.offset !== undefined ) texture.offset.fromArray( data.offset ); - if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat ); - if ( data.wrap !== undefined ) { + uvLayer, uv, u, v, - texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING ); - texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING ); + faces = json.faces, + vertices = json.vertices, + normals = json.normals, + colors = json.colors, - } + scale = json.scale, - if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); - if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); - if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy; + nUvLayers = 0; - if ( data.flipY !== undefined ) texture.flipY = data.flipY; - textures[ data.uuid ] = texture; + if ( json.uvs !== undefined ) { - } + // disregard empty arrays - } + for ( i = 0; i < json.uvs.length; i ++ ) { - return textures; + if ( json.uvs[ i ].length ) nUvLayers ++; - }, + } - parseObject: function () { + for ( i = 0; i < nUvLayers; i ++ ) { - var matrix = new Matrix4(); + geometry.faceVertexUvs[ i ] = []; - return function parseObject( data, geometries, materials ) { + } - var object; + } - function getGeometry( name ) { + offset = 0; + zLength = vertices.length; - if ( geometries[ name ] === undefined ) { + while ( offset < zLength ) { - console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); + vertex = new Vector3(); - } + vertex.x = vertices[ offset ++ ] * scale; + vertex.y = vertices[ offset ++ ] * scale; + vertex.z = vertices[ offset ++ ] * scale; - return geometries[ name ]; + geometry.vertices.push( vertex ); } - function getMaterial( name ) { + offset = 0; + zLength = faces.length; - if ( name === undefined ) return undefined; + while ( offset < zLength ) { - if ( Array.isArray( name ) ) { + type = faces[ offset ++ ]; - var array = []; + isQuad = isBitSet( type, 0 ); + hasMaterial = isBitSet( type, 1 ); + hasFaceVertexUv = isBitSet( type, 3 ); + hasFaceNormal = isBitSet( type, 4 ); + hasFaceVertexNormal = isBitSet( type, 5 ); + hasFaceColor = isBitSet( type, 6 ); + hasFaceVertexColor = isBitSet( type, 7 ); - for ( var i = 0, l = name.length; i < l; i ++ ) { + // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor); - var uuid = name[ i ]; + if ( isQuad ) { - if ( materials[ uuid ] === undefined ) { + faceA = new Face3(); + faceA.a = faces[ offset ]; + faceA.b = faces[ offset + 1 ]; + faceA.c = faces[ offset + 3 ]; - console.warn( 'THREE.ObjectLoader: Undefined material', uuid ); + faceB = new Face3(); + faceB.a = faces[ offset + 1 ]; + faceB.b = faces[ offset + 2 ]; + faceB.c = faces[ offset + 3 ]; - } + offset += 4; - array.push( materials[ uuid ] ); + if ( hasMaterial ) { - } + materialIndex = faces[ offset ++ ]; + faceA.materialIndex = materialIndex; + faceB.materialIndex = materialIndex; - return array; + } - } + // to get face <=> uv index correspondence - if ( materials[ name ] === undefined ) { + fi = geometry.faces.length; - console.warn( 'THREE.ObjectLoader: Undefined material', name ); + if ( hasFaceVertexUv ) { - } + for ( i = 0; i < nUvLayers; i ++ ) { - return materials[ name ]; + uvLayer = json.uvs[ i ]; - } + geometry.faceVertexUvs[ i ][ fi ] = []; + geometry.faceVertexUvs[ i ][ fi + 1 ] = []; - switch ( data.type ) { + for ( j = 0; j < 4; j ++ ) { - case 'Scene': + uvIndex = faces[ offset ++ ]; - object = new Scene(); + u = uvLayer[ uvIndex * 2 ]; + v = uvLayer[ uvIndex * 2 + 1 ]; - if ( data.background !== undefined ) { + uv = new Vector2( u, v ); - if ( Number.isInteger( data.background ) ) { + if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv ); + if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv ); - object.background = new Color( data.background ); + } } } - if ( data.fog !== undefined ) { - - if ( data.fog.type === 'Fog' ) { - - object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far ); + if ( hasFaceNormal ) { - } else if ( data.fog.type === 'FogExp2' ) { + normalIndex = faces[ offset ++ ] * 3; - object.fog = new FogExp2( data.fog.color, data.fog.density ); + faceA.normal.set( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - } + faceB.normal.copy( faceA.normal ); } - break; - - case 'PerspectiveCamera': - - object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); + if ( hasFaceVertexNormal ) { - if ( data.focus !== undefined ) object.focus = data.focus; - if ( data.zoom !== undefined ) object.zoom = data.zoom; - if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge; - if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset; - if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); + for ( i = 0; i < 4; i ++ ) { - break; + normalIndex = faces[ offset ++ ] * 3; - case 'OrthographicCamera': + normal = new Vector3( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); - break; + if ( i !== 2 ) faceA.vertexNormals.push( normal ); + if ( i !== 0 ) faceB.vertexNormals.push( normal ); - case 'AmbientLight': + } - object = new AmbientLight( data.color, data.intensity ); + } - break; - case 'DirectionalLight': + if ( hasFaceColor ) { - object = new DirectionalLight( data.color, data.intensity ); + colorIndex = faces[ offset ++ ]; + hex = colors[ colorIndex ]; - break; + faceA.color.setHex( hex ); + faceB.color.setHex( hex ); - case 'PointLight': + } - object = new PointLight( data.color, data.intensity, data.distance, data.decay ); - break; + if ( hasFaceVertexColor ) { - case 'RectAreaLight': + for ( i = 0; i < 4; i ++ ) { - object = new RectAreaLight( data.color, data.intensity, data.width, data.height ); + colorIndex = faces[ offset ++ ]; + hex = colors[ colorIndex ]; - break; + if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) ); + if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) ); - case 'SpotLight': + } - object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); + } - break; + geometry.faces.push( faceA ); + geometry.faces.push( faceB ); - case 'HemisphereLight': + } else { - object = new HemisphereLight( data.color, data.groundColor, data.intensity ); + face = new Face3(); + face.a = faces[ offset ++ ]; + face.b = faces[ offset ++ ]; + face.c = faces[ offset ++ ]; - break; + if ( hasMaterial ) { - case 'SkinnedMesh': + materialIndex = faces[ offset ++ ]; + face.materialIndex = materialIndex; - console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' ); + } - case 'Mesh': + // to get face <=> uv index correspondence - var geometry = getGeometry( data.geometry ); - var material = getMaterial( data.material ); + fi = geometry.faces.length; - if ( geometry.bones && geometry.bones.length > 0 ) { + if ( hasFaceVertexUv ) { - object = new SkinnedMesh( geometry, material ); + for ( i = 0; i < nUvLayers; i ++ ) { - } else { + uvLayer = json.uvs[ i ]; - object = new Mesh( geometry, material ); + geometry.faceVertexUvs[ i ][ fi ] = []; - } + for ( j = 0; j < 3; j ++ ) { - break; + uvIndex = faces[ offset ++ ]; - case 'LOD': + u = uvLayer[ uvIndex * 2 ]; + v = uvLayer[ uvIndex * 2 + 1 ]; - object = new LOD(); + uv = new Vector2( u, v ); - break; + geometry.faceVertexUvs[ i ][ fi ].push( uv ); - case 'Line': + } - object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); + } - break; + } - case 'LineLoop': + if ( hasFaceNormal ) { - object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) ); + normalIndex = faces[ offset ++ ] * 3; - break; + face.normal.set( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - case 'LineSegments': + } - object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); + if ( hasFaceVertexNormal ) { - break; + for ( i = 0; i < 3; i ++ ) { - case 'PointCloud': - case 'Points': + normalIndex = faces[ offset ++ ] * 3; - object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); + normal = new Vector3( + normals[ normalIndex ++ ], + normals[ normalIndex ++ ], + normals[ normalIndex ] + ); - break; + face.vertexNormals.push( normal ); - case 'Sprite': + } - object = new Sprite( getMaterial( data.material ) ); + } - break; - case 'Group': + if ( hasFaceColor ) { - object = new Group(); + colorIndex = faces[ offset ++ ]; + face.color.setHex( colors[ colorIndex ] ); - break; + } - default: - object = new Object3D(); + if ( hasFaceVertexColor ) { - } + for ( i = 0; i < 3; i ++ ) { - object.uuid = data.uuid; + colorIndex = faces[ offset ++ ]; + face.vertexColors.push( new Color( colors[ colorIndex ] ) ); - if ( data.name !== undefined ) object.name = data.name; - if ( data.matrix !== undefined ) { + } - matrix.fromArray( data.matrix ); - matrix.decompose( object.position, object.quaternion, object.scale ); + } - } else { + geometry.faces.push( face ); - if ( data.position !== undefined ) object.position.fromArray( data.position ); - if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); - if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion ); - if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); + } } - if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; - if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; - - if ( data.shadow ) { + } - if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias; - if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius; - if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize ); - if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera ); + function parseSkin( json, geometry ) { - } + var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2; - if ( data.visible !== undefined ) object.visible = data.visible; - if ( data.userData !== undefined ) object.userData = data.userData; + if ( json.skinWeights ) { - if ( data.children !== undefined ) { + for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) { - for ( var child in data.children ) { + var x = json.skinWeights[ i ]; + var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0; + var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0; + var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0; - object.add( this.parseObject( data.children[ child ], geometries, materials ) ); + geometry.skinWeights.push( new Vector4( x, y, z, w ) ); } } - if ( data.type === 'LOD' ) { + if ( json.skinIndices ) { + + for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) { - var levels = data.levels; + var a = json.skinIndices[ i ]; + var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0; + var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0; + var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0; - for ( var l = 0; l < levels.length; l ++ ) { + geometry.skinIndices.push( new Vector4( a, b, c, d ) ); - var level = levels[ l ]; - var child = object.getObjectByProperty( 'uuid', level.object ); + } - if ( child !== undefined ) { + } - object.addLevel( child, level.distance ); + geometry.bones = json.bones; - } + if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) { - } + console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' + + geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' ); } - return object; + } - }; + function parseMorphing( json, geometry ) { - }() + var scale = json.scale; - } ); + if ( json.morphTargets !== undefined ) { - var TEXTURE_MAPPING = { - UVMapping: UVMapping, - CubeReflectionMapping: CubeReflectionMapping, - CubeRefractionMapping: CubeRefractionMapping, - EquirectangularReflectionMapping: EquirectangularReflectionMapping, - EquirectangularRefractionMapping: EquirectangularRefractionMapping, - SphericalReflectionMapping: SphericalReflectionMapping, - CubeUVReflectionMapping: CubeUVReflectionMapping, - CubeUVRefractionMapping: CubeUVRefractionMapping - }; + for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) { - var TEXTURE_WRAPPING = { - RepeatWrapping: RepeatWrapping, - ClampToEdgeWrapping: ClampToEdgeWrapping, - MirroredRepeatWrapping: MirroredRepeatWrapping - }; + geometry.morphTargets[ i ] = {}; + geometry.morphTargets[ i ].name = json.morphTargets[ i ].name; + geometry.morphTargets[ i ].vertices = []; - var TEXTURE_FILTER = { - NearestFilter: NearestFilter, - NearestMipMapNearestFilter: NearestMipMapNearestFilter, - NearestMipMapLinearFilter: NearestMipMapLinearFilter, - LinearFilter: LinearFilter, - LinearMipMapNearestFilter: LinearMipMapNearestFilter, - LinearMipMapLinearFilter: LinearMipMapLinearFilter - }; + var dstVertices = geometry.morphTargets[ i ].vertices; + var srcVertices = json.morphTargets[ i ].vertices; - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - * Bezier Curves formulas obtained from - * http://en.wikipedia.org/wiki/Bézier_curve - */ + for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) { - function CatmullRom( t, p0, p1, p2, p3 ) { + var vertex = new Vector3(); + vertex.x = srcVertices[ v ] * scale; + vertex.y = srcVertices[ v + 1 ] * scale; + vertex.z = srcVertices[ v + 2 ] * scale; - var v0 = ( p2 - p0 ) * 0.5; - var v1 = ( p3 - p1 ) * 0.5; - var t2 = t * t; - var t3 = t * t2; - return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; + dstVertices.push( vertex ); - } + } - // + } - function QuadraticBezierP0( t, p ) { + } - var k = 1 - t; - return k * k * p; + if ( json.morphColors !== undefined && json.morphColors.length > 0 ) { - } + console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' ); - function QuadraticBezierP1( t, p ) { + var faces = geometry.faces; + var morphColors = json.morphColors[ 0 ].colors; - return 2 * ( 1 - t ) * t * p; + for ( var i = 0, l = faces.length; i < l; i ++ ) { - } + faces[ i ].color.fromArray( morphColors, i * 3 ); - function QuadraticBezierP2( t, p ) { + } - return t * t * p; + } - } + } - function QuadraticBezier( t, p0, p1, p2 ) { + function parseAnimations( json, geometry ) { - return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) + - QuadraticBezierP2( t, p2 ); + var outputAnimations = []; - } + // parse old style Bone/Hierarchy animations + var animations = []; - // + if ( json.animation !== undefined ) { - function CubicBezierP0( t, p ) { + animations.push( json.animation ); - var k = 1 - t; - return k * k * k * p; + } - } + if ( json.animations !== undefined ) { - function CubicBezierP1( t, p ) { + if ( json.animations.length ) { - var k = 1 - t; - return 3 * k * k * t * p; + animations = animations.concat( json.animations ); - } + } else { - function CubicBezierP2( t, p ) { + animations.push( json.animations ); - return 3 * ( 1 - t ) * t * t * p; + } - } + } - function CubicBezierP3( t, p ) { + for ( var i = 0; i < animations.length; i ++ ) { - return t * t * t * p; + var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones ); + if ( clip ) outputAnimations.push( clip ); - } + } - function CubicBezier( t, p0, p1, p2, p3 ) { + // parse implicit morph animations + if ( geometry.morphTargets ) { - return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) + - CubicBezierP3( t, p3 ); + // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary. + var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 ); + outputAnimations = outputAnimations.concat( morphAnimationClips ); - } + } - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Extensible curve object - * - * Some common of curve methods: - * .getPoint(t), getTangent(t) - * .getPointAt(u), getTangentAt(u) - * .getPoints(), .getSpacedPoints() - * .getLength() - * .updateArcLengths() - * - * This following curves inherit from THREE.Curve: - * - * -- 2D curves -- - * THREE.ArcCurve - * THREE.CubicBezierCurve - * THREE.EllipseCurve - * THREE.LineCurve - * THREE.QuadraticBezierCurve - * THREE.SplineCurve - * - * -- 3D curves -- - * THREE.CatmullRomCurve3 - * THREE.CubicBezierCurve3 - * THREE.LineCurve3 - * THREE.QuadraticBezierCurve3 - * - * A series of curves can be represented as a THREE.CurvePath. - * - **/ + if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations; - /************************************************************** - * Abstract Curve base class - **************************************************************/ + } - function Curve() { + return function parse( json, texturePath ) { - this.arcLengthDivisions = 200; + if ( json.data !== undefined ) { - } + // Geometry 4.0 spec + json = json.data; - Object.assign( Curve.prototype, { + } - // Virtual base class method to overwrite and implement in subclasses - // - t [0 .. 1] + if ( json.scale !== undefined ) { - getPoint: function () { + json.scale = 1.0 / json.scale; - console.warn( 'THREE.Curve: .getPoint() not implemented.' ); - return null; + } else { - }, + json.scale = 1.0; - // Get point at relative position in curve according to arc length - // - u [0 .. 1] + } - getPointAt: function ( u ) { + var geometry = new Geometry(); - var t = this.getUtoTmapping( u ); - return this.getPoint( t ); + parseModel( json, geometry ); + parseSkin( json, geometry ); + parseMorphing( json, geometry ); + parseAnimations( json, geometry ); - }, + geometry.computeFaceNormals(); + geometry.computeBoundingSphere(); - // Get sequence of points using getPoint( t ) + if ( json.materials === undefined || json.materials.length === 0 ) { - getPoints: function ( divisions ) { + return { geometry: geometry }; - if ( divisions === undefined ) divisions = 5; + } else { - var points = []; + var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin ); - for ( var d = 0; d <= divisions; d ++ ) { + return { geometry: geometry, materials: materials }; - points.push( this.getPoint( d / divisions ) ); + } - } + }; - return points; + } )() - }, + } ); - // Get sequence of points using getPointAt( u ) + /** + * @author mrdoob / http://mrdoob.com/ + */ - getSpacedPoints: function ( divisions ) { + function ObjectLoader( manager ) { - if ( divisions === undefined ) divisions = 5; + this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; + this.texturePath = ''; - var points = []; + } - for ( var d = 0; d <= divisions; d ++ ) { + Object.assign( ObjectLoader.prototype, { - points.push( this.getPointAt( d / divisions ) ); + load: function ( url, onLoad, onProgress, onError ) { - } + if ( this.texturePath === '' ) { - return points; + this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 ); - }, + } - // Get total curve arc length + var scope = this; - getLength: function () { + var loader = new FileLoader( scope.manager ); + loader.load( url, function ( text ) { - var lengths = this.getLengths(); - return lengths[ lengths.length - 1 ]; + var json = null; - }, + try { - // Get list of cumulative segment lengths + json = JSON.parse( text ); - getLengths: function ( divisions ) { + } catch ( error ) { - if ( divisions === undefined ) divisions = this.arcLengthDivisions; + if ( onError !== undefined ) onError( error ); - if ( this.cacheArcLengths && - ( this.cacheArcLengths.length === divisions + 1 ) && - ! this.needsUpdate ) { + console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message ); - return this.cacheArcLengths; + return; - } + } - this.needsUpdate = false; + var metadata = json.metadata; - var cache = []; - var current, last = this.getPoint( 0 ); - var p, sum = 0; + if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { - cache.push( 0 ); + console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' ); + return; - for ( p = 1; p <= divisions; p ++ ) { + } - current = this.getPoint( p / divisions ); - sum += current.distanceTo( last ); - cache.push( sum ); - last = current; + scope.parse( json, onLoad ); - } + }, onProgress, onError ); - this.cacheArcLengths = cache; + }, - return cache; // { sums: cache, sum: sum }; Sum is in the last element. + setTexturePath: function ( value ) { + + this.texturePath = value; }, - updateArcLengths: function () { + setCrossOrigin: function ( value ) { - this.needsUpdate = true; - this.getLengths(); + this.crossOrigin = value; }, - // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + parse: function ( json, onLoad ) { - getUtoTmapping: function ( u, distance ) { + var shapes = this.parseShape( json.shapes ); + var geometries = this.parseGeometries( json.geometries, shapes ); - var arcLengths = this.getLengths(); + var images = this.parseImages( json.images, function () { - var i = 0, il = arcLengths.length; + if ( onLoad !== undefined ) onLoad( object ); - var targetArcLength; // The targeted u distance value to get + } ); - if ( distance ) { + var textures = this.parseTextures( json.textures, images ); + var materials = this.parseMaterials( json.materials, textures ); - targetArcLength = distance; + var object = this.parseObject( json.object, geometries, materials ); - } else { + if ( json.animations ) { - targetArcLength = u * arcLengths[ il - 1 ]; + object.animations = this.parseAnimations( json.animations ); } - // binary search for the index with largest value smaller than target u distance - - var low = 0, high = il - 1, comparison; + if ( json.images === undefined || json.images.length === 0 ) { - while ( low <= high ) { + if ( onLoad !== undefined ) onLoad( object ); - i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats + } - comparison = arcLengths[ i ] - targetArcLength; + return object; - if ( comparison < 0 ) { + }, - low = i + 1; + parseShape: function ( json ) { - } else if ( comparison > 0 ) { + var shapes = {}; - high = i - 1; + if ( json !== undefined ) { - } else { + for ( var i = 0, l = json.length; i < l; i ++ ) { - high = i; - break; + var shape = new Shape().fromJSON( json[ i ] ); - // DONE + shapes[ shape.uuid ] = shape; } } - i = high; - - if ( arcLengths[ i ] === targetArcLength ) { - - return i / ( il - 1 ); - - } + return shapes; - // we could get finer grain at lengths, or use simple interpolation between two points + }, - var lengthBefore = arcLengths[ i ]; - var lengthAfter = arcLengths[ i + 1 ]; + parseGeometries: function ( json, shapes ) { - var segmentLength = lengthAfter - lengthBefore; + var geometries = {}; - // determine where we are between the 'before' and 'after' points + if ( json !== undefined ) { - var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; + var geometryLoader = new JSONLoader(); + var bufferGeometryLoader = new BufferGeometryLoader(); - // add that fractional amount to t + for ( var i = 0, l = json.length; i < l; i ++ ) { - var t = ( i + segmentFraction ) / ( il - 1 ); + var geometry; + var data = json[ i ]; - return t; + switch ( data.type ) { - }, + case 'PlaneGeometry': + case 'PlaneBufferGeometry': - // Returns a unit vector tangent at t - // In case any sub curve does not implement its tangent derivation, - // 2 points a small delta apart will be used to find its gradient - // which seems to give a reasonable approximation + geometry = new Geometries[ data.type ]( + data.width, + data.height, + data.widthSegments, + data.heightSegments + ); - getTangent: function ( t ) { + break; - var delta = 0.0001; - var t1 = t - delta; - var t2 = t + delta; + case 'BoxGeometry': + case 'BoxBufferGeometry': + case 'CubeGeometry': // backwards compatible - // Capping in case of danger + geometry = new Geometries[ data.type ]( + data.width, + data.height, + data.depth, + data.widthSegments, + data.heightSegments, + data.depthSegments + ); - if ( t1 < 0 ) t1 = 0; - if ( t2 > 1 ) t2 = 1; + break; - var pt1 = this.getPoint( t1 ); - var pt2 = this.getPoint( t2 ); + case 'CircleGeometry': + case 'CircleBufferGeometry': - var vec = pt2.clone().sub( pt1 ); - return vec.normalize(); + geometry = new Geometries[ data.type ]( + data.radius, + data.segments, + data.thetaStart, + data.thetaLength + ); - }, + break; - getTangentAt: function ( u ) { + case 'CylinderGeometry': + case 'CylinderBufferGeometry': - var t = this.getUtoTmapping( u ); - return this.getTangent( t ); + geometry = new Geometries[ data.type ]( + data.radiusTop, + data.radiusBottom, + data.height, + data.radialSegments, + data.heightSegments, + data.openEnded, + data.thetaStart, + data.thetaLength + ); - }, + break; - computeFrenetFrames: function ( segments, closed ) { + case 'ConeGeometry': + case 'ConeBufferGeometry': - // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf + geometry = new Geometries[ data.type ]( + data.radius, + data.height, + data.radialSegments, + data.heightSegments, + data.openEnded, + data.thetaStart, + data.thetaLength + ); - var normal = new Vector3(); + break; - var tangents = []; - var normals = []; - var binormals = []; + case 'SphereGeometry': + case 'SphereBufferGeometry': - var vec = new Vector3(); - var mat = new Matrix4(); + geometry = new Geometries[ data.type ]( + data.radius, + data.widthSegments, + data.heightSegments, + data.phiStart, + data.phiLength, + data.thetaStart, + data.thetaLength + ); - var i, u, theta; + break; - // compute the tangent vectors for each segment on the curve + case 'DodecahedronGeometry': + case 'DodecahedronBufferGeometry': + case 'IcosahedronGeometry': + case 'IcosahedronBufferGeometry': + case 'OctahedronGeometry': + case 'OctahedronBufferGeometry': + case 'TetrahedronGeometry': + case 'TetrahedronBufferGeometry': - for ( i = 0; i <= segments; i ++ ) { + geometry = new Geometries[ data.type ]( + data.radius, + data.detail + ); - u = i / segments; + break; - tangents[ i ] = this.getTangentAt( u ); - tangents[ i ].normalize(); + case 'RingGeometry': + case 'RingBufferGeometry': - } + geometry = new Geometries[ data.type ]( + data.innerRadius, + data.outerRadius, + data.thetaSegments, + data.phiSegments, + data.thetaStart, + data.thetaLength + ); - // select an initial normal vector perpendicular to the first tangent vector, - // and in the direction of the minimum tangent xyz component + break; - normals[ 0 ] = new Vector3(); - binormals[ 0 ] = new Vector3(); - var min = Number.MAX_VALUE; - var tx = Math.abs( tangents[ 0 ].x ); - var ty = Math.abs( tangents[ 0 ].y ); - var tz = Math.abs( tangents[ 0 ].z ); + case 'TorusGeometry': + case 'TorusBufferGeometry': - if ( tx <= min ) { + geometry = new Geometries[ data.type ]( + data.radius, + data.tube, + data.radialSegments, + data.tubularSegments, + data.arc + ); - min = tx; - normal.set( 1, 0, 0 ); + break; - } + case 'TorusKnotGeometry': + case 'TorusKnotBufferGeometry': - if ( ty <= min ) { + geometry = new Geometries[ data.type ]( + data.radius, + data.tube, + data.tubularSegments, + data.radialSegments, + data.p, + data.q + ); - min = ty; - normal.set( 0, 1, 0 ); + break; - } + case 'LatheGeometry': + case 'LatheBufferGeometry': - if ( tz <= min ) { + geometry = new Geometries[ data.type ]( + data.points, + data.segments, + data.phiStart, + data.phiLength + ); - normal.set( 0, 0, 1 ); + break; - } + case 'PolyhedronGeometry': + case 'PolyhedronBufferGeometry': - vec.crossVectors( tangents[ 0 ], normal ).normalize(); + geometry = new Geometries[ data.type ]( + data.vertices, + data.indices, + data.radius, + data.details + ); - normals[ 0 ].crossVectors( tangents[ 0 ], vec ); - binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); + break; + case 'ShapeGeometry': + case 'ShapeBufferGeometry': - // compute the slowly-varying normal and binormal vectors for each segment on the curve + var geometryShapes = []; - for ( i = 1; i <= segments; i ++ ) { + for ( var i = 0, l = data.shapes.length; i < l; i ++ ) { - normals[ i ] = normals[ i - 1 ].clone(); + var shape = shapes[ data.shapes[ i ] ]; - binormals[ i ] = binormals[ i - 1 ].clone(); + geometryShapes.push( shape ); - vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); + } - if ( vec.length() > Number.EPSILON ) { + geometry = new Geometries[ data.type ]( + geometryShapes, + data.curveSegments + ); - vec.normalize(); + break; - theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors + case 'BufferGeometry': - normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); + geometry = bufferGeometryLoader.parse( data ); - } + break; - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + case 'Geometry': - } + geometry = geometryLoader.parse( data, this.texturePath ).geometry; - // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same + break; - if ( closed === true ) { + default: - theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) ); - theta /= segments; + console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); - if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) { + continue; - theta = - theta; + } - } + geometry.uuid = data.uuid; - for ( i = 1; i <= segments; i ++ ) { + if ( data.name !== undefined ) geometry.name = data.name; - // twist a little... - normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); - binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); + geometries[ data.uuid ] = geometry; } } - return { - tangents: tangents, - normals: normals, - binormals: binormals - }; - - } - - } ); - - function LineCurve( v1, v2 ) { - - Curve.call( this ); - - this.v1 = v1; - this.v2 = v2; - - } + return geometries; - LineCurve.prototype = Object.create( Curve.prototype ); - LineCurve.prototype.constructor = LineCurve; + }, - LineCurve.prototype.isLineCurve = true; + parseMaterials: function ( json, textures ) { - LineCurve.prototype.getPoint = function ( t ) { + var materials = {}; - if ( t === 1 ) { + if ( json !== undefined ) { - return this.v2.clone(); + var loader = new MaterialLoader(); + loader.setTextures( textures ); - } + for ( var i = 0, l = json.length; i < l; i ++ ) { - var point = this.v2.clone().sub( this.v1 ); - point.multiplyScalar( t ).add( this.v1 ); + var data = json[ i ]; - return point; + if ( data.type === 'MultiMaterial' ) { - }; + // Deprecated - // Line curve is linear, so we can overwrite default getPointAt + var array = []; - LineCurve.prototype.getPointAt = function ( u ) { + for ( var j = 0; j < data.materials.length; j ++ ) { - return this.getPoint( u ); + array.push( loader.parse( data.materials[ j ] ) ); - }; + } - LineCurve.prototype.getTangent = function ( t ) { + materials[ data.uuid ] = array; - var tangent = this.v2.clone().sub( this.v1 ); + } else { - return tangent.normalize(); + materials[ data.uuid ] = loader.parse( data ); - }; + } - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * - **/ + } - /************************************************************** - * Curved Path - a curve path is simply a array of connected - * curves, but retains the api of a curve - **************************************************************/ + } - function CurvePath() { + return materials; - Curve.call( this ); + }, - this.curves = []; + parseAnimations: function ( json ) { - this.autoClose = false; // Automatically closes the path + var animations = []; - } + for ( var i = 0; i < json.length; i ++ ) { - CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), { + var clip = AnimationClip.parse( json[ i ] ); - constructor: CurvePath, + animations.push( clip ); - add: function ( curve ) { + } - this.curves.push( curve ); + return animations; }, - closePath: function () { + parseImages: function ( json, onLoad ) { - // Add a line curve if start and end of lines are not connected - var startPoint = this.curves[ 0 ].getPoint( 0 ); - var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); + var scope = this; + var images = {}; - if ( ! startPoint.equals( endPoint ) ) { + function loadImage( url ) { - this.curves.push( new LineCurve( endPoint, startPoint ) ); + scope.manager.itemStart( url ); - } + return loader.load( url, function () { - }, + scope.manager.itemEnd( url ); - // To get accurate point with reference to - // entire path distance at time t, - // following has to be done: + }, undefined, function () { - // 1. Length of each sub path have to be known - // 2. Locate and identify type of curve - // 3. Get t for the curve - // 4. Return curve.getPointAt(t') + scope.manager.itemEnd( url ); + scope.manager.itemError( url ); - getPoint: function ( t ) { + } ); - var d = t * this.getLength(); - var curveLengths = this.getCurveLengths(); - var i = 0; + } - // To think about boundaries points. + if ( json !== undefined && json.length > 0 ) { - while ( i < curveLengths.length ) { + var manager = new LoadingManager( onLoad ); - if ( curveLengths[ i ] >= d ) { + var loader = new ImageLoader( manager ); + loader.setCrossOrigin( this.crossOrigin ); - var diff = curveLengths[ i ] - d; - var curve = this.curves[ i ]; + for ( var i = 0, l = json.length; i < l; i ++ ) { - var segmentLength = curve.getLength(); - var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + var image = json[ i ]; + var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url; - return curve.getPointAt( u ); + images[ image.uuid ] = loadImage( path ); } - i ++; - } - return null; - - // loop where sum != 0, sum > d , sum+1 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) { + var array = []; - points.push( points[ 0 ] ); + for ( var i = 0, l = name.length; i < l; i ++ ) { - } + var uuid = name[ i ]; - return points; + if ( materials[ uuid ] === undefined ) { - }, + console.warn( 'THREE.ObjectLoader: Undefined material', uuid ); - /************************************************************** - * Create Geometries Helpers - **************************************************************/ + } - /// Generate geometry from path points (for Line or Points objects) + array.push( materials[ uuid ] ); - createPointsGeometry: function ( divisions ) { + } - var pts = this.getPoints( divisions ); - return this.createGeometry( pts ); + return array; - }, + } - // Generate geometry from equidistant sampling along the path + if ( materials[ name ] === undefined ) { - createSpacedPointsGeometry: function ( divisions ) { + console.warn( 'THREE.ObjectLoader: Undefined material', name ); - var pts = this.getSpacedPoints( divisions ); - return this.createGeometry( pts ); + } - }, + return materials[ name ]; - createGeometry: function ( points ) { + } - var geometry = new Geometry(); + switch ( data.type ) { - for ( var i = 0, l = points.length; i < l; i ++ ) { + case 'Scene': - var point = points[ i ]; - geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); + object = new Scene(); - } + if ( data.background !== undefined ) { - return geometry; + if ( Number.isInteger( data.background ) ) { - } + object.background = new Color( data.background ); - } ); + } - function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + } - Curve.call( this ); + if ( data.fog !== undefined ) { - this.aX = aX; - this.aY = aY; + if ( data.fog.type === 'Fog' ) { - this.xRadius = xRadius; - this.yRadius = yRadius; + object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far ); - this.aStartAngle = aStartAngle; - this.aEndAngle = aEndAngle; + } else if ( data.fog.type === 'FogExp2' ) { - this.aClockwise = aClockwise; + object.fog = new FogExp2( data.fog.color, data.fog.density ); - this.aRotation = aRotation || 0; + } - } + } - EllipseCurve.prototype = Object.create( Curve.prototype ); - EllipseCurve.prototype.constructor = EllipseCurve; + break; - EllipseCurve.prototype.isEllipseCurve = true; + case 'PerspectiveCamera': - EllipseCurve.prototype.getPoint = function ( t ) { + object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); - var twoPi = Math.PI * 2; - var deltaAngle = this.aEndAngle - this.aStartAngle; - var samePoints = Math.abs( deltaAngle ) < Number.EPSILON; + if ( data.focus !== undefined ) object.focus = data.focus; + if ( data.zoom !== undefined ) object.zoom = data.zoom; + if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge; + if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset; + if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); - // ensures that deltaAngle is 0 .. 2 PI - while ( deltaAngle < 0 ) deltaAngle += twoPi; - while ( deltaAngle > twoPi ) deltaAngle -= twoPi; + break; - if ( deltaAngle < Number.EPSILON ) { + case 'OrthographicCamera': - if ( samePoints ) { + object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); - deltaAngle = 0; + if ( data.zoom !== undefined ) object.zoom = data.zoom; + if ( data.view !== undefined ) object.view = Object.assign( {}, data.view ); - } else { + break; - deltaAngle = twoPi; + case 'AmbientLight': - } + object = new AmbientLight( data.color, data.intensity ); - } + break; - if ( this.aClockwise === true && ! samePoints ) { + case 'DirectionalLight': - if ( deltaAngle === twoPi ) { + object = new DirectionalLight( data.color, data.intensity ); - deltaAngle = - twoPi; + break; - } else { + case 'PointLight': - deltaAngle = deltaAngle - twoPi; + object = new PointLight( data.color, data.intensity, data.distance, data.decay ); - } + break; - } + case 'RectAreaLight': - var angle = this.aStartAngle + t * deltaAngle; - var x = this.aX + this.xRadius * Math.cos( angle ); - var y = this.aY + this.yRadius * Math.sin( angle ); + object = new RectAreaLight( data.color, data.intensity, data.width, data.height ); - if ( this.aRotation !== 0 ) { + break; - var cos = Math.cos( this.aRotation ); - var sin = Math.sin( this.aRotation ); + case 'SpotLight': - var tx = x - this.aX; - var ty = y - this.aY; + object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); - // Rotate the point about the center of the ellipse. - x = tx * cos - ty * sin + this.aX; - y = tx * sin + ty * cos + this.aY; + break; - } + case 'HemisphereLight': - return new Vector2( x, y ); + object = new HemisphereLight( data.color, data.groundColor, data.intensity ); - }; + break; - function SplineCurve( points /* array of Vector2 */ ) { + case 'SkinnedMesh': - Curve.call( this ); + console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' ); - this.points = ( points === undefined ) ? [] : points; + case 'Mesh': - } + var geometry = getGeometry( data.geometry ); + var material = getMaterial( data.material ); - SplineCurve.prototype = Object.create( Curve.prototype ); - SplineCurve.prototype.constructor = SplineCurve; + if ( geometry.bones && geometry.bones.length > 0 ) { - SplineCurve.prototype.isSplineCurve = true; + object = new SkinnedMesh( geometry, material ); - SplineCurve.prototype.getPoint = function ( t ) { + } else { - var points = this.points; - var point = ( points.length - 1 ) * t; + object = new Mesh( geometry, material ); - var intPoint = Math.floor( point ); - var weight = point - intPoint; + } - var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; - var point1 = points[ intPoint ]; - var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; - var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; + break; - return new Vector2( - CatmullRom( weight, point0.x, point1.x, point2.x, point3.x ), - CatmullRom( weight, point0.y, point1.y, point2.y, point3.y ) - ); + case 'LOD': - }; + object = new LOD(); - function CubicBezierCurve( v0, v1, v2, v3 ) { + break; - Curve.call( this ); + case 'Line': - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; + object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); - } + break; - CubicBezierCurve.prototype = Object.create( Curve.prototype ); - CubicBezierCurve.prototype.constructor = CubicBezierCurve; + case 'LineLoop': - CubicBezierCurve.prototype.getPoint = function ( t ) { + object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) ); - var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + break; - return new Vector2( - CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), - CubicBezier( t, v0.y, v1.y, v2.y, v3.y ) - ); + case 'LineSegments': - }; + object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); - function QuadraticBezierCurve( v0, v1, v2 ) { + break; - Curve.call( this ); + case 'PointCloud': + case 'Points': - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; + object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); - } + break; - QuadraticBezierCurve.prototype = Object.create( Curve.prototype ); - QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve; + case 'Sprite': - QuadraticBezierCurve.prototype.getPoint = function ( t ) { + object = new Sprite( getMaterial( data.material ) ); - var v0 = this.v0, v1 = this.v1, v2 = this.v2; + break; - return new Vector2( - QuadraticBezier( t, v0.x, v1.x, v2.x ), - QuadraticBezier( t, v0.y, v1.y, v2.y ) - ); + case 'Group': - }; + object = new Group(); - var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), { + break; - fromPoints: function ( vectors ) { + default: - this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y ); + object = new Object3D(); - for ( var i = 1, l = vectors.length; i < l; i ++ ) { + } - this.lineTo( vectors[ i ].x, vectors[ i ].y ); + object.uuid = data.uuid; - } + if ( data.name !== undefined ) object.name = data.name; + if ( data.matrix !== undefined ) { - }, + object.matrix.fromArray( data.matrix ); + object.matrix.decompose( object.position, object.quaternion, object.scale ); - moveTo: function ( x, y ) { + } else { - this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? + if ( data.position !== undefined ) object.position.fromArray( data.position ); + if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation ); + if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion ); + if ( data.scale !== undefined ) object.scale.fromArray( data.scale ); - }, + } - lineTo: function ( x, y ) { + if ( data.castShadow !== undefined ) object.castShadow = data.castShadow; + if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow; - var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); - this.curves.push( curve ); + if ( data.shadow ) { - this.currentPoint.set( x, y ); + if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias; + if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius; + if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize ); + if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera ); - }, + } - quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { + if ( data.visible !== undefined ) object.visible = data.visible; + if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled; + if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder; + if ( data.userData !== undefined ) object.userData = data.userData; - var curve = new QuadraticBezierCurve( - this.currentPoint.clone(), - new Vector2( aCPx, aCPy ), - new Vector2( aX, aY ) - ); + if ( data.children !== undefined ) { - this.curves.push( curve ); + var children = data.children; - this.currentPoint.set( aX, aY ); + for ( var i = 0; i < children.length; i ++ ) { - }, + object.add( this.parseObject( children[ i ], geometries, materials ) ); - bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { + } - var curve = new CubicBezierCurve( - this.currentPoint.clone(), - new Vector2( aCP1x, aCP1y ), - new Vector2( aCP2x, aCP2y ), - new Vector2( aX, aY ) - ); + } - this.curves.push( curve ); + if ( data.type === 'LOD' ) { - this.currentPoint.set( aX, aY ); + var levels = data.levels; - }, + for ( var l = 0; l < levels.length; l ++ ) { - splineThru: function ( pts /*Array of Vector*/ ) { + var level = levels[ l ]; + var child = object.getObjectByProperty( 'uuid', level.object ); - var npts = [ this.currentPoint.clone() ].concat( pts ); + if ( child !== undefined ) { - var curve = new SplineCurve( npts ); - this.curves.push( curve ); + object.addLevel( child, level.distance ); - this.currentPoint.copy( pts[ pts.length - 1 ] ); + } - }, + } - arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + } - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; + return object; - this.absarc( aX + x0, aY + y0, aRadius, - aStartAngle, aEndAngle, aClockwise ); + } - }, + } ); - absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { + var TEXTURE_MAPPING = { + UVMapping: UVMapping, + CubeReflectionMapping: CubeReflectionMapping, + CubeRefractionMapping: CubeRefractionMapping, + EquirectangularReflectionMapping: EquirectangularReflectionMapping, + EquirectangularRefractionMapping: EquirectangularRefractionMapping, + SphericalReflectionMapping: SphericalReflectionMapping, + CubeUVReflectionMapping: CubeUVReflectionMapping, + CubeUVRefractionMapping: CubeUVRefractionMapping + }; - this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); + var TEXTURE_WRAPPING = { + RepeatWrapping: RepeatWrapping, + ClampToEdgeWrapping: ClampToEdgeWrapping, + MirroredRepeatWrapping: MirroredRepeatWrapping + }; - }, + var TEXTURE_FILTER = { + NearestFilter: NearestFilter, + NearestMipMapNearestFilter: NearestMipMapNearestFilter, + NearestMipMapLinearFilter: NearestMipMapLinearFilter, + LinearFilter: LinearFilter, + LinearMipMapNearestFilter: LinearMipMapNearestFilter, + LinearMipMapLinearFilter: LinearMipMapLinearFilter + }; - ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + /** + * @author thespite / http://clicktorelease.com/ + */ - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; + function ImageBitmapLoader( manager ) { - this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + if ( typeof createImageBitmap === 'undefined' ) { - }, + console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' ); - absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { + } - var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); + if ( typeof fetch === 'undefined' ) { - if ( this.curves.length > 0 ) { + console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' ); - // if a previous curve is present, attempt to join - var firstPoint = curve.getPoint( 0 ); + } - if ( ! firstPoint.equals( this.currentPoint ) ) { + this.manager = manager !== undefined ? manager : DefaultLoadingManager; + this.options = undefined; - this.lineTo( firstPoint.x, firstPoint.y ); + } - } + ImageBitmapLoader.prototype = { - } + constructor: ImageBitmapLoader, - this.curves.push( curve ); + setOptions: function setOptions( options ) { - var lastPoint = curve.getPoint( 1 ); - this.currentPoint.copy( lastPoint ); + this.options = options; - } + return this; - } ); + }, - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Creates free form 2d path using series of points, lines or curves. - **/ + load: function load( url, onLoad, onProgress, onError ) { - function Path( points ) { + if ( url === undefined ) url = ''; - CurvePath.call( this ); - this.currentPoint = new Vector2(); + if ( this.path !== undefined ) url = this.path + url; - if ( points ) { + var scope = this; - this.fromPoints( points ); + var cached = Cache.get( url ); - } + if ( cached !== undefined ) { - } + scope.manager.itemStart( url ); - Path.prototype = PathPrototype; - PathPrototype.constructor = Path; + setTimeout( function () { - /** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Defines a 2d shape plane using paths. - **/ + if ( onLoad ) onLoad( cached ); - // STEP 1 Create a path. - // STEP 2 Turn path into shape. - // STEP 3 ExtrudeGeometry takes in Shape/Shapes - // STEP 3a - Extract points from each shape, turn to vertices - // STEP 3b - Triangulate each shape, add faces. + scope.manager.itemEnd( url ); - function Shape() { + }, 0 ); - Path.apply( this, arguments ); + return cached; - this.holes = []; + } - } + fetch( url ).then( function ( res ) { - Shape.prototype = Object.assign( Object.create( PathPrototype ), { + return res.blob(); - constructor: Shape, + } ).then( function ( blob ) { - getPointsHoles: function ( divisions ) { + return createImageBitmap( blob, scope.options ); - var holesPts = []; + } ).then( function ( imageBitmap ) { - for ( var i = 0, l = this.holes.length; i < l; i ++ ) { + Cache.add( url, imageBitmap ); - holesPts[ i ] = this.holes[ i ].getPoints( divisions ); + if ( onLoad ) onLoad( imageBitmap ); - } + scope.manager.itemEnd( url ); - return holesPts; + } ).catch( function ( e ) { - }, + if ( onError ) onError( e ); - // Get points of shape and holes (keypoints based on segments parameter) + scope.manager.itemEnd( url ); + scope.manager.itemError( url ); - extractAllPoints: function ( divisions ) { + } ); - return { + }, - shape: this.getPoints( divisions ), - holes: this.getPointsHoles( divisions ) + setCrossOrigin: function ( /* value */ ) { - }; + return this; }, - extractPoints: function ( divisions ) { + setPath: function ( value ) { - return this.extractAllPoints( divisions ); + this.path = value; + return this; } - } ); + }; /** * @author zz85 / http://www.lab4games.net/zz85/blog @@ -35612,6 +37677,8 @@ function ShapePath() { + this.type = 'ShapePath'; + this.subPaths = []; this.currentPath = null; @@ -35683,7 +37750,7 @@ var inside = false; for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { - var edgeLowPt = inPolygon[ p ]; + var edgeLowPt = inPolygon[ p ]; var edgeHighPt = inPolygon[ q ]; var edgeDx = edgeHighPt.x - edgeLowPt.x; @@ -35694,7 +37761,7 @@ // not parallel if ( edgeDy < 0 ) { - edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; + edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; } @@ -35887,6 +37954,8 @@ function Font( data ) { + this.type = 'Font'; + this.data = data; } @@ -35897,167 +37966,128 @@ generateShapes: function ( text, size, divisions ) { - function createPaths( text ) { - - var chars = String( text ).split( '' ); - var scale = size / data.resolution; - var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale; - - var offsetX = 0, offsetY = 0; - - var paths = []; - - for ( var i = 0; i < chars.length; i ++ ) { - - var char = chars[ i ]; - - if ( char === '\n' ) { - - offsetX = 0; - offsetY -= line_height; - - } else { - - var ret = createPath( char, scale, offsetX, offsetY ); - offsetX += ret.offsetX; - paths.push( ret.path ); + if ( size === undefined ) size = 100; + if ( divisions === undefined ) divisions = 4; - } + var shapes = []; + var paths = createPaths( text, size, divisions, this.data ); - } + for ( var p = 0, pl = paths.length; p < pl; p ++ ) { - return paths; + Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); } - function createPath( c, scale, offsetX, offsetY ) { - - var glyph = data.glyphs[ c ] || data.glyphs[ '?' ]; - - if ( ! glyph ) return; - - var path = new ShapePath(); - - var pts = []; - var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste; - - if ( glyph.o ) { - - var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); - - for ( var i = 0, l = outline.length; i < l; ) { + return shapes; - var action = outline[ i ++ ]; + } - switch ( action ) { + } ); - case 'm': // moveTo + function createPaths( text, size, divisions, data ) { - x = outline[ i ++ ] * scale + offsetX; - y = outline[ i ++ ] * scale + offsetY; + var chars = String( text ).split( '' ); + var scale = size / data.resolution; + var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale; - path.moveTo( x, y ); + var paths = []; - break; + var offsetX = 0, offsetY = 0; - case 'l': // lineTo + for ( var i = 0; i < chars.length; i ++ ) { - x = outline[ i ++ ] * scale + offsetX; - y = outline[ i ++ ] * scale + offsetY; + var char = chars[ i ]; - path.lineTo( x, y ); + if ( char === '\n' ) { - break; + offsetX = 0; + offsetY -= line_height; - case 'q': // quadraticCurveTo + } else { - cpx = outline[ i ++ ] * scale + offsetX; - cpy = outline[ i ++ ] * scale + offsetY; - cpx1 = outline[ i ++ ] * scale + offsetX; - cpy1 = outline[ i ++ ] * scale + offsetY; + var ret = createPath( char, divisions, scale, offsetX, offsetY, data ); + offsetX += ret.offsetX; + paths.push( ret.path ); - path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); + } - laste = pts[ pts.length - 1 ]; + } - if ( laste ) { + return paths; - cpx0 = laste.x; - cpy0 = laste.y; + } - for ( var i2 = 1; i2 <= divisions; i2 ++ ) { + function createPath( char, divisions, scale, offsetX, offsetY, data ) { - var t = i2 / divisions; - QuadraticBezier( t, cpx0, cpx1, cpx ); - QuadraticBezier( t, cpy0, cpy1, cpy ); + var glyph = data.glyphs[ char ] || data.glyphs[ '?' ]; - } + if ( ! glyph ) return; - } + var path = new ShapePath(); - break; + var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2; - case 'b': // bezierCurveTo + if ( glyph.o ) { - cpx = outline[ i ++ ] * scale + offsetX; - cpy = outline[ i ++ ] * scale + offsetY; - cpx1 = outline[ i ++ ] * scale + offsetX; - cpy1 = outline[ i ++ ] * scale + offsetY; - cpx2 = outline[ i ++ ] * scale + offsetX; - cpy2 = outline[ i ++ ] * scale + offsetY; + var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); - path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); + for ( var i = 0, l = outline.length; i < l; ) { - laste = pts[ pts.length - 1 ]; + var action = outline[ i ++ ]; - if ( laste ) { + switch ( action ) { - cpx0 = laste.x; - cpy0 = laste.y; + case 'm': // moveTo - for ( var i2 = 1; i2 <= divisions; i2 ++ ) { + x = outline[ i ++ ] * scale + offsetX; + y = outline[ i ++ ] * scale + offsetY; - var t = i2 / divisions; - CubicBezier( t, cpx0, cpx1, cpx2, cpx ); - CubicBezier( t, cpy0, cpy1, cpy2, cpy ); + path.moveTo( x, y ); - } + break; - } + case 'l': // lineTo - break; + x = outline[ i ++ ] * scale + offsetX; + y = outline[ i ++ ] * scale + offsetY; - } + path.lineTo( x, y ); - } + break; - } + case 'q': // quadraticCurveTo - return { offsetX: glyph.ha * scale, path: path }; + cpx = outline[ i ++ ] * scale + offsetX; + cpy = outline[ i ++ ] * scale + offsetY; + cpx1 = outline[ i ++ ] * scale + offsetX; + cpy1 = outline[ i ++ ] * scale + offsetY; - } + path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); - // + break; - if ( size === undefined ) size = 100; - if ( divisions === undefined ) divisions = 4; + case 'b': // bezierCurveTo - var data = this.data; + cpx = outline[ i ++ ] * scale + offsetX; + cpy = outline[ i ++ ] * scale + offsetY; + cpx1 = outline[ i ++ ] * scale + offsetX; + cpy1 = outline[ i ++ ] * scale + offsetY; + cpx2 = outline[ i ++ ] * scale + offsetX; + cpy2 = outline[ i ++ ] * scale + offsetY; - var paths = createPaths( text ); - var shapes = []; + path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); - for ( var p = 0, pl = paths.length; p < pl; p ++ ) { + break; - Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); + } } - return shapes; - } - } ); + return { offsetX: glyph.ha * scale, path: path }; + + } /** * @author mrdoob / http://mrdoob.com/ @@ -36076,6 +38106,7 @@ var scope = this; var loader = new FileLoader( this.manager ); + loader.setPath( this.path ); loader.load( url, function ( text ) { var json; @@ -36103,10 +38134,21 @@ return new Font( json ); + }, + + setPath: function ( value ) { + + this.path = value; + return this; + } } ); + /** + * @author mrdoob / http://mrdoob.com/ + */ + var context; var AudioContext = { @@ -36305,7 +38347,7 @@ this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options ); this.renderTarget.texture.name = "CubeCamera"; - this.updateCubeMap = function ( renderer, scene ) { + this.update = function ( renderer, scene ) { if ( this.parent === null ) this.updateMatrixWorld(); @@ -36338,6 +38380,23 @@ }; + this.clear = function ( renderer, color, depth, stencil ) { + + var renderTarget = this.renderTarget; + + for ( var i = 0; i < 6; i ++ ) { + + renderTarget.activeCubeFace = i; + renderer.setRenderTarget( renderTarget ); + + renderer.clear( color, depth, stencil ); + + } + + renderer.setRenderTarget( null ); + + }; + } CubeCamera.prototype = Object.create( Object3D.prototype ); @@ -36487,6 +38546,7 @@ this.buffer = null; this.loop = false; this.startTime = 0; + this.offset = 0; this.playbackRate = 1; this.isPlaying = false; this.hasPlaybackControl = true; @@ -36550,7 +38610,8 @@ source.loop = this.loop; source.onended = this.onEnded.bind( this ); source.playbackRate.setValueAtTime( this.playbackRate, this.startTime ); - source.start( 0, this.startTime ); + this.startTime = this.context.currentTime; + source.start( this.startTime, this.offset ); this.isPlaying = true; @@ -36569,9 +38630,13 @@ } - this.source.stop(); - this.startTime = this.context.currentTime; - this.isPlaying = false; + if ( this.isPlaying === true ) { + + this.source.stop(); + this.offset += ( this.context.currentTime - this.startTime ) * this.playbackRate; + this.isPlaying = false; + + } return this; @@ -36587,7 +38652,7 @@ } this.source.stop(); - this.startTime = 0; + this.offset = 0; this.isPlaying = false; return this; @@ -36752,7 +38817,7 @@ return this.gain.gain.value; }, - + setVolume: function ( value ) { this.gain.gain.value = value; @@ -37109,6 +39174,9 @@ * @author tschw */ + // Characters [].:/ are reserved for track binding syntax. + var RESERVED_CHARS_RE = '\\[\\]\\.:\\/'; + function Composite( targetGroup, path, optionalParsedPath ) { var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path ); @@ -37210,87 +39278,99 @@ * @param {string} name Node name to be sanitized. * @return {string} */ - sanitizeNodeName: function ( name ) { + sanitizeNodeName: ( function () { - return name.replace( /\s/g, '_' ).replace( /[^\w-]/g, '' ); + var reservedRe = new RegExp( '[' + RESERVED_CHARS_RE + ']', 'g' ); - }, + return function sanitizeNodeName( name ) { + + return name.replace( /\s/g, '_' ).replace( reservedRe, '' ); + + }; + + }() ), parseTrackName: function () { + // Attempts to allow node names from any language. ES5's `\w` regexp matches + // only latin characters, and the unicode \p{L} is not yet supported. So + // instead, we exclude reserved characters and match everything else. + var wordChar = '[^' + RESERVED_CHARS_RE + ']'; + var wordCharOrDot = '[^' + RESERVED_CHARS_RE.replace( '\\.', '' ) + ']'; + // Parent directories, delimited by '/' or ':'. Currently unused, but must // be matched to parse the rest of the track name. - var directoryRe = /((?:[\w-]+[\/:])*)/; + var directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', wordChar ); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. - var nodeRe = /([\w-\.]+)?/; + var nodeRe = /(WCOD+)?/.source.replace( 'WCOD', wordCharOrDot ); - // Object on target node, and accessor. Name may contain only word + // Object on target node, and accessor. May not contain reserved // characters. Accessor may contain any character except closing bracket. - var objectRe = /(?:\.([\w-]+)(?:\[(.+)\])?)?/; + var objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', wordChar ); - // Property and accessor. May contain only word characters. Accessor may + // Property and accessor. May not contain reserved characters. Accessor may // contain any non-bracket characters. - var propertyRe = /\.([\w-]+)(?:\[(.+)\])?/; + var propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', wordChar ); - var trackRe = new RegExp('' + var trackRe = new RegExp( '' + '^' - + directoryRe.source - + nodeRe.source - + objectRe.source - + propertyRe.source + + directoryRe + + nodeRe + + objectRe + + propertyRe + '$' ); var supportedObjectNames = [ 'material', 'materials', 'bones' ]; - return function ( trackName ) { - - var matches = trackRe.exec( trackName ); + return function parseTrackName( trackName ) { - if ( ! matches ) { + var matches = trackRe.exec( trackName ); - throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName ); + if ( ! matches ) { - } + throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName ); - var results = { - // directoryName: matches[ 1 ], // (tschw) currently unused - nodeName: matches[ 2 ], - objectName: matches[ 3 ], - objectIndex: matches[ 4 ], - propertyName: matches[ 5 ], // required - propertyIndex: matches[ 6 ] - }; + } - var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' ); + var results = { + // directoryName: matches[ 1 ], // (tschw) currently unused + nodeName: matches[ 2 ], + objectName: matches[ 3 ], + objectIndex: matches[ 4 ], + propertyName: matches[ 5 ], // required + propertyIndex: matches[ 6 ] + }; - if ( lastDot !== undefined && lastDot !== -1 ) { + var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' ); - var objectName = results.nodeName.substring( lastDot + 1 ); + if ( lastDot !== undefined && lastDot !== - 1 ) { - // Object names must be checked against a whitelist. Otherwise, there - // is no way to parse 'foo.bar.baz': 'baz' must be a property, but - // 'bar' could be the objectName, or part of a nodeName (which can - // include '.' characters). - if ( supportedObjectNames.indexOf( objectName ) !== -1 ) { + var objectName = results.nodeName.substring( lastDot + 1 ); - results.nodeName = results.nodeName.substring( 0, lastDot ); - results.objectName = objectName; + // Object names must be checked against a whitelist. Otherwise, there + // is no way to parse 'foo.bar.baz': 'baz' must be a property, but + // 'bar' could be the objectName, or part of a nodeName (which can + // include '.' characters). + if ( supportedObjectNames.indexOf( objectName ) !== - 1 ) { - } + results.nodeName = results.nodeName.substring( 0, lastDot ); + results.objectName = objectName; } - if ( results.propertyName === null || results.propertyName.length === 0 ) { + } + + if ( results.propertyName === null || results.propertyName.length === 0 ) { - throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName ); + throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName ); - } + } - return results; + return results; - }; + }; }(), @@ -37305,27 +39385,9 @@ // search into skeleton bones. if ( root.skeleton ) { - var searchSkeleton = function ( skeleton ) { - - for ( var i = 0; i < skeleton.bones.length; i ++ ) { - - var bone = skeleton.bones[ i ]; - - if ( bone.name === nodeName ) { - - return bone; - - } - - } - - return null; - - }; - - var bone = searchSkeleton( root.skeleton ); + var bone = root.skeleton.getBoneByName( nodeName ); - if ( bone ) { + if ( bone !== undefined ) { return bone; @@ -37434,20 +39496,20 @@ function setValue_direct( buffer, offset ) { - this.node[ this.propertyName ] = buffer[ offset ]; + this.targetObject[ this.propertyName ] = buffer[ offset ]; }, function setValue_direct_setNeedsUpdate( buffer, offset ) { - this.node[ this.propertyName ] = buffer[ offset ]; + this.targetObject[ this.propertyName ] = buffer[ offset ]; this.targetObject.needsUpdate = true; }, function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { - this.node[ this.propertyName ] = buffer[ offset ]; + this.targetObject[ this.propertyName ] = buffer[ offset ]; this.targetObject.matrixWorldNeedsUpdate = true; } @@ -37580,8 +39642,7 @@ if ( ! targetObject ) { - targetObject = PropertyBinding.findNode( - this.rootNode, parsedPath.nodeName ) || this.rootNode; + targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode; this.node = targetObject; @@ -37859,7 +39920,7 @@ * @author tschw */ - function AnimationObjectGroup( var_args ) { + function AnimationObjectGroup() { this.uuid = _Math.generateUUID(); @@ -37888,11 +39949,22 @@ this.stats = { objects: { - get total() { return scope._objects.length; }, - get inUse() { return this.total - scope.nCachedObjects_; } + get total() { + + return scope._objects.length; + + }, + get inUse() { + + return this.total - scope.nCachedObjects_; + + } }, + get bindingsPerObject() { + + return scope._bindings.length; - get bindingsPerObject() { return scope._bindings.length; } + } }; @@ -37902,7 +39974,7 @@ isAnimationObjectGroup: true, - add: function( var_args ) { + add: function () { var objects = this._objects, nObjects = objects.length, @@ -37911,14 +39983,14 @@ paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, - nBindings = bindings.length; + nBindings = bindings.length, + knownObject = undefined; for ( var i = 0, n = arguments.length; i !== n; ++ i ) { var object = arguments[ i ], uuid = object.uuid, - index = indicesByUUID[ uuid ], - knownObject = undefined; + index = indicesByUUID[ uuid ]; if ( index === undefined ) { @@ -37932,9 +40004,7 @@ for ( var j = 0, m = nBindings; j !== m; ++ j ) { - bindings[ j ].push( - new PropertyBinding( - object, paths[ j ], parsedPaths[ j ] ) ); + bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) ); } @@ -37969,8 +40039,7 @@ // for objects that are cached, the binding may // or may not exist - binding = new PropertyBinding( - object, paths[ j ], parsedPaths[ j ] ); + binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ); } @@ -37991,7 +40060,7 @@ }, - remove: function( var_args ) { + remove: function () { var objects = this._objects, nCachedObjects = this.nCachedObjects_, @@ -38040,7 +40109,7 @@ }, // remove & forget - uncache: function( var_args ) { + uncache: function () { var objects = this._objects, nObjects = objects.length, @@ -38218,8 +40287,8 @@ interpolants = new Array( nTracks ); var interpolantSettings = { - endingStart: ZeroCurvatureEnding, - endingEnd: ZeroCurvatureEnding + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding }; for ( var i = 0; i !== nTracks; ++ i ) { @@ -38244,7 +40313,7 @@ this._weightInterpolant = null; this.loop = LoopRepeat; - this._loopCount = -1; + this._loopCount = - 1; // global mixer time when the action is to be started // it's set back to 'null' upon start of the action @@ -38276,7 +40345,7 @@ // State & Scheduling - play: function() { + play: function () { this._mixer._activateAction( this ); @@ -38284,7 +40353,7 @@ }, - stop: function() { + stop: function () { this._mixer._deactivateAction( this ); @@ -38292,20 +40361,20 @@ }, - reset: function() { + reset: function () { this.paused = false; this.enabled = true; this.time = 0; // restart clip - this._loopCount = -1; // forget previous loops + this._loopCount = - 1; // forget previous loops this._startTime = null; // forget scheduling return this.stopFading().stopWarping(); }, - isRunning: function() { + isRunning: function () { return this.enabled && ! this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction( this ); @@ -38313,13 +40382,13 @@ }, // return true when play has been called - isScheduled: function() { + isScheduled: function () { return this._mixer._isActiveAction( this ); }, - startAt: function( time ) { + startAt: function ( time ) { this._startTime = time; @@ -38327,7 +40396,7 @@ }, - setLoop: function( mode, repetitions ) { + setLoop: function ( mode, repetitions ) { this.loop = mode; this.repetitions = repetitions; @@ -38341,7 +40410,7 @@ // set the weight stopping any scheduled fading // although .enabled = false yields an effective weight of zero, this // method does *not* change .enabled, because it would be confusing - setEffectiveWeight: function( weight ) { + setEffectiveWeight: function ( weight ) { this.weight = weight; @@ -38353,30 +40422,30 @@ }, // return the weight considering fading and .enabled - getEffectiveWeight: function() { + getEffectiveWeight: function () { return this._effectiveWeight; }, - fadeIn: function( duration ) { + fadeIn: function ( duration ) { return this._scheduleFading( duration, 0, 1 ); }, - fadeOut: function( duration ) { + fadeOut: function ( duration ) { return this._scheduleFading( duration, 1, 0 ); }, - crossFadeFrom: function( fadeOutAction, duration, warp ) { + crossFadeFrom: function ( fadeOutAction, duration, warp ) { fadeOutAction.fadeOut( duration ); this.fadeIn( duration ); - if( warp ) { + if ( warp ) { var fadeInDuration = this._clip.duration, fadeOutDuration = fadeOutAction._clip.duration, @@ -38393,13 +40462,13 @@ }, - crossFadeTo: function( fadeInAction, duration, warp ) { + crossFadeTo: function ( fadeInAction, duration, warp ) { return fadeInAction.crossFadeFrom( this, duration, warp ); }, - stopFading: function() { + stopFading: function () { var weightInterpolant = this._weightInterpolant; @@ -38419,23 +40488,23 @@ // set the time scale stopping any scheduled warping // although .paused = true yields an effective time scale of zero, this // method does *not* change .paused, because it would be confusing - setEffectiveTimeScale: function( timeScale ) { + setEffectiveTimeScale: function ( timeScale ) { this.timeScale = timeScale; - this._effectiveTimeScale = this.paused ? 0 :timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; return this.stopWarping(); }, // return the time scale considering warping and .paused - getEffectiveTimeScale: function() { + getEffectiveTimeScale: function () { return this._effectiveTimeScale; }, - setDuration: function( duration ) { + setDuration: function ( duration ) { this.timeScale = this._clip.duration / duration; @@ -38443,7 +40512,7 @@ }, - syncWith: function( action ) { + syncWith: function ( action ) { this.time = action.time; this.timeScale = action.timeScale; @@ -38452,13 +40521,13 @@ }, - halt: function( duration ) { + halt: function ( duration ) { return this.warp( this._effectiveTimeScale, 0, duration ); }, - warp: function( startTimeScale, endTimeScale, duration ) { + warp: function ( startTimeScale, endTimeScale, duration ) { var mixer = this._mixer, now = mixer.time, interpolant = this._timeScaleInterpolant, @@ -38485,7 +40554,7 @@ }, - stopWarping: function() { + stopWarping: function () { var timeScaleInterpolant = this._timeScaleInterpolant; @@ -38502,19 +40571,19 @@ // Object Accessors - getMixer: function() { + getMixer: function () { return this._mixer; }, - getClip: function() { + getClip: function () { return this._clip; }, - getRoot: function() { + getRoot: function () { return this._localRoot || this._mixer._root; @@ -38522,7 +40591,7 @@ // Interna - _update: function( time, deltaTime, timeDirection, accuIndex ) { + _update: function ( time, deltaTime, timeDirection, accuIndex ) { // called by the mixer @@ -38581,7 +40650,7 @@ }, - _updateWeight: function( time ) { + _updateWeight: function ( time ) { var weight = 0; @@ -38618,7 +40687,7 @@ }, - _updateTimeScale: function( time ) { + _updateTimeScale: function ( time ) { var timeScale = 0; @@ -38661,7 +40730,7 @@ }, - _updateTime: function( deltaTime ) { + _updateTime: function ( deltaTime ) { var time = this.time + deltaTime; @@ -38674,7 +40743,8 @@ if ( loop === LoopOnce ) { - if ( loopCount === -1 ) { + if ( loopCount === - 1 ) { + // just started this._loopCount = 0; @@ -38699,7 +40769,7 @@ this._mixer.dispatchEvent( { type: 'finished', action: this, - direction: deltaTime < 0 ? -1 : 1 + direction: deltaTime < 0 ? - 1 : 1 } ); } @@ -38708,15 +40778,15 @@ var pingPong = ( loop === LoopPingPong ); - if ( loopCount === -1 ) { + if ( loopCount === - 1 ) { + // just started if ( deltaTime >= 0 ) { loopCount = 0; - this._setEndings( - true, this.repetitions === 0, pingPong ); + this._setEndings( true, this.repetitions === 0, pingPong ); } else { @@ -38724,14 +40794,14 @@ // transition through zero counts as a repetition, // so leave loopCount at -1 - this._setEndings( - this.repetitions === 0, true, pingPong ); + this._setEndings( this.repetitions === 0, true, pingPong ); } } if ( time >= duration || time < 0 ) { + // wrap around var loopDelta = Math.floor( time / duration ); // signed @@ -38741,7 +40811,8 @@ var pending = this.repetitions - loopCount; - if ( pending < 0 ) { + if ( pending <= 0 ) { + // have to stop (switch state, clamp time, fire event) if ( this.clampWhenFinished ) this.paused = true; @@ -38751,13 +40822,15 @@ this._mixer.dispatchEvent( { type: 'finished', action: this, - direction: deltaTime > 0 ? 1 : -1 + direction: deltaTime > 0 ? 1 : - 1 } ); } else { + // keep running - if ( pending === 0 ) { + if ( pending === 1 ) { + // entering the last round var atStart = deltaTime < 0; @@ -38780,6 +40853,7 @@ } if ( pingPong && ( loopCount & 1 ) === 1 ) { + // invert time for the "pong round" this.time = time; @@ -38794,7 +40868,7 @@ }, - _setEndings: function( atStart, atEnd, pingPong ) { + _setEndings: function ( atStart, atEnd, pingPong ) { var settings = this._interpolantSettings; @@ -38809,8 +40883,7 @@ if ( atStart ) { - settings.endingStart = this.zeroSlopeAtStart ? - ZeroSlopeEnding : ZeroCurvatureEnding; + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; } else { @@ -38820,8 +40893,7 @@ if ( atEnd ) { - settings.endingEnd = this.zeroSlopeAtEnd ? - ZeroSlopeEnding : ZeroCurvatureEnding; + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; } else { @@ -38833,7 +40905,7 @@ }, - _scheduleFading: function( duration, weightNow, weightThen ) { + _scheduleFading: function ( duration, weightNow, weightThen ) { var mixer = this._mixer, now = mixer.time, interpolant = this._weightInterpolant; @@ -38879,7 +40951,9 @@ } - Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, { + AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { + + constructor: AnimationMixer, _bindAction: function ( action, prototypeAction ) { @@ -38929,7 +41003,7 @@ } var path = prototypeAction && prototypeAction. - _propertyBindings[ i ].binding.parsedPath; + _propertyBindings[ i ].binding.parsedPath; binding = new PropertyMixer( PropertyBinding.create( root, trackName, path ), @@ -39045,16 +41119,40 @@ this.stats = { actions: { - get total() { return scope._actions.length; }, - get inUse() { return scope._nActiveActions; } + get total() { + + return scope._actions.length; + + }, + get inUse() { + + return scope._nActiveActions; + + } }, bindings: { - get total() { return scope._bindings.length; }, - get inUse() { return scope._nActiveBindings; } + get total() { + + return scope._bindings.length; + + }, + get inUse() { + + return scope._nActiveBindings; + + } }, controlInterpolants: { - get total() { return scope._controlInterpolants.length; }, - get inUse() { return scope._nActiveControlInterpolants; } + get total() { + + return scope._controlInterpolants.length; + + }, + get inUse() { + + return scope._nActiveControlInterpolants; + + } } }; @@ -39256,7 +41354,7 @@ remove_empty_map: { - for ( var _ in bindingByName ) break remove_empty_map; + for ( var _ in bindingByName ) break remove_empty_map; // eslint-disable-line no-unused-vars delete bindingsByRoot[ rootUuid ]; @@ -39625,47 +41723,19 @@ isInstancedBufferGeometry: true, - addGroup: function ( start, count, materialIndex ) { - - this.groups.push( { - - start: start, - count: count, - materialIndex: materialIndex - - } ); - - }, - copy: function ( source ) { - var index = source.index; - - if ( index !== null ) { - - this.setIndex( index.clone() ); - - } - - var attributes = source.attributes; - - for ( var name in attributes ) { - - var attribute = attributes[ name ]; - this.addAttribute( name, attribute.clone() ); + BufferGeometry.prototype.copy.call( this, source ); - } - - var groups = source.groups; + this.maxInstancedCount = source.maxInstancedCount; - for ( var i = 0, l = groups.length; i < l; i ++ ) { + return this; - var group = groups[ i ]; - this.addGroup( group.start, group.count, group.materialIndex ); + }, - } + clone: function () { - return this; + return new this.constructor().copy( this ); } @@ -39677,8 +41747,6 @@ function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) { - this.uuid = _Math.generateUUID(); - this.data = interleavedBuffer; this.itemSize = itemSize; this.offset = offset; @@ -39815,8 +41883,6 @@ function InterleavedBuffer( array, stride ) { - this.uuid = _Math.generateUUID(); - this.array = array; this.stride = stride; this.count = array !== undefined ? array.length / stride : 0; @@ -39824,8 +41890,6 @@ this.dynamic = false; this.updateRange = { offset: 0, count: - 1 }; - this.onUploadCallback = function () {}; - this.version = 0; } @@ -39844,6 +41908,8 @@ isInterleavedBuffer: true, + onUploadCallback: function () {}, + setArray: function ( array ) { if ( Array.isArray( array ) ) { @@ -40002,8 +42068,10 @@ Object.defineProperties( this.params, { PointCloud: { get: function () { + console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); return this.Points; + } } } ); @@ -40068,9 +42136,9 @@ }, - intersectObject: function ( object, recursive ) { + intersectObject: function ( object, recursive, optionalTarget ) { - var intersects = []; + var intersects = optionalTarget || []; intersectObject( object, this, intersects, recursive ); @@ -40080,9 +42148,9 @@ }, - intersectObjects: function ( objects, recursive ) { + intersectObjects: function ( objects, recursive, optionalTarget ) { - var intersects = []; + var intersects = optionalTarget || []; if ( Array.isArray( objects ) === false ) { @@ -40225,7 +42293,7 @@ }, // restrict phi to be betwee EPS and PI-EPS - makeSafe: function() { + makeSafe: function () { var EPS = 0.000001; this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); @@ -40234,7 +42302,7 @@ }, - setFromVector3: function( vec3 ) { + setFromVector3: function ( vec3 ) { this.radius = vec3.length(); @@ -40301,7 +42369,7 @@ }, - setFromVector3: function( vec3 ) { + setFromVector3: function ( vec3 ) { this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z ); this.theta = Math.atan2( vec3.x, vec3.z ); @@ -40313,321 +42381,245 @@ } ); - /** - * @author alteredq / http://alteredqualia.com/ - */ - - function MorphBlendMesh( geometry, material ) { - - Mesh.call( this, geometry, material ); - - this.animationsMap = {}; - this.animationsList = []; - - // prepare default animation - // (all frames played together in 1 second) - - var numFrames = this.geometry.morphTargets.length; - - var name = "__default"; - - var startFrame = 0; - var endFrame = numFrames - 1; - - var fps = numFrames / 1; - - this.createAnimation( name, startFrame, endFrame, fps ); - this.setAnimationWeight( name, 1 ); - - } - - MorphBlendMesh.prototype = Object.create( Mesh.prototype ); - MorphBlendMesh.prototype.constructor = MorphBlendMesh; - - MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) { - - var animation = { - - start: start, - end: end, - - length: end - start + 1, - - fps: fps, - duration: ( end - start ) / fps, - - lastFrame: 0, - currentFrame: 0, - - active: false, - - time: 0, - direction: 1, - weight: 1, - - directionBackwards: false, - mirroredLoop: false - - }; - - this.animationsMap[ name ] = animation; - this.animationsList.push( animation ); - - }; - - MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) { - - var pattern = /([a-z]+)_?(\d+)/i; - - var firstAnimation, frameRanges = {}; - - var geometry = this.geometry; - - for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) { - - var morph = geometry.morphTargets[ i ]; - var chunks = morph.name.match( pattern ); - - if ( chunks && chunks.length > 1 ) { - - var name = chunks[ 1 ]; - - if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity }; - - var range = frameRanges[ name ]; - - if ( i < range.start ) range.start = i; - if ( i > range.end ) range.end = i; - - if ( ! firstAnimation ) firstAnimation = name; - - } - - } - - for ( var name in frameRanges ) { - - var range = frameRanges[ name ]; - this.createAnimation( name, range.start, range.end, fps ); - - } - - this.firstAnimation = firstAnimation; - - }; - - MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.direction = 1; - animation.directionBackwards = false; - - } - - }; - - MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.direction = - 1; - animation.directionBackwards = true; - - } - - }; - - MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.fps = fps; - animation.duration = ( animation.end - animation.start ) / animation.fps; - - } - - }; - - MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.duration = duration; - animation.fps = ( animation.end - animation.start ) / animation.duration; - - } - - }; - - MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.weight = weight; - - } - - }; - - MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.time = time; - - } - - }; - - MorphBlendMesh.prototype.getAnimationTime = function ( name ) { - - var time = 0; - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - time = animation.time; - - } - - return time; - - }; - - MorphBlendMesh.prototype.getAnimationDuration = function ( name ) { - - var duration = - 1; - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - duration = animation.duration; - - } - - return duration; - - }; - - MorphBlendMesh.prototype.playAnimation = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.time = 0; - animation.active = true; - - } else { - - console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" ); - - } - - }; - - MorphBlendMesh.prototype.stopAnimation = function ( name ) { - - var animation = this.animationsMap[ name ]; - - if ( animation ) { - - animation.active = false; - - } - - }; - - MorphBlendMesh.prototype.update = function ( delta ) { - - for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) { - - var animation = this.animationsList[ i ]; - - if ( ! animation.active ) continue; - - var frameTime = animation.duration / animation.length; - - animation.time += animation.direction * delta; - - if ( animation.mirroredLoop ) { - - if ( animation.time > animation.duration || animation.time < 0 ) { - - animation.direction *= - 1; - - if ( animation.time > animation.duration ) { - - animation.time = animation.duration; - animation.directionBackwards = true; - - } - - if ( animation.time < 0 ) { - - animation.time = 0; - animation.directionBackwards = false; - - } - - } - - } else { - - animation.time = animation.time % animation.duration; - - if ( animation.time < 0 ) animation.time += animation.duration; - - } - - var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 ); - var weight = animation.weight; - - if ( keyframe !== animation.currentFrame ) { - - this.morphTargetInfluences[ animation.lastFrame ] = 0; - this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight; - - this.morphTargetInfluences[ keyframe ] = 0; - - animation.lastFrame = animation.currentFrame; - animation.currentFrame = keyframe; - - } - - var mix = ( animation.time % frameTime ) / frameTime; - - if ( animation.directionBackwards ) mix = 1 - mix; - - if ( animation.currentFrame !== animation.lastFrame ) { - - this.morphTargetInfluences[ animation.currentFrame ] = mix * weight; - this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight; - - } else { - - this.morphTargetInfluences[ animation.currentFrame ] = weight; - - } - - } - - }; + /** + * @author bhouston / http://clara.io + */ + + function Box2( min, max ) { + + this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); + this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); + + } + + Object.assign( Box2.prototype, { + + set: function ( min, max ) { + + this.min.copy( min ); + this.max.copy( max ); + + return this; + + }, + + setFromPoints: function ( points ) { + + this.makeEmpty(); + + for ( var i = 0, il = points.length; i < il; i ++ ) { + + this.expandByPoint( points[ i ] ); + + } + + return this; + + }, + + setFromCenterAndSize: function () { + + var v1 = new Vector2(); + + return function setFromCenterAndSize( center, size ) { + + var halfSize = v1.copy( size ).multiplyScalar( 0.5 ); + this.min.copy( center ).sub( halfSize ); + this.max.copy( center ).add( halfSize ); + + return this; + + }; + + }(), + + clone: function () { + + return new this.constructor().copy( this ); + + }, + + copy: function ( box ) { + + this.min.copy( box.min ); + this.max.copy( box.max ); + + return this; + + }, + + makeEmpty: function () { + + this.min.x = this.min.y = + Infinity; + this.max.x = this.max.y = - Infinity; + + return this; + + }, + + isEmpty: function () { + + // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes + + return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); + + }, + + getCenter: function ( target ) { + + if ( target === undefined ) { + + console.warn( 'THREE.Box2: .getCenter() target is now required' ); + target = new Vector2(); + + } + + return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); + + }, + + getSize: function ( target ) { + + if ( target === undefined ) { + + console.warn( 'THREE.Box2: .getSize() target is now required' ); + target = new Vector2(); + + } + + return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); + + }, + + expandByPoint: function ( point ) { + + this.min.min( point ); + this.max.max( point ); + + return this; + + }, + + expandByVector: function ( vector ) { + + this.min.sub( vector ); + this.max.add( vector ); + + return this; + + }, + + expandByScalar: function ( scalar ) { + + this.min.addScalar( - scalar ); + this.max.addScalar( scalar ); + + return this; + + }, + + containsPoint: function ( point ) { + + return point.x < this.min.x || point.x > this.max.x || + point.y < this.min.y || point.y > this.max.y ? false : true; + + }, + + containsBox: function ( box ) { + + return this.min.x <= box.min.x && box.max.x <= this.max.x && + this.min.y <= box.min.y && box.max.y <= this.max.y; + + }, + + getParameter: function ( point, target ) { + + // This can potentially have a divide by zero if the box + // has a size dimension of 0. + + if ( target === undefined ) { + + console.warn( 'THREE.Box2: .getParameter() target is now required' ); + target = new Vector2(); + + } + + return target.set( + ( point.x - this.min.x ) / ( this.max.x - this.min.x ), + ( point.y - this.min.y ) / ( this.max.y - this.min.y ) + ); + + }, + + intersectsBox: function ( box ) { + + // using 4 splitting planes to rule out intersections + + return box.max.x < this.min.x || box.min.x > this.max.x || + box.max.y < this.min.y || box.min.y > this.max.y ? false : true; + + }, + + clampPoint: function ( point, target ) { + + if ( target === undefined ) { + + console.warn( 'THREE.Box2: .clampPoint() target is now required' ); + target = new Vector2(); + + } + + return target.copy( point ).clamp( this.min, this.max ); + + }, + + distanceToPoint: function () { + + var v1 = new Vector2(); + + return function distanceToPoint( point ) { + + var clampedPoint = v1.copy( point ).clamp( this.min, this.max ); + return clampedPoint.sub( point ).length(); + + }; + + }(), + + intersect: function ( box ) { + + this.min.max( box.min ); + this.max.min( box.max ); + + return this; + + }, + + union: function ( box ) { + + this.min.min( box.min ); + this.max.max( box.max ); + + return this; + + }, + + translate: function ( offset ) { + + this.min.add( offset ); + this.max.add( offset ); + + return this; + + }, + + equals: function ( box ) { + + return box.min.equals( this.min ) && box.max.equals( this.max ); + + } + + } ); /** * @author alteredq / http://alteredqualia.com/ @@ -40638,7 +42630,7 @@ Object3D.call( this ); this.material = material; - this.render = function ( renderCallback ) {}; + this.render = function ( /* renderCallback */ ) {}; } @@ -40650,7 +42642,7 @@ /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley - */ + */ function VertexNormalsHelper( object, size, hex, linewidth ) { @@ -40795,9 +42787,9 @@ * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley - */ + */ - function SpotLightHelper( light ) { + function SpotLightHelper( light, color ) { Object3D.call( this ); @@ -40807,14 +42799,16 @@ this.matrix = light.matrixWorld; this.matrixAutoUpdate = false; + this.color = color; + var geometry = new BufferGeometry(); var positions = [ - 0, 0, 0, 0, 0, 1, - 0, 0, 0, 1, 0, 1, - 0, 0, 0, - 1, 0, 1, - 0, 0, 0, 0, 1, 1, - 0, 0, 0, 0, - 1, 1 + 0, 0, 0, 0, 0, 1, + 0, 0, 0, 1, 0, 1, + 0, 0, 0, - 1, 0, 1, + 0, 0, 0, 0, 1, 1, + 0, 0, 0, 0, - 1, 1 ]; for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { @@ -40869,7 +42863,15 @@ this.cone.lookAt( vector2.sub( vector ) ); - this.cone.material.color.copy( this.light.color ); + if ( this.color !== undefined ) { + + this.cone.material.color.set( this.color ); + + } else { + + this.cone.material.color.copy( this.light.color ); + + } }; @@ -40943,21 +42945,19 @@ this.matrix = object.matrixWorld; this.matrixAutoUpdate = false; - this.onBeforeRender(); - } SkeletonHelper.prototype = Object.create( LineSegments.prototype ); SkeletonHelper.prototype.constructor = SkeletonHelper; - SkeletonHelper.prototype.onBeforeRender = function () { + SkeletonHelper.prototype.updateMatrixWorld = function () { var vector = new Vector3(); var boneMatrix = new Matrix4(); var matrixWorldInv = new Matrix4(); - return function onBeforeRender() { + return function updateMatrixWorld( force ) { var bones = this.bones; @@ -40988,6 +42988,8 @@ geometry.getAttribute( 'position' ).needsUpdate = true; + Object3D.prototype.updateMatrixWorld.call( this, force ); + }; }(); @@ -40997,20 +42999,24 @@ * @author mrdoob / http://mrdoob.com/ */ - function PointLightHelper( light, sphereSize ) { + function PointLightHelper( light, sphereSize, color ) { this.light = light; this.light.updateMatrixWorld(); + this.color = color; + var geometry = new SphereBufferGeometry( sphereSize, 4, 2 ); var material = new MeshBasicMaterial( { wireframe: true, fog: false } ); - material.color.copy( this.light.color ); Mesh.call( this, geometry, material ); this.matrix = this.light.matrixWorld; this.matrixAutoUpdate = false; + this.update(); + + /* var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 ); var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); @@ -41047,7 +43053,15 @@ PointLightHelper.prototype.update = function () { - this.material.color.copy( this.light.color ); + if ( this.color !== undefined ) { + + this.material.color.set( this.color ); + + } else { + + this.material.color.copy( this.light.color ); + + } /* var d = this.light.distance; @@ -41072,7 +43086,7 @@ * @author WestLangley / http://github.com/WestLangley */ - function RectAreaLightHelper( light ) { + function RectAreaLightHelper( light, color ) { Object3D.call( this ); @@ -41082,13 +43096,17 @@ this.matrix = light.matrixWorld; this.matrixAutoUpdate = false; - var material = new LineBasicMaterial( { color: light.color } ); + this.color = color; + + var material = new LineBasicMaterial( { fog: false } ); var geometry = new BufferGeometry(); geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 5 * 3 ), 3 ) ); - this.add( new Line( geometry, material ) ); + this.line = new Line( geometry, material ); + this.add( this.line ); + this.update(); @@ -41106,30 +43124,34 @@ RectAreaLightHelper.prototype.update = function () { - var line = this.children[ 0 ]; - - // update material - - line.material.color.copy( this.light.color ); - // calculate new dimensions of the helper var hx = this.light.width * 0.5; var hy = this.light.height * 0.5; - var position = line.geometry.attributes.position; + var position = this.line.geometry.attributes.position; var array = position.array; // update vertices - array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0; - array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0; - array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0; - array[ 9 ] = - hx; array[ 10 ] = - hy; array[ 11 ] = 0; - array[ 12 ] = hx; array[ 13 ] = - hy; array[ 14 ] = 0; + array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0; + array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0; + array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0; + array[ 9 ] = - hx; array[ 10 ] = - hy; array[ 11 ] = 0; + array[ 12 ] = hx; array[ 13 ] = - hy; array[ 14 ] = 0; position.needsUpdate = true; + if ( this.color !== undefined ) { + + this.line.material.color.set( this.color ); + + } else { + + this.line.material.color.copy( this.light.color ); + + } + }; /** @@ -41138,7 +43160,7 @@ * @author Mugen87 / https://github.com/Mugen87 */ - function HemisphereLightHelper( light, size ) { + function HemisphereLightHelper( light, size, color ) { Object3D.call( this ); @@ -41148,17 +43170,20 @@ this.matrix = light.matrixWorld; this.matrixAutoUpdate = false; + this.color = color; + var geometry = new OctahedronBufferGeometry( size ); geometry.rotateY( Math.PI * 0.5 ); - var material = new MeshBasicMaterial( { vertexColors: VertexColors, wireframe: true } ); + this.material = new MeshBasicMaterial( { wireframe: true, fog: false } ); + if ( this.color === undefined ) this.material.vertexColors = VertexColors; var position = geometry.getAttribute( 'position' ); var colors = new Float32Array( position.count * 3 ); geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) ); - this.add( new Mesh( geometry, material ) ); + this.add( new Mesh( geometry, this.material ) ); this.update(); @@ -41185,23 +43210,31 @@ var mesh = this.children[ 0 ]; - var colors = mesh.geometry.getAttribute( 'color' ); + if ( this.color !== undefined ) { - color1.copy( this.light.color ); - color2.copy( this.light.groundColor ); + this.material.color.set( this.color ); - for ( var i = 0, l = colors.count; i < l; i ++ ) { + } else { + + var colors = mesh.geometry.getAttribute( 'color' ); + + color1.copy( this.light.color ); + color2.copy( this.light.groundColor ); + + for ( var i = 0, l = colors.count; i < l; i ++ ) { - var color = ( i < ( l / 2 ) ) ? color1 : color2; + var color = ( i < ( l / 2 ) ) ? color1 : color2; - colors.setXYZ( i, color.r, color.g, color.b ); + colors.setXYZ( i, color.r, color.g, color.b ); + + } + + colors.needsUpdate = true; } mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() ); - colors.needsUpdate = true; - }; }(); @@ -41340,7 +43373,7 @@ /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley - */ + */ function FaceNormalsHelper( object, size, hex, linewidth ) { @@ -41452,7 +43485,7 @@ * @author WestLangley / http://github.com/WestLangley */ - function DirectionalLightHelper( light, size ) { + function DirectionalLightHelper( light, size, color ) { Object3D.call( this ); @@ -41462,25 +43495,29 @@ this.matrix = light.matrixWorld; this.matrixAutoUpdate = false; + this.color = color; + if ( size === undefined ) size = 1; var geometry = new BufferGeometry(); geometry.addAttribute( 'position', new Float32BufferAttribute( [ - - size, size, 0, - size, size, 0, - size, - size, 0, + - size, size, 0, + size, size, 0, + size, - size, 0, - size, - size, 0, - - size, size, 0 + - size, size, 0 ], 3 ) ); var material = new LineBasicMaterial( { fog: false } ); - this.add( new Line( geometry, material ) ); + this.lightPlane = new Line( geometry, material ); + this.add( this.lightPlane ); geometry = new BufferGeometry(); geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); - this.add( new Line( geometry, material )); + this.targetLine = new Line( geometry, material ); + this.add( this.targetLine ); this.update(); @@ -41491,13 +43528,10 @@ DirectionalLightHelper.prototype.dispose = function () { - var lightPlane = this.children[ 0 ]; - var targetLine = this.children[ 1 ]; - - lightPlane.geometry.dispose(); - lightPlane.material.dispose(); - targetLine.geometry.dispose(); - targetLine.material.dispose(); + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); }; @@ -41513,14 +43547,22 @@ v2.setFromMatrixPosition( this.light.target.matrixWorld ); v3.subVectors( v2, v1 ); - var lightPlane = this.children[ 0 ]; - var targetLine = this.children[ 1 ]; + this.lightPlane.lookAt( v3 ); + + if ( this.color !== undefined ) { - lightPlane.lookAt( v3 ); - lightPlane.material.color.copy( this.light.color ); + this.lightPlane.material.color.set( this.color ); + this.targetLine.material.color.set( this.color ); - targetLine.lookAt( v3 ); - targetLine.scale.z = v3.length(); + } else { + + this.lightPlane.material.color.copy( this.light.color ); + this.targetLine.material.color.copy( this.light.color ); + + } + + this.targetLine.lookAt( v3 ); + this.targetLine.scale.z = v3.length(); }; @@ -41556,50 +43598,50 @@ // near - addLine( "n1", "n2", colorFrustum ); - addLine( "n2", "n4", colorFrustum ); - addLine( "n4", "n3", colorFrustum ); - addLine( "n3", "n1", colorFrustum ); + addLine( 'n1', 'n2', colorFrustum ); + addLine( 'n2', 'n4', colorFrustum ); + addLine( 'n4', 'n3', colorFrustum ); + addLine( 'n3', 'n1', colorFrustum ); // far - addLine( "f1", "f2", colorFrustum ); - addLine( "f2", "f4", colorFrustum ); - addLine( "f4", "f3", colorFrustum ); - addLine( "f3", "f1", colorFrustum ); + addLine( 'f1', 'f2', colorFrustum ); + addLine( 'f2', 'f4', colorFrustum ); + addLine( 'f4', 'f3', colorFrustum ); + addLine( 'f3', 'f1', colorFrustum ); // sides - addLine( "n1", "f1", colorFrustum ); - addLine( "n2", "f2", colorFrustum ); - addLine( "n3", "f3", colorFrustum ); - addLine( "n4", "f4", colorFrustum ); + addLine( 'n1', 'f1', colorFrustum ); + addLine( 'n2', 'f2', colorFrustum ); + addLine( 'n3', 'f3', colorFrustum ); + addLine( 'n4', 'f4', colorFrustum ); // cone - addLine( "p", "n1", colorCone ); - addLine( "p", "n2", colorCone ); - addLine( "p", "n3", colorCone ); - addLine( "p", "n4", colorCone ); + addLine( 'p', 'n1', colorCone ); + addLine( 'p', 'n2', colorCone ); + addLine( 'p', 'n3', colorCone ); + addLine( 'p', 'n4', colorCone ); // up - addLine( "u1", "u2", colorUp ); - addLine( "u2", "u3", colorUp ); - addLine( "u3", "u1", colorUp ); + addLine( 'u1', 'u2', colorUp ); + addLine( 'u2', 'u3', colorUp ); + addLine( 'u3', 'u1', colorUp ); // target - addLine( "c", "t", colorTarget ); - addLine( "p", "c", colorCross ); + addLine( 'c', 't', colorTarget ); + addLine( 'p', 'c', colorCross ); // cross - addLine( "cn1", "cn2", colorCross ); - addLine( "cn3", "cn4", colorCross ); + addLine( 'cn1', 'cn2', colorCross ); + addLine( 'cn3', 'cn4', colorCross ); - addLine( "cf1", "cf2", colorCross ); - addLine( "cf3", "cf4", colorCross ); + addLine( 'cf1', 'cf2', colorCross ); + addLine( 'cf3', 'cf4', colorCross ); function addLine( a, b, color ) { @@ -41684,40 +43726,40 @@ // center / target - setPoint( "c", 0, 0, - 1 ); - setPoint( "t", 0, 0, 1 ); + setPoint( 'c', 0, 0, - 1 ); + setPoint( 't', 0, 0, 1 ); // near - setPoint( "n1", - w, - h, - 1 ); - setPoint( "n2", w, - h, - 1 ); - setPoint( "n3", - w, h, - 1 ); - setPoint( "n4", w, h, - 1 ); + setPoint( 'n1', - w, - h, - 1 ); + setPoint( 'n2', w, - h, - 1 ); + setPoint( 'n3', - w, h, - 1 ); + setPoint( 'n4', w, h, - 1 ); // far - setPoint( "f1", - w, - h, 1 ); - setPoint( "f2", w, - h, 1 ); - setPoint( "f3", - w, h, 1 ); - setPoint( "f4", w, h, 1 ); + setPoint( 'f1', - w, - h, 1 ); + setPoint( 'f2', w, - h, 1 ); + setPoint( 'f3', - w, h, 1 ); + setPoint( 'f4', w, h, 1 ); // up - setPoint( "u1", w * 0.7, h * 1.1, - 1 ); - setPoint( "u2", - w * 0.7, h * 1.1, - 1 ); - setPoint( "u3", 0, h * 2, - 1 ); + setPoint( 'u1', w * 0.7, h * 1.1, - 1 ); + setPoint( 'u2', - w * 0.7, h * 1.1, - 1 ); + setPoint( 'u3', 0, h * 2, - 1 ); // cross - setPoint( "cf1", - w, 0, 1 ); - setPoint( "cf2", w, 0, 1 ); - setPoint( "cf3", 0, - h, 1 ); - setPoint( "cf4", 0, h, 1 ); + setPoint( 'cf1', - w, 0, 1 ); + setPoint( 'cf2', w, 0, 1 ); + setPoint( 'cf3', 0, - h, 1 ); + setPoint( 'cf4', 0, h, 1 ); - setPoint( "cn1", - w, 0, - 1 ); - setPoint( "cn2", w, 0, - 1 ); - setPoint( "cn3", 0, - h, - 1 ); - setPoint( "cn4", 0, h, - 1 ); + setPoint( 'cn1', - w, 0, - 1 ); + setPoint( 'cn2', w, 0, - 1 ); + setPoint( 'cn3', 0, - h, - 1 ); + setPoint( 'cn4', 0, h, - 1 ); geometry.getAttribute( 'position' ).needsUpdate = true; @@ -41796,10 +43838,10 @@ var position = this.geometry.attributes.position; var array = position.array; - array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z; - array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z; - array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z; - array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z; + array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z; + array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z; + array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z; + array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z; array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z; array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z; array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z; @@ -41822,6 +43864,104 @@ }; + /** + * @author WestLangley / http://github.com/WestLangley + */ + + function Box3Helper( box, hex ) { + + this.type = 'Box3Helper'; + + this.box = box; + + var color = ( hex !== undefined ) ? hex : 0xffff00; + + var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); + + var positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ]; + + var geometry = new BufferGeometry(); + + geometry.setIndex( new BufferAttribute( indices, 1 ) ); + + geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + + LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) ); + + this.geometry.computeBoundingSphere(); + + } + + Box3Helper.prototype = Object.create( LineSegments.prototype ); + Box3Helper.prototype.constructor = Box3Helper; + + Box3Helper.prototype.updateMatrixWorld = function ( force ) { + + var box = this.box; + + if ( box.isEmpty() ) return; + + box.getCenter( this.position ); + + box.getSize( this.scale ); + + this.scale.multiplyScalar( 0.5 ); + + Object3D.prototype.updateMatrixWorld.call( this, force ); + + }; + + /** + * @author WestLangley / http://github.com/WestLangley + */ + + function PlaneHelper( plane, size, hex ) { + + this.type = 'PlaneHelper'; + + this.plane = plane; + + this.size = ( size === undefined ) ? 1 : size; + + var color = ( hex !== undefined ) ? hex : 0xffff00; + + var positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ]; + + var geometry = new BufferGeometry(); + geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + geometry.computeBoundingSphere(); + + Line.call( this, geometry, new LineBasicMaterial( { color: color } ) ); + + // + + var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ]; + + var geometry2 = new BufferGeometry(); + geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); + geometry2.computeBoundingSphere(); + + this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) ); + + } + + PlaneHelper.prototype = Object.create( Line.prototype ); + PlaneHelper.prototype.constructor = PlaneHelper; + + PlaneHelper.prototype.updateMatrixWorld = function ( force ) { + + var scale = - this.plane.constant; + + if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter + + this.scale.set( 0.5 * this.size, 0.5 * this.size, scale ); + + this.lookAt( this.plane.normal ); + + Object3D.prototype.updateMatrixWorld.call( this, force ); + + }; + /** * @author WestLangley / http://github.com/WestLangley * @author zz85 / http://github.com/zz85 @@ -41937,20 +44077,20 @@ * @author mrdoob / http://mrdoob.com/ */ - function AxisHelper( size ) { + function AxesHelper( size ) { size = size || 1; var vertices = [ - 0, 0, 0, size, 0, 0, - 0, 0, 0, 0, size, 0, - 0, 0, 0, 0, 0, size + 0, 0, 0, size, 0, 0, + 0, 0, 0, 0, size, 0, + 0, 0, 0, 0, 0, size ]; var colors = [ - 1, 0, 0, 1, 0.6, 0, - 0, 1, 0, 0.6, 1, 0, - 0, 0, 1, 0, 0.6, 1 + 1, 0, 0, 1, 0.6, 0, + 0, 1, 0, 0.6, 1, 0, + 0, 0, 1, 0, 0.6, 1 ]; var geometry = new BufferGeometry(); @@ -41963,314 +44103,8 @@ } - AxisHelper.prototype = Object.create( LineSegments.prototype ); - AxisHelper.prototype.constructor = AxisHelper; - - /** - * @author zz85 https://github.com/zz85 - * - * Centripetal CatmullRom Curve - which is useful for avoiding - * cusps and self-intersections in non-uniform catmull rom curves. - * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf - * - * curve.type accepts centripetal(default), chordal and catmullrom - * curve.tension is used for catmullrom which defaults to 0.5 - */ - - - /* - Based on an optimized c++ solution in - - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/ - - http://ideone.com/NoEbVM - - This CubicPoly class could be used for reusing some variables and calculations, - but for three.js curve use, it could be possible inlined and flatten into a single function call - which can be placed in CurveUtils. - */ - - function CubicPoly() { - - var c0 = 0, c1 = 0, c2 = 0, c3 = 0; - - /* - * Compute coefficients for a cubic polynomial - * p(s) = c0 + c1*s + c2*s^2 + c3*s^3 - * such that - * p(0) = x0, p(1) = x1 - * and - * p'(0) = t0, p'(1) = t1. - */ - function init( x0, x1, t0, t1 ) { - - c0 = x0; - c1 = t0; - c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; - c3 = 2 * x0 - 2 * x1 + t0 + t1; - - } - - return { - - initCatmullRom: function ( x0, x1, x2, x3, tension ) { - - init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); - - }, - - initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) { - - // compute tangents when parameterized in [t1,t2] - var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; - var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; - - // rescale tangents for parametrization in [0,1] - t1 *= dt1; - t2 *= dt1; - - init( x1, x2, t1, t2 ); - - }, - - calc: function ( t ) { - - var t2 = t * t; - var t3 = t2 * t; - return c0 + c1 * t + c2 * t2 + c3 * t3; - - } - - }; - - } - - // - - var tmp = new Vector3(); - var px = new CubicPoly(); - var py = new CubicPoly(); - var pz = new CubicPoly(); - - function CatmullRomCurve3( points ) { - - Curve.call( this ); - - if ( points.length < 2 ) console.warn( 'THREE.CatmullRomCurve3: Points array needs at least two entries.' ); - - this.points = points || []; - this.closed = false; - - } - - CatmullRomCurve3.prototype = Object.create( Curve.prototype ); - CatmullRomCurve3.prototype.constructor = CatmullRomCurve3; - - CatmullRomCurve3.prototype.getPoint = function ( t ) { - - var points = this.points; - var l = points.length; - - var point = ( l - ( this.closed ? 0 : 1 ) ) * t; - var intPoint = Math.floor( point ); - var weight = point - intPoint; - - if ( this.closed ) { - - intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length; - - } else if ( weight === 0 && intPoint === l - 1 ) { - - intPoint = l - 2; - weight = 1; - - } - - var p0, p1, p2, p3; // 4 points - - if ( this.closed || intPoint > 0 ) { - - p0 = points[ ( intPoint - 1 ) % l ]; - - } else { - - // extrapolate first point - tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); - p0 = tmp; - - } - - p1 = points[ intPoint % l ]; - p2 = points[ ( intPoint + 1 ) % l ]; - - if ( this.closed || intPoint + 2 < l ) { - - p3 = points[ ( intPoint + 2 ) % l ]; - - } else { - - // extrapolate last point - tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); - p3 = tmp; - - } - - if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) { - - // init Centripetal / Chordal Catmull-Rom - var pow = this.type === 'chordal' ? 0.5 : 0.25; - var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); - var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); - var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); - - // safety check for repeated points - if ( dt1 < 1e-4 ) dt1 = 1.0; - if ( dt0 < 1e-4 ) dt0 = dt1; - if ( dt2 < 1e-4 ) dt2 = dt1; - - px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 ); - py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 ); - pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 ); - - } else if ( this.type === 'catmullrom' ) { - - var tension = this.tension !== undefined ? this.tension : 0.5; - px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension ); - py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension ); - pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension ); - - } - - return new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) ); - - }; - - function CubicBezierCurve3( v0, v1, v2, v3 ) { - - Curve.call( this ); - - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - this.v3 = v3; - - } - - CubicBezierCurve3.prototype = Object.create( Curve.prototype ); - CubicBezierCurve3.prototype.constructor = CubicBezierCurve3; - - CubicBezierCurve3.prototype.getPoint = function ( t ) { - - var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; - - return new Vector3( - CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), - CubicBezier( t, v0.y, v1.y, v2.y, v3.y ), - CubicBezier( t, v0.z, v1.z, v2.z, v3.z ) - ); - - }; - - function QuadraticBezierCurve3( v0, v1, v2 ) { - - Curve.call( this ); - - this.v0 = v0; - this.v1 = v1; - this.v2 = v2; - - } - - QuadraticBezierCurve3.prototype = Object.create( Curve.prototype ); - QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3; - - QuadraticBezierCurve3.prototype.getPoint = function ( t ) { - - var v0 = this.v0, v1 = this.v1, v2 = this.v2; - - return new Vector3( - QuadraticBezier( t, v0.x, v1.x, v2.x ), - QuadraticBezier( t, v0.y, v1.y, v2.y ), - QuadraticBezier( t, v0.z, v1.z, v2.z ) - ); - - }; - - function LineCurve3( v1, v2 ) { - - Curve.call( this ); - - this.v1 = v1; - this.v2 = v2; - - } - - LineCurve3.prototype = Object.create( Curve.prototype ); - LineCurve3.prototype.constructor = LineCurve3; - - LineCurve3.prototype.getPoint = function ( t ) { - - if ( t === 1 ) { - - return this.v2.clone(); - - } - - var vector = new Vector3(); - - vector.subVectors( this.v2, this.v1 ); // diff - vector.multiplyScalar( t ); - vector.add( this.v1 ); - - return vector; - - }; - - function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - - EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - - } - - ArcCurve.prototype = Object.create( EllipseCurve.prototype ); - ArcCurve.prototype.constructor = ArcCurve; - - /** - * @author alteredq / http://alteredqualia.com/ - */ - - var SceneUtils = { - - createMultiMaterialObject: function ( geometry, materials ) { - - var group = new Group(); - - for ( var i = 0, l = materials.length; i < l; i ++ ) { - - group.add( new Mesh( geometry, materials[ i ] ) ); - - } - - return group; - - }, - - detach: function ( child, parent, scene ) { - - child.applyMatrix( parent.matrixWorld ); - parent.remove( child ); - scene.add( child ); - - }, - - attach: function ( child, scene, parent ) { - - child.applyMatrix( new Matrix4().getInverse( parent.matrixWorld ) ); - - scene.remove( child ); - parent.add( child ); - - } - - }; + AxesHelper.prototype = Object.create( LineSegments.prototype ); + AxesHelper.prototype.constructor = AxesHelper; /** * @author mrdoob / http://mrdoob.com/ @@ -42447,6 +44281,64 @@ // + Object.assign( CurvePath.prototype, { + + createPointsGeometry: function ( divisions ) { + + console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' ); + + // generate geometry from path points (for Line or Points objects) + + var pts = this.getPoints( divisions ); + return this.createGeometry( pts ); + + }, + + createSpacedPointsGeometry: function ( divisions ) { + + console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' ); + + // generate geometry from equidistant sampling along the path + + var pts = this.getSpacedPoints( divisions ); + return this.createGeometry( pts ); + + }, + + createGeometry: function ( points ) { + + console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' ); + + var geometry = new Geometry(); + + for ( var i = 0, l = points.length; i < l; i ++ ) { + + var point = points[ i ]; + geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); + + } + + return geometry; + + } + + } ); + + // + + Object.assign( Path.prototype, { + + fromPoints: function ( points ) { + + console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' ); + this.setFromPoints( points ); + + } + + } ); + + // + function ClosedSplineCurve3( points ) { console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' ); @@ -42487,17 +44379,17 @@ Object.assign( Spline.prototype, { - initFromArray: function ( a ) { + initFromArray: function ( /* a */ ) { console.error( 'THREE.Spline: .initFromArray() has been removed.' ); }, - getControlPointsArray: function ( optionalTarget ) { + getControlPointsArray: function ( /* optionalTarget */ ) { console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' ); }, - reparametrizeByArcLength: function ( samplingCoef ) { + reparametrizeByArcLength: function ( /* samplingCoef */ ) { console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' ); @@ -42506,6 +44398,14 @@ } ); // + + function AxisHelper( size ) { + + console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' ); + return new AxesHelper( size ); + + } + function BoundingBoxHelper( object, color ) { console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' ); @@ -42529,7 +44429,7 @@ SkeletonHelper.prototype.update = function () { console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' ); - + }; function WireframeHelper( object, hex ) { @@ -42541,6 +44441,17 @@ // + Object.assign( Loader.prototype, { + + extractUrlBase: function ( url ) { + + console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' ); + return LoaderUtils.extractUrlBase( url ); + + } + + } ); + function XHRLoader( manager ) { console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' ); @@ -42626,12 +44537,30 @@ }; - _Math.random16 = function () { + Object.assign( _Math, { - console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' ); - return Math.random(); + random16: function () { - }; + console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' ); + return Math.random(); + + }, + + nearestPowerOfTwo: function ( value ) { + + console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' ); + return _Math.floorPowerOfTwo( value ); + + }, + + nextPowerOfTwo: function ( value ) { + + console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' ); + return _Math.ceilPowerOfTwo( value ); + + } + + } ); Object.assign( Matrix3.prototype, { @@ -42647,18 +44576,18 @@ return vector.applyMatrix3( this ); }, - multiplyVector3Array: function ( a ) { + multiplyVector3Array: function ( /* a */ ) { - console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' ); + console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' ); }, - applyToBuffer: function( buffer, offset, length ) { + applyToBuffer: function ( buffer /*, offset, length */ ) { console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' ); return this.applyToBufferAttribute( buffer ); }, - applyToVector3Array: function( array, offset, length ) { + applyToVector3Array: function ( /* array, offset, length */ ) { console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' ); @@ -42716,9 +44645,9 @@ return vector.applyMatrix4( this ); }, - multiplyVector3Array: function ( a ) { + multiplyVector3Array: function ( /* a */ ) { - console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' ); + console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' ); }, rotateAxis: function ( v ) { @@ -42758,18 +44687,18 @@ console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); }, - applyToBuffer: function( buffer, offset, length ) { + applyToBuffer: function ( buffer /*, offset, length */ ) { console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' ); return this.applyToBufferAttribute( buffer ); }, - applyToVector3Array: function( array, offset, length ) { + applyToVector3Array: function ( /* array, offset, length */ ) { console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' ); }, - makeFrustum: function( left, right, bottom, top, near, far ) { + makeFrustum: function ( left, right, bottom, top, near, far ) { console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' ); return this.makePerspective( left, right, top, bottom, near, far ); @@ -42815,8 +44744,66 @@ } ); + Object.assign( Triangle.prototype, { + + area: function () { + + console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' ); + return this.getArea(); + + }, + barycoordFromPoint: function ( point, target ) { + + console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); + return this.getBarycoord( point, target ); + + }, + midpoint: function ( target ) { + + console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' ); + return this.getMidpoint( target ); + + }, + normal: function ( target ) { + + console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); + return this.getNormal( target ); + + }, + plane: function ( target ) { + + console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' ); + return this.getPlane( target ); + + } + + } ); + + Object.assign( Triangle, { + + barycoordFromPoint: function ( point, a, b, c, target ) { + + console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); + return Triangle.getBarycoord( point, a, b, c, target ); + + }, + normal: function ( a, b, c, target ) { + + console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); + return Triangle.getNormal( a, b, c, target ); + + } + + } ); + Object.assign( Shape.prototype, { + extractAllPoints: function ( divisions ) { + + console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' ); + return this.extractPoints( divisions ); + + }, extrude: function ( options ) { console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' ); @@ -42836,9 +44823,21 @@ fromAttribute: function ( attribute, index, offset ) { - console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' ); + console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' ); return this.fromBufferAttribute( attribute, index, offset ); + }, + distanceToManhattan: function ( v ) { + + console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); + return this.manhattanDistanceTo( v ); + + }, + lengthManhattan: function () { + + console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' ); + return this.manhattanLength(); + } } ); @@ -42881,9 +44880,21 @@ }, fromAttribute: function ( attribute, index, offset ) { - console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' ); + console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' ); return this.fromBufferAttribute( attribute, index, offset ); + }, + distanceToManhattan: function ( v ) { + + console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); + return this.manhattanDistanceTo( v ); + + }, + lengthManhattan: function () { + + console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' ); + return this.manhattanLength(); + } } ); @@ -42892,20 +44903,35 @@ fromAttribute: function ( attribute, index, offset ) { - console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' ); + console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' ); return this.fromBufferAttribute( attribute, index, offset ); + }, + lengthManhattan: function () { + + console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' ); + return this.manhattanLength(); + } } ); // - Geometry.prototype.computeTangents = function () { + Object.assign( Geometry.prototype, { - console.warn( 'THREE.Geometry: .computeTangents() has been removed.' ); + computeTangents: function () { - }; + console.error( 'THREE.Geometry: .computeTangents() has been removed.' ); + + }, + computeLineDistances: function () { + + console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' ); + + } + + } ); Object.assign( Object3D.prototype, { @@ -42925,6 +44951,11 @@ console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); return this.translateOnAxis( axis, distance ); + }, + getWorldRotation: function () { + + console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' ); + } } ); @@ -43134,6 +45165,11 @@ return this.array.length; } + }, + copyIndicesArray: function ( /* indices */ ) { + + console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' ); + } } ); @@ -43241,6 +45277,20 @@ console.warn( 'THREE.Material: .wrapRGB has been removed.' ); return new Color(); + } + }, + + shading: { + get: function () { + + console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); + + }, + set: function ( value ) { + + console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); + this.flatShading = ( value === FlatShading ); + } } @@ -43294,6 +45344,27 @@ }, + getMaxAnisotropy: function () { + + console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' ); + return this.capabilities.getMaxAnisotropy(); + + }, + + getPrecision: function () { + + console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' ); + return this.capabilities.precision; + + }, + + resetGLState: function () { + + console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' ); + return this.state.reset(); + + }, + supportsFloatTextures: function () { console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' ); @@ -43367,6 +45438,11 @@ console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' ); + }, + setFaceCulling: function () { + + console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' ); + } } ); @@ -43402,13 +45478,13 @@ shadowMapCullFace: { get: function () { - return this.shadowMap.cullFace; + console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); + return undefined; }, - set: function ( value ) { + set: function ( /* value */ ) { - console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' ); - this.shadowMap.cullFace = value; + console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); } } @@ -43419,14 +45495,39 @@ cullFace: { get: function () { - return this.renderReverseSided ? CullFaceFront : CullFaceBack; + console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); + return undefined; }, - set: function ( cullFace ) { + set: function ( /* cullFace */ ) { - var value = ( cullFace !== CullFaceBack ); - console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." ); - this.renderReverseSided = value; + console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); + + } + }, + renderReverseSided: { + get: function () { + + console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); + return undefined; + + }, + set: function () { + + console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); + + } + }, + renderSingleSided: { + get: function () { + + console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); + return undefined; + + }, + set: function () { + + console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); } } @@ -43582,6 +45683,20 @@ // + Object.defineProperties( WebVRManager.prototype, { + + standing: { + set: function ( /* value */ ) { + + console.warn( 'THREE.WebVRManager: .standing has been removed.' ); + + } + } + + } ); + + // + Audio.prototype.load = function ( file ) { console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' ); @@ -43605,6 +45720,15 @@ // + CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) { + + console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' ); + return this.update( renderer, scene ); + + }; + + // + var GeometryUtils = { merge: function ( geometry1, geometry2, materialIndexOffset ) { @@ -43724,6 +45848,38 @@ } + // + + var SceneUtils = { + + createMultiMaterialObject: function ( /* geometry, materials */ ) { + + console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' ); + + }, + + detach: function ( /* child, parent, scene */ ) { + + console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' ); + + }, + + attach: function ( /* child, scene, parent */ ) { + + console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' ); + + } + + }; + + // + + function LensFlare() { + + console.error( 'THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js' ); + + } + exports.WebGLRenderTargetCube = WebGLRenderTargetCube; exports.WebGLRenderTarget = WebGLRenderTarget; exports.WebGLRenderer = WebGLRenderer; @@ -43734,7 +45890,6 @@ exports.FogExp2 = FogExp2; exports.Fog = Fog; exports.Scene = Scene; - exports.LensFlare = LensFlare; exports.Sprite = Sprite; exports.LOD = LOD; exports.SkinnedMesh = SkinnedMesh; @@ -43764,9 +45919,11 @@ exports.LoadingManager = LoadingManager; exports.JSONLoader = JSONLoader; exports.ImageLoader = ImageLoader; + exports.ImageBitmapLoader = ImageBitmapLoader; exports.FontLoader = FontLoader; exports.FileLoader = FileLoader; exports.Loader = Loader; + exports.LoaderUtils = LoaderUtils; exports.Cache = Cache; exports.AudioLoader = AudioLoader; exports.SpotLightShadow = SpotLightShadow; @@ -43806,7 +45963,6 @@ exports.Uniform = Uniform; exports.InstancedBufferGeometry = InstancedBufferGeometry; exports.BufferGeometry = BufferGeometry; - exports.GeometryIdCount = GeometryIdCount; exports.Geometry = Geometry; exports.InterleavedBufferAttribute = InterleavedBufferAttribute; exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer; @@ -43842,7 +45998,6 @@ exports.Vector2 = Vector2; exports.Quaternion = Quaternion; exports.Color = Color; - exports.MorphBlendMesh = MorphBlendMesh; exports.ImmediateRenderObject = ImmediateRenderObject; exports.VertexNormalsHelper = VertexNormalsHelper; exports.SpotLightHelper = SpotLightHelper; @@ -43856,18 +46011,10 @@ exports.DirectionalLightHelper = DirectionalLightHelper; exports.CameraHelper = CameraHelper; exports.BoxHelper = BoxHelper; + exports.Box3Helper = Box3Helper; + exports.PlaneHelper = PlaneHelper; exports.ArrowHelper = ArrowHelper; - exports.AxisHelper = AxisHelper; - exports.CatmullRomCurve3 = CatmullRomCurve3; - exports.CubicBezierCurve3 = CubicBezierCurve3; - exports.QuadraticBezierCurve3 = QuadraticBezierCurve3; - exports.LineCurve3 = LineCurve3; - exports.ArcCurve = ArcCurve; - exports.EllipseCurve = EllipseCurve; - exports.SplineCurve = SplineCurve; - exports.CubicBezierCurve = CubicBezierCurve; - exports.QuadraticBezierCurve = QuadraticBezierCurve; - exports.LineCurve = LineCurve; + exports.AxesHelper = AxesHelper; exports.Shape = Shape; exports.Path = Path; exports.ShapePath = ShapePath; @@ -43875,7 +46022,7 @@ exports.CurvePath = CurvePath; exports.Curve = Curve; exports.ShapeUtils = ShapeUtils; - exports.SceneUtils = SceneUtils; + exports.WebGLUtils = WebGLUtils; exports.WireframeGeometry = WireframeGeometry; exports.ParametricGeometry = ParametricGeometry; exports.ParametricBufferGeometry = ParametricBufferGeometry; @@ -43930,6 +46077,7 @@ exports.MeshNormalMaterial = MeshNormalMaterial; exports.MeshLambertMaterial = MeshLambertMaterial; exports.MeshDepthMaterial = MeshDepthMaterial; + exports.MeshDistanceMaterial = MeshDistanceMaterial; exports.MeshBasicMaterial = MeshBasicMaterial; exports.LineDashedMaterial = LineDashedMaterial; exports.LineBasicMaterial = LineBasicMaterial; @@ -43944,6 +46092,16 @@ exports.Uint8BufferAttribute = Uint8BufferAttribute; exports.Int8BufferAttribute = Int8BufferAttribute; exports.BufferAttribute = BufferAttribute; + exports.ArcCurve = ArcCurve; + exports.CatmullRomCurve3 = CatmullRomCurve3; + exports.CubicBezierCurve = CubicBezierCurve; + exports.CubicBezierCurve3 = CubicBezierCurve3; + exports.EllipseCurve = EllipseCurve; + exports.LineCurve = LineCurve; + exports.LineCurve3 = LineCurve3; + exports.QuadraticBezierCurve = QuadraticBezierCurve; + exports.QuadraticBezierCurve3 = QuadraticBezierCurve3; + exports.SplineCurve = SplineCurve; exports.REVISION = REVISION; exports.MOUSE = MOUSE; exports.CullFaceNone = CullFaceNone; @@ -44047,6 +46205,20 @@ exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format; exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format; exports.RGB_ETC1_Format = RGB_ETC1_Format; + exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format; + exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format; + exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format; + exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format; + exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format; + exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format; + exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format; + exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format; + exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format; + exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format; + exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format; + exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format; + exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format; + exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format; exports.LoopOnce = LoopOnce; exports.LoopRepeat = LoopRepeat; exports.LoopPingPong = LoopPingPong; @@ -44095,6 +46267,7 @@ exports.ClosedSplineCurve3 = ClosedSplineCurve3; exports.SplineCurve3 = SplineCurve3; exports.Spline = Spline; + exports.AxisHelper = AxisHelper; exports.BoundingBoxHelper = BoundingBoxHelper; exports.EdgesHelper = EdgesHelper; exports.WireframeHelper = WireframeHelper; @@ -44104,6 +46277,8 @@ exports.ImageUtils = ImageUtils; exports.Projector = Projector; exports.CanvasRenderer = CanvasRenderer; + exports.SceneUtils = SceneUtils; + exports.LensFlare = LensFlare; Object.defineProperty(exports, '__esModule', { value: true }); diff --git a/demo/libs/three.min.js b/demo/libs/three.min.js index 61b0f39..96fc18a 100644 --- a/demo/libs/three.min.js +++ b/demo/libs/three.min.js @@ -1,874 +1,927 @@ // threejs.org/license -(function(l,xa){"object"===typeof exports&&"undefined"!==typeof module?xa(exports):"function"===typeof define&&define.amd?define(["exports"],xa):xa(l.THREE=l.THREE||{})})(this,function(l){function xa(){}function C(a,b){this.x=a||0;this.y=b||0}function ba(a,b,c,d,e,f,g,h,k,m){Object.defineProperty(this,"id",{value:hf++});this.uuid=Y.generateUUID();this.name="";this.image=void 0!==a?a:ba.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=void 0!==b?b:ba.DEFAULT_MAPPING;this.wrapS=void 0!==c?c:1001;this.wrapT= -void 0!==d?d:1001;this.magFilter=void 0!==e?e:1006;this.minFilter=void 0!==f?f:1008;this.anisotropy=void 0!==k?k:1;this.format=void 0!==g?g:1023;this.type=void 0!==h?h:1009;this.offset=new C(0,0);this.repeat=new C(1,1);this.generateMipmaps=!0;this.premultiplyAlpha=!1;this.flipY=!0;this.unpackAlignment=4;this.encoding=void 0!==m?m:3E3;this.version=0;this.onUpdate=null}function fa(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=void 0!==d?d:1}function Cb(a,b,c){this.uuid=Y.generateUUID();this.width= -a;this.height=b;this.scissor=new fa(0,0,a,b);this.scissorTest=!1;this.viewport=new fa(0,0,a,b);c=c||{};void 0===c.minFilter&&(c.minFilter=1006);this.texture=new ba(void 0,void 0,c.wrapS,c.wrapT,c.magFilter,c.minFilter,c.format,c.type,c.anisotropy,c.encoding);this.depthBuffer=void 0!==c.depthBuffer?c.depthBuffer:!0;this.stencilBuffer=void 0!==c.stencilBuffer?c.stencilBuffer:!0;this.depthTexture=void 0!==c.depthTexture?c.depthTexture:null}function Db(a,b,c){Cb.call(this,a,b,c);this.activeMipMapLevel= -this.activeCubeFace=0}function oa(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._w=void 0!==d?d:1}function n(a,b,c){this.x=a||0;this.y=b||0;this.z=c||0}function K(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];0=d||0 0 ) {\nfloat depth = gl_FragCoord.z / gl_FragCoord.w;\nfloat fogFactor = 0.0;\nif ( fogType == 1 ) {\nfogFactor = smoothstep( fogNear, fogFar, depth );\n} else {\nconst float LOG2 = 1.442695;\nfogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );\nfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n}\ngl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );\n}\n}"].join("\n")); -w.compileShader(P);w.compileShader(M);w.attachShader(ka,P);w.attachShader(ka,M);w.linkProgram(ka);O=ka;x=w.getAttribLocation(O,"position");u=w.getAttribLocation(O,"uv");c=w.getUniformLocation(O,"uvOffset");d=w.getUniformLocation(O,"uvScale");e=w.getUniformLocation(O,"rotation");f=w.getUniformLocation(O,"scale");g=w.getUniformLocation(O,"color");h=w.getUniformLocation(O,"map");k=w.getUniformLocation(O,"opacity");m=w.getUniformLocation(O,"modelViewMatrix");q=w.getUniformLocation(O,"projectionMatrix"); -v=w.getUniformLocation(O,"fogType");p=w.getUniformLocation(O,"fogDensity");r=w.getUniformLocation(O,"fogNear");l=w.getUniformLocation(O,"fogFar");t=w.getUniformLocation(O,"fogColor");y=w.getUniformLocation(O,"alphaTest");ka=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");ka.width=8;ka.height=8;P=ka.getContext("2d");P.fillStyle="white";P.fillRect(0,0,8,8);aa=new ba(ka);aa.needsUpdate=!0}w.useProgram(O);I.initAttributes();I.enableAttribute(x);I.enableAttribute(u);I.disableUnusedAttributes(); -I.disable(w.CULL_FACE);I.enable(w.BLEND);w.bindBuffer(w.ARRAY_BUFFER,W);w.vertexAttribPointer(x,2,w.FLOAT,!1,16,0);w.vertexAttribPointer(u,2,w.FLOAT,!1,16,8);w.bindBuffer(w.ELEMENT_ARRAY_BUFFER,D);w.uniformMatrix4fv(q,!1,Ya.projectionMatrix.elements);I.activeTexture(w.TEXTURE0);w.uniform1i(h,0);P=ka=0;(M=n.fog)?(w.uniform3f(t,M.color.r,M.color.g,M.color.b),M.isFog?(w.uniform1f(r,M.near),w.uniform1f(l,M.far),w.uniform1i(v,1),P=ka=1):M.isFogExp2&&(w.uniform1f(p,M.density),w.uniform1i(v,2),P=ka=2)): -(w.uniform1i(v,0),P=ka=0);for(var M=0,V=b.length;Mb&&(b=a[c]);return b}function E(){Object.defineProperty(this, -"id",{value:Rd++});this.uuid=Y.generateUUID();this.name="";this.type="BufferGeometry";this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.drawRange={start:0,count:Infinity}}function Gb(a,b,c,d,e,f){J.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};this.fromBufferGeometry(new ib(a,b,c,d,e,f));this.mergeVertices()}function ib(a,b,c,d,e,f){function g(a,b, -c,d,e,f,g,l,W,D,O){var aa=f/W,F=g/D,ja=f/2,T=g/2,C=l/2;g=W+1;var B=D+1,z=f=0,P,M,V=new n;for(M=0;M/gm,function(a,c){var d=X[c]; -if(void 0===d)throw Error("Can not resolve #include <"+c+">");return Ud(d)})}function Ne(a){return a.replace(/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,function(a,c,d,e){a="";for(c=parseInt(c);cb||a.height>b){var c=b/Math.max(a.width,a.height),d=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");d.width=Math.floor(a.width*c);d.height=Math.floor(a.height*c);d.getContext("2d").drawImage(a, -0,0,a.width,a.height,0,0,d.width,d.height);console.warn("THREE.WebGLRenderer: image is too big ("+a.width+"x"+a.height+"). Resized to "+d.width+"x"+d.height,a);return d}return a}function k(a){return Y.isPowerOfTwo(a.width)&&Y.isPowerOfTwo(a.height)}function m(a,b){return a.generateMipmaps&&b&&1003!==a.minFilter&&1006!==a.minFilter}function q(b){return 1003===b||1004===b||1005===b?a.NEAREST:a.LINEAR}function v(b){b=b.target;b.removeEventListener("dispose",v);a:{var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube); -else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d.remove(b)}g.textures--}function p(b){b=b.target;b.removeEventListener("dispose",p);var c=d.get(b),e=d.get(b.texture);if(b){void 0!==e.__webglTexture&&a.deleteTexture(e.__webglTexture);b.depthTexture&&b.depthTexture.dispose();if(b.isWebGLRenderTargetCube)for(e=0;6>e;e++)a.deleteFramebuffer(c.__webglFramebuffer[e]),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer[e]);else a.deleteFramebuffer(c.__webglFramebuffer), -c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d.remove(b.texture);d.remove(b)}g.textures--}function r(b,p){var q=d.get(b);if(0y;y++)n[y]=r||t?t?b.image[y].image:b.image[y]:h(b.image[y],e.maxCubemapSize);var x=k(n[0]),F=f(b.format),ja=f(b.type);l(a.TEXTURE_CUBE_MAP,b,x);for(y= -0;6>y;y++)if(r)for(var T,C=n[y].mipmaps,z=0,B=C.length;zv;v++)e.__webglFramebuffer[v]=a.createFramebuffer()}else e.__webglFramebuffer=a.createFramebuffer();if(h){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);l(a.TEXTURE_CUBE_MAP,b.texture,q);for(v=0;6>v;v++)t(e.__webglFramebuffer[v],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+v);m(b.texture,q)&&a.generateMipmap(a.TEXTURE_CUBE_MAP);c.bindTexture(a.TEXTURE_CUBE_MAP, -null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),l(a.TEXTURE_2D,b.texture,q),t(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),m(b.texture,q)&&a.generateMipmap(a.TEXTURE_2D),c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=!0===b.isWebGLRenderTargetCube;if(b.depthTexture){if(f)throw Error("target.depthTexture not supported in Cube render targets");if(b&&b.isWebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported!");a.bindFramebuffer(a.FRAMEBUFFER, -e.__webglFramebuffer);if(!b.depthTexture||!b.depthTexture.isDepthTexture)throw Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");d.get(b.depthTexture).__webglTexture&&b.depthTexture.image.width===b.width&&b.depthTexture.image.height===b.height||(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0);r(b.depthTexture,0);e=d.get(b.depthTexture).__webglTexture;if(1026===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER, -a.DEPTH_ATTACHMENT,a.TEXTURE_2D,e,0);else if(1027===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.TEXTURE_2D,e,0);else throw Error("Unknown depthTexture format");}else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),n(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),n(e.__webglDepthbuffer, -b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap=function(b){var e=b.texture,f=k(b);m(e,f)&&(b=b.isWebGLRenderTargetCube?a.TEXTURE_CUBE_MAP:a.TEXTURE_2D,e=d.get(e).__webglTexture,c.bindTexture(b,e),a.generateMipmap(b),c.bindTexture(b,null))}}function eg(){var a={};return{get:function(b){b=b.uuid;var c=a[b];void 0===c&&(c={},a[b]=c);return c},remove:function(b){delete a[b.uuid]},clear:function(){a={}}}}function fg(a,b,c){function d(b,c,d){var e=new Uint8Array(4),f=a.createTexture(); -a.bindTexture(b,f);a.texParameteri(b,a.TEXTURE_MIN_FILTER,a.NEAREST);a.texParameteri(b,a.TEXTURE_MAG_FILTER,a.NEAREST);for(b=0;b=ia.maxTextures&&console.warn("THREE.WebGLRenderer: Trying to use "+a+" texture units while this GPU supports only "+ -ia.maxTextures);X+=1;return a};this.setTexture2D=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTarget&&(a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);ra.setTexture2D(b,c)}}();this.setTexture=function(){var a=!1;return function(b,c){a||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),a=!0);ra.setTexture2D(b,c)}}();this.setTextureCube=function(){var a= -!1;return function(b,c){b&&b.isWebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);b&&b.isCubeTexture||Array.isArray(b.image)&&6===b.image.length?ra.setTextureCube(b,c):ra.setTextureCubeDynamic(b,c)}}();this.getRenderTarget=function(){return P};this.setRenderTarget=function(a){(P=a)&&void 0===ha.get(a).__webglFramebuffer&&ra.setupRenderTarget(a);var b=a&&a.isWebGLRenderTargetCube, -c;a?(c=ha.get(a),c=b?c.__webglFramebuffer[a.activeCubeFace]:c.__webglFramebuffer,J.copy(a.scissor),Z=a.scissorTest,U.copy(a.viewport)):(c=null,J.copy(ea).multiplyScalar(Q),Z=na,U.copy(hd).multiplyScalar(Q));M!==c&&(A.bindFramebuffer(A.FRAMEBUFFER,c),M=c);ga.scissor(J);ga.setScissorTest(Z);ga.viewport(U);b&&(b=ha.get(a.texture),A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,b.__webglTexture,a.activeMipMapLevel))};this.readRenderTargetPixels= -function(a,b,c,d,e,f){if(a&&a.isWebGLRenderTarget){var g=ha.get(a).__webglFramebuffer;if(g){var h=!1;g!==M&&(A.bindFramebuffer(A.FRAMEBUFFER,g),h=!0);try{var k=a.texture,m=k.format,q=k.type;1023!==m&&y(m)!==A.getParameter(A.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===q||y(q)===A.getParameter(A.IMPLEMENTATION_COLOR_READ_TYPE)||1015===q&&(ma.get("OES_texture_float")||ma.get("WEBGL_color_buffer_float"))|| -1016===q&&ma.get("EXT_color_buffer_half_float")?A.checkFramebufferStatus(A.FRAMEBUFFER)===A.FRAMEBUFFER_COMPLETE?0<=b&&b<=a.width-d&&0<=c&&c<=a.height-e&&A.readPixels(b,c,d,e,y(m),y(q),f):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."):console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.")}finally{h&&A.bindFramebuffer(A.FRAMEBUFFER,M)}}}else console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.")}} -function Ib(a,b){this.name="";this.color=new G(a);this.density=void 0!==b?b:2.5E-4}function Jb(a,b,c){this.name="";this.color=new G(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function ld(){z.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function Yd(a,b,c,d,e){z.call(this);this.lensFlares=[];this.positionScreen=new n;this.customUpdateCallback=void 0;void 0!==a&&this.add(a,b,c,d,e)}function bb(a){U.call(this);this.type="SpriteMaterial"; -this.color=new G(16777215);this.map=null;this.rotation=0;this.lights=this.fog=!1;this.setValues(a)}function xc(a){z.call(this);this.type="Sprite";this.material=void 0!==a?a:new bb}function yc(){z.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function zc(a,b){a=a||[];this.bones=a.slice(0);this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===b)this.calculateInverses();else if(this.bones.length===b.length)this.boneInverses=b.slice(0);else{console.warn("THREE.Skeleton boneInverses is the wrong length."); -this.boneInverses=[];for(var c=0,d=this.bones.length;c=a.HAVE_CURRENT_DATA&&(q.needsUpdate=!0)}ba.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1;var q=this;m()}function Lb(a,b, -c,d,e,f,g,h,k,m,q,v){ba.call(this,null,f,g,h,k,m,d,e,q,v);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1}function qd(a,b,c,d,e,f,g,h,k){ba.call(this,a,b,c,d,e,f,g,h,k);this.needsUpdate=!0}function Bc(a,b,c,d,e,f,g,h,k,m){m=void 0!==m?m:1026;if(1026!==m&&1027!==m)throw Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===c&&1026===m&&(c=1012);void 0===c&&1027===m&&(c=1020);ba.call(this,null,d,e,f,g,h,m,c,k);this.image={width:a, -height:b};this.magFilter=void 0!==g?g:1003;this.minFilter=void 0!==h?h:1003;this.generateMipmaps=this.flipY=!1}function Mb(a){E.call(this);this.type="WireframeGeometry";var b=[],c,d,e,f,g=[0,0],h={},k,m,q=["a","b","c"];if(a&&a.isGeometry){var v=a.faces;c=0;for(e=v.length;cd;d++)k=p[q[d]],m=p[q[(d+1)%3]],g[0]=Math.min(k,m),g[1]=Math.max(k,m),k=g[0]+","+g[1],void 0===h[k]&&(h[k]={index1:g[0],index2:g[1]})}for(k in h)c=h[k],q=a.vertices[c.index1],b.push(q.x,q.y,q.z),q=a.vertices[c.index2], -b.push(q.x,q.y,q.z)}else if(a&&a.isBufferGeometry){var r,q=new n;if(null!==a.index){v=a.attributes.position;p=a.index;r=a.groups;0===r.length&&(r=[{start:0,count:p.count,materialIndex:0}]);a=0;for(f=r.length;ad;d++)k=p.getX(c+d),m=p.getX(c+(d+1)%3),g[0]=Math.min(k,m),g[1]=Math.max(k,m),k=g[0]+","+g[1],void 0===h[k]&&(h[k]={index1:g[0],index2:g[1]});for(k in h)c=h[k],q.fromBufferAttribute(v,c.index1),b.push(q.x,q.y,q.z),q.fromBufferAttribute(v, -c.index2),b.push(q.x,q.y,q.z)}else for(v=a.attributes.position,c=0,e=v.count/3;cd;d++)h=3*c+d,q.fromBufferAttribute(v,h),b.push(q.x,q.y,q.z),h=3*c+(d+1)%3,q.fromBufferAttribute(v,h),b.push(q.x,q.y,q.z)}this.addAttribute("position",new B(b,3))}function Cc(a,b,c){J.call(this);this.type="ParametricGeometry";this.parameters={func:a,slices:b,stacks:c};this.fromBufferGeometry(new Nb(a,b,c));this.mergeVertices()}function Nb(a,b,c){E.call(this);this.type="ParametricBufferGeometry";this.parameters= -{func:a,slices:b,stacks:c};var d=[],e=[],f=[],g=[],h=new n,k=new n,m=new n,q=new n,v=new n,p,r,l=b+1;for(p=0;p<=c;p++){var t=p/c;for(r=0;r<=b;r++){var y=r/b,k=a(y,t,k);e.push(k.x,k.y,k.z);0<=y-1E-5?(m=a(y-1E-5,t,m),q.subVectors(k,m)):(m=a(y+1E-5,t,m),q.subVectors(m,k));0<=t-1E-5?(m=a(y,t-1E-5,m),v.subVectors(k,m)):(m=a(y,t+1E-5,m),v.subVectors(m,k));h.crossVectors(q,v).normalize();f.push(h.x,h.y,h.z);g.push(y,t)}}for(p=0;pd&&1===a.x&&(k[b]=a.x-1);0===c.x&&0=== -c.z&&(k[b]=d/2/Math.PI+.5)}E.call(this);this.type="PolyhedronBufferGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};c=c||1;d=d||0;var h=[],k=[];(function(a){for(var c=new n,d=new n,g=new n,h=0;he&&(.2>b&&(k[a+0]+=1),.2>c&&(k[a+2]+=1),.2>d&&(k[a+4]+=1))})();this.addAttribute("position",new B(h,3));this.addAttribute("normal", -new B(h.slice(),3));this.addAttribute("uv",new B(k,2));0===d?this.computeVertexNormals():this.normalizeNormals()}function Ec(a,b){J.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Ob(a,b));this.mergeVertices()}function Ob(a,b){za.call(this,[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],a,b);this.type="TetrahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Fc(a,b){J.call(this);this.type="OctahedronGeometry";this.parameters= -{radius:a,detail:b};this.fromBufferGeometry(new lb(a,b));this.mergeVertices()}function lb(a,b){za.call(this,[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],a,b);this.type="OctahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Gc(a,b){J.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Pb(a,b));this.mergeVertices()}function Pb(a,b){var c=(1+Math.sqrt(5))/2;za.call(this,[-1,c,0,1,c,0, --1,-c,0,1,-c,0,0,-1,c,0,1,c,0,-1,-c,0,1,-c,c,0,-1,c,0,1,-c,0,-1,-c,0,1],[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],a,b);this.type="IcosahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Hc(a,b){J.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Qb(a,b));this.mergeVertices()}function Qb(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;za.call(this, -[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-d,-c,0,-d,c,0,d,-c,0,d,c,-d,-c,0,-d,c,0,d,-c,0,d,c,0,-c,0,-d,c,0,-d,-c,0,d,c,0,d],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],a,b);this.type="DodecahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Ic(a, -b,c,d,e,f){J.call(this);this.type="TubeGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};void 0!==f&&console.warn("THREE.TubeGeometry: taper has been removed.");a=new Rb(a,b,c,d,e);this.tangents=a.tangents;this.normals=a.normals;this.binormals=a.binormals;this.fromBufferGeometry(a);this.mergeVertices()}function Rb(a,b,c,d,e){function f(e){var f=a.getPointAt(e/b),m=g.normals[e];e=g.binormals[e];for(v=0;v<=d;v++){var q=v/d*Math.PI*2,l=Math.sin(q),q=-Math.cos(q); -k.x=q*m.x+l*e.x;k.y=q*m.y+l*e.y;k.z=q*m.z+l*e.z;k.normalize();r.push(k.x,k.y,k.z);h.x=f.x+c*k.x;h.y=f.y+c*k.y;h.z=f.z+c*k.z;p.push(h.x,h.y,h.z)}}E.call(this);this.type="TubeBufferGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};b=b||64;c=c||1;d=d||8;e=e||!1;var g=a.computeFrenetFrames(b,e);this.tangents=g.tangents;this.normals=g.normals;this.binormals=g.binormals;var h=new n,k=new n,m=new C,q,v,p=[],r=[],l=[],t=[];for(q=0;qn;n++)g=l[k[n]],h=l[k[(n+1)%3]],e[0]=Math.min(g,h),e[1]=Math.max(g,h),g=e[0]+","+e[1],void 0===f[g]?f[g]={index1:e[0],index2:e[1],face1:v,face2:void 0}:f[g].face2=v;for(g in f)if(e=f[g],void 0===e.face2||m[e.face1].normal.dot(m[e.face2].normal)<=d)k=q[e.index1],c.push(k.x,k.y,k.z),k=q[e.index2],c.push(k.x,k.y,k.z);this.addAttribute("position", -new B(c,3))}function nb(a,b,c,d,e,f,g,h){J.call(this);this.type="CylinderGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};this.fromBufferGeometry(new Ua(a,b,c,d,e,f,g,h));this.mergeVertices()}function Ua(a,b,c,d,e,f,g,h){function k(c){var e,f,k,t=new C,D=new n,O=0,aa=!0===c?a:b,F=!0===c?1:-1;f=ca;for(e=1;e<=d;e++)v.push(0,y*F,0),p.push(0,F,0),l.push(.5,.5),ca++;k=ca;for(e=0;e<=d;e++){var B=e/d*h+g,z=Math.cos(B), -B=Math.sin(B);D.x=aa*B;D.y=y*F;D.z=aa*z;v.push(D.x,D.y,D.z);p.push(0,F,0);t.x=.5*z+.5;t.y=.5*B*F+.5;l.push(t.x,t.y);ca++}for(e=0;ethis.duration&&this.resetDuration();this.optimize()}function Gd(a){this.manager= -void 0!==a?a:va;this.textures={}}function be(a){this.manager=void 0!==a?a:va}function ec(){this.onLoadStart=function(){};this.onLoadProgress=function(){};this.onLoadComplete=function(){}}function ce(a){"boolean"===typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),a=void 0);this.manager=void 0!==a?a:va;this.withCredentials=!1}function Pe(a){this.manager=void 0!==a?a:va;this.texturePath=""}function Qe(a,b,c,d,e){b=.5*(d-b);e=.5*(e-c);var f=a*a;return(2* -c-2*d+b+e)*a*f+(-3*c+3*d-2*b-e)*f+b*a+c}function wb(a,b,c,d){var e=1-a;return e*e*b+2*(1-a)*a*c+a*a*d}function xb(a,b,c,d,e){var f=1-a,g=1-a;return f*f*f*b+3*g*g*a*c+3*(1-a)*a*a*d+a*a*a*e}function ua(){this.arcLengthDivisions=200}function Qa(a,b){this.arcLengthDivisions=200;this.v1=a;this.v2=b}function Vc(){this.arcLengthDivisions=200;this.curves=[];this.autoClose=!1}function Va(a,b,c,d,e,f,g,h){this.arcLengthDivisions=200;this.aX=a;this.aY=b;this.xRadius=c;this.yRadius=d;this.aStartAngle=e;this.aEndAngle= -f;this.aClockwise=g;this.aRotation=h||0}function yb(a){this.arcLengthDivisions=200;this.points=void 0===a?[]:a}function fc(a,b,c,d){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2=c;this.v3=d}function gc(a,b,c){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2=c}function Wc(a){Vc.call(this);this.currentPoint=new C;a&&this.fromPoints(a)}function zb(){Wc.apply(this,arguments);this.holes=[]}function de(){this.subPaths=[];this.currentPath=null}function ee(a){this.data=a}function Re(a){this.manager= -void 0!==a?a:va}function fe(a){this.manager=void 0!==a?a:va}function Se(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new qa;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new qa;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=!1}function Hd(a,b,c){z.call(this);this.type="CubeCamera";var d=new qa(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new n(1,0,0));this.add(d);var e=new qa(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new n(-1,0,0));this.add(e); -var f=new qa(90,1,a,b);f.up.set(0,0,1);f.lookAt(new n(0,1,0));this.add(f);var g=new qa(90,1,a,b);g.up.set(0,0,-1);g.lookAt(new n(0,-1,0));this.add(g);var h=new qa(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new n(0,0,1));this.add(h);var k=new qa(90,1,a,b);k.up.set(0,-1,0);k.lookAt(new n(0,0,-1));this.add(k);this.renderTarget=new Db(c,c,{format:1022,magFilter:1006,minFilter:1006});this.renderTarget.texture.name="CubeCamera";this.updateCubeMap=function(a,b){null===this.parent&&this.updateMatrixWorld();var c= -this.renderTarget,p=c.texture.generateMipmaps;c.texture.generateMipmaps=!1;c.activeCubeFace=0;a.render(b,d,c);c.activeCubeFace=1;a.render(b,e,c);c.activeCubeFace=2;a.render(b,f,c);c.activeCubeFace=3;a.render(b,g,c);c.activeCubeFace=4;a.render(b,h,c);c.texture.generateMipmaps=p;c.activeCubeFace=5;a.render(b,k,c);a.setRenderTarget(null)}}function ge(){z.call(this);this.type="AudioListener";this.context=he.getContext();this.gain=this.context.createGain();this.gain.connect(this.context.destination);this.filter= -null}function hc(a){z.call(this);this.type="Audio";this.context=a.context;this.gain=this.context.createGain();this.gain.connect(a.getInput());this.autoplay=!1;this.buffer=null;this.loop=!1;this.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";this.filters=[]}function ie(a){hc.call(this,a);this.panner=this.context.createPanner();this.panner.connect(this.gain)}function je(a,b){this.analyser=a.context.createAnalyser();this.analyser.fftSize=void 0!== -b?b:2048;this.data=new Uint8Array(this.analyser.frequencyBinCount);a.getOutput().connect(this.analyser)}function ke(a,b,c){this.binding=a;this.valueSize=c;a=Float64Array;switch(b){case "quaternion":b=this._slerp;break;case "string":case "bool":a=Array;b=this._select;break;default:b=this._lerp}this.buffer=new a(4*c);this._mixBufferRegion=b;this.referenceCount=this.useCount=this.cumulativeWeight=0}function Te(a,b,c){c=c||ha.parseTrackName(b);this._targetGroup=a;this._bindings=a.subscribe_(b,c)}function ha(a, -b,c){this.path=b;this.parsedPath=c||ha.parseTrackName(b);this.node=ha.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function Ue(a){this.uuid=Y.generateUUID();this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var b={};this._indicesByUUID=b;for(var c=0,d=arguments.length;c!==d;++c)b[arguments[c].uuid]=c;this._paths=[];this._parsedPaths=[];this._bindings=[];this._bindingsIndicesByPath={};var e=this;this.stats={objects:{get total(){return e._objects.length},get inUse(){return this.total- -e.nCachedObjects_}},get bindingsPerObject(){return e._bindings.length}}}function Ve(a,b,c){this._mixer=a;this._clip=b;this._localRoot=c||null;a=b.tracks;b=a.length;c=Array(b);for(var d={endingStart:2400,endingEnd:2400},e=0;e!==b;++e){var f=a[e].createInterpolant(null);c[e]=f;f.settings=d}this._interpolantSettings=d;this._interpolants=c;this._propertyBindings=Array(b);this._weightInterpolant=this._timeScaleInterpolant=this._byClipCacheIndex=this._cacheIndex=null;this.loop=2201;this._loopCount=-1;this._startTime= -null;this.time=0;this._effectiveWeight=this.weight=this._effectiveTimeScale=this.timeScale=1;this.repetitions=Infinity;this.paused=!1;this.enabled=!0;this.clampWhenFinished=!1;this.zeroSlopeAtEnd=this.zeroSlopeAtStart=!0}function We(a){this._root=a;this._initMemoryManager();this.time=this._accuIndex=0;this.timeScale=1}function Id(a,b){"string"===typeof a&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),a=b);this.value=a}function le(){E.call(this);this.type="InstancedBufferGeometry"; -this.maxInstancedCount=void 0}function me(a,b,c,d){this.uuid=Y.generateUUID();this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0===d}function ic(a,b){this.uuid=Y.generateUUID();this.array=a;this.stride=b;this.count=void 0!==a?a.length/b:0;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function ne(a,b,c){ic.call(this,a,b);this.meshPerAttribute=c||1}function oe(a,b,c){Z.call(this,a,b);this.meshPerAttribute=c||1}function Xe(a,b,c,d){this.ray= -new kb(a,b);this.near=c||0;this.far=d||Infinity;this.params={Mesh:{},Line:{},LOD:{},Points:{threshold:1},Sprite:{}};Object.defineProperties(this.params,{PointCloud:{get:function(){console.warn("THREE.Raycaster: params.PointCloud has been renamed to params.Points.");return this.Points}}})}function Ye(a,b){return a.distance-b.distance}function pe(a,b,c,d){if(!1!==a.visible&&(a.raycast(b,c),!0===d)){a=a.children;d=0;for(var e=a.length;dc;c++,d++){var e=c/32*Math.PI*2,f=d/32*Math.PI*2;b.push(Math.cos(e),Math.sin(e),1,Math.cos(f),Math.sin(f),1)}a.addAttribute("position",new B(b,3));b=new ea({fog:!1});this.cone=new Q(a,b);this.add(this.cone);this.update()}function bf(a){var b=[];a&&a.isBone&&b.push(a);for(var c=0;ca.length&&console.warn("THREE.CatmullRomCurve3: Points array needs at least two entries.");this.points=a||[];this.closed=!1}function bd(a,b,c,d){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2= -c;this.v3=d}function cd(a,b,c){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2=c}function dd(a,b){this.arcLengthDivisions=200;this.v1=a;this.v2=b}function Md(a,b,c,d,e,f){Va.call(this,a,b,c,c,d,e,f)}function cf(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");La.call(this,a);this.type="catmullrom";this.closed=!0}function df(a){console.warn("THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");La.call(this,a);this.type= -"catmullrom"}function se(a){console.warn("THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.");La.call(this,a);this.type="catmullrom"}void 0===Number.EPSILON&&(Number.EPSILON=Math.pow(2,-52));void 0===Number.isInteger&&(Number.isInteger=function(a){return"number"===typeof a&&isFinite(a)&&Math.floor(a)===a});void 0===Math.sign&&(Math.sign=function(a){return 0>a?-1:0b&&(b=a[c]);return b}function F(){Object.defineProperty(this,"id",{value:Bf+=2});this.uuid=S.generateUUID();this.name="";this.type="BufferGeometry";this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.drawRange= +{start:0,count:Infinity}}function Kb(a,b,c,d,e,f){N.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};this.fromBufferGeometry(new mb(a,b,c,d,e,f));this.mergeVertices()}function mb(a,b,c,d,e,f){function g(a,b,c,d,e,f,g,k,P,H,ta){var q=f/P,v=g/H,x=f/2,K=g/2,w=k/2;g=P+1;var y=H+1,B=f=0,G,C,z=new p;for(C=0;Cm;m++){if(n=d[m])if(h=n[0],l=n[1]){u&&e.addAttribute("morphTarget"+m,u[h]);f&&e.addAttribute("morphNormal"+m,f[h]);c[m]=l;continue}c[m]=0}g.getUniforms().setValue(a,"morphTargetInfluences",c)}}}function Nf(a,b){var c={};return{update:function(d){var e=b.render.frame,f=d.geometry,g=a.get(d,f);c[g.id]!==e&&(f.isGeometry&&g.updateFromObject(d), +a.update(g),c[g.id]=e);return g},dispose:function(){c={}}}}function ab(a,b,c,d,e,f,g,h,l,m){a=void 0!==a?a:[];Y.call(this,a,void 0!==b?b:301,c,d,e,f,g,h,l,m);this.flipY=!1}function Mb(a,b,c){var d=a[0];if(0>=d||0/gm,function(a,c){a=V[c];if(void 0===a)throw Error("Can not resolve #include <"+c+ +">");return Wd(a)})}function Te(a){return a.replace(/#pragma unroll_loop[\s]+?for \( int i = (\d+); i < (\d+); i \+\+ \) \{([\s\S]+?)(?=\})\}/g,function(a,c,d,e){a="";for(c=parseInt(c);c 0 ) {\n\t\tfloat fogFactor = 0.0;\n\t\tif ( fogType == 1 ) {\n\t\t\tfogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t\t} else {\n\t\t\tconst float LOG2 = 1.442695;\n\t\t\tfogFactor = exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 );\n\t\t\tfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n\t\t}\n\t\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n\t}\n}"].join("\n")); +b.compileShader(ya);b.compileShader(Q);b.attachShader(ta,ya);b.attachShader(ta,Q);b.linkProgram(ta);Z=ta;K=b.getAttribLocation(Z,"position");P=b.getAttribLocation(Z,"uv");f=b.getUniformLocation(Z,"uvOffset");g=b.getUniformLocation(Z,"uvScale");h=b.getUniformLocation(Z,"rotation");l=b.getUniformLocation(Z,"center");m=b.getUniformLocation(Z,"scale");u=b.getUniformLocation(Z,"color");n=b.getUniformLocation(Z,"map");t=b.getUniformLocation(Z,"opacity");r=b.getUniformLocation(Z,"modelViewMatrix");k=b.getUniformLocation(Z, +"projectionMatrix");v=b.getUniformLocation(Z,"fogType");x=b.getUniformLocation(Z,"fogDensity");y=b.getUniformLocation(Z,"fogNear");w=b.getUniformLocation(Z,"fogFar");B=b.getUniformLocation(Z,"fogColor");b.getUniformLocation(Z,"fogDepth");G=b.getUniformLocation(Z,"alphaTest");ta=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");ta.width=8;ta.height=8;ya=ta.getContext("2d");ya.fillStyle="white";ya.fillRect(0,0,8,8);z=new zc(ta)}c.useProgram(Z);c.initAttributes();c.enableAttribute(K); +c.enableAttribute(P);c.disableUnusedAttributes();c.disable(b.CULL_FACE);c.enable(b.BLEND);b.bindBuffer(b.ARRAY_BUFFER,C);b.vertexAttribPointer(K,2,b.FLOAT,!1,16,0);b.vertexAttribPointer(P,2,b.FLOAT,!1,16,8);b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,nb);b.uniformMatrix4fv(k,!1,md.projectionMatrix.elements);c.activeTexture(b.TEXTURE0);b.uniform1i(n,0);ya=ta=0;(Q=p.fog)?(b.uniform3f(B,Q.color.r,Q.color.g,Q.color.b),Q.isFog?(b.uniform1f(y,Q.near),b.uniform1f(w,Q.far),b.uniform1i(v,1),ya=ta=1):Q.isFogExp2&& +(b.uniform1f(x,Q.density),b.uniform1i(v,2),ya=ta=2)):(b.uniform1i(v,0),ya=ta=0);Q=0;for(var L=q.length;Qb||a.height>b){if("data"in a){console.warn("THREE.WebGLRenderer: image in DataTexture is too big ("+a.width+"x"+a.height+").");return}b/=Math.max(a.width,a.height);var c=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");c.width=Math.floor(a.width*b);c.height=Math.floor(a.height* +b);c.getContext("2d").drawImage(a,0,0,a.width,a.height,0,0,c.width,c.height);console.warn("THREE.WebGLRenderer: image is too big ("+a.width+"x"+a.height+"). Resized to "+c.width+"x"+c.height,a);return c}return a}function l(a){return S.isPowerOfTwo(a.width)&&S.isPowerOfTwo(a.height)}function m(a,b){return a.generateMipmaps&&b&&1003!==a.minFilter&&1006!==a.minFilter}function u(b,c,e,f){a.generateMipmap(b);d.get(c).__maxMipLevel=Math.log2(Math.max(e,f))}function n(b){return 1003===b||1004===b||1005=== +b?a.NEAREST:a.LINEAR}function t(b){b=b.target;b.removeEventListener("dispose",t);a:{var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube);else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d.remove(b)}b.isVideoTexture&&delete B[b.id];g.memory.textures--}function k(b){b=b.target;b.removeEventListener("dispose",k);var c=d.get(b),e=d.get(b.texture);if(b){void 0!==e.__webglTexture&&a.deleteTexture(e.__webglTexture);b.depthTexture&&b.depthTexture.dispose(); +if(b.isWebGLRenderTargetCube)for(e=0;6>e;e++)a.deleteFramebuffer(c.__webglFramebuffer[e]),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer[e]);else a.deleteFramebuffer(c.__webglFramebuffer),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d.remove(b.texture);d.remove(b)}g.memory.textures--}function q(b,n){var k=d.get(b);if(b.isVideoTexture){var r=b.id,q=g.render.frame;B[r]!==q&&(B[r]=q,b.update())}if(0p;p++)q[p]=n||r?r?b.image[p].image:b.image[p]:h(b.image[p],e.maxCubemapSize);var x=q[0],w=l(x),K=f.convert(b.format),y=f.convert(b.type);v(a.TEXTURE_CUBE_MAP,b,w);for(p=0;6>p;p++)if(n)for(var B,G=q[p].mipmaps,P=0,C=G.length;Pt;t++)e.__webglFramebuffer[t]=a.createFramebuffer()}else e.__webglFramebuffer=a.createFramebuffer();if(h){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);v(a.TEXTURE_CUBE_MAP,b.texture,n);for(t=0;6>t;t++)p(e.__webglFramebuffer[t],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+t);m(b.texture,n)&&u(a.TEXTURE_CUBE_MAP,b.texture,b.width,b.height);c.bindTexture(a.TEXTURE_CUBE_MAP,null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),v(a.TEXTURE_2D,b.texture,n),p(e.__webglFramebuffer, +b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),m(b.texture,n)&&u(a.TEXTURE_2D,b.texture,b.width,b.height),c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=!0===b.isWebGLRenderTargetCube;if(b.depthTexture){if(f)throw Error("target.depthTexture not supported in Cube render targets");if(b&&b.isWebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported");a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer);if(!b.depthTexture||!b.depthTexture.isDepthTexture)throw Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture"); +d.get(b.depthTexture).__webglTexture&&b.depthTexture.image.width===b.width&&b.depthTexture.image.height===b.height||(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0);q(b.depthTexture,0);e=d.get(b.depthTexture).__webglTexture;if(1026===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.TEXTURE_2D,e,0);else if(1027===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.TEXTURE_2D,e, +0);else throw Error("Unknown depthTexture format");}else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),y(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),y(e.__webglDepthbuffer,b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap=function(b){var e=b.texture,f=l(b);if(m(e,f)){f=b.isWebGLRenderTargetCube? +a.TEXTURE_CUBE_MAP:a.TEXTURE_2D;var g=d.get(e).__webglTexture;c.bindTexture(f,g);u(f,e,b.width,b.height);c.bindTexture(f,null)}}}function Ve(a,b){return{convert:function(c){if(1E3===c)return a.REPEAT;if(1001===c)return a.CLAMP_TO_EDGE;if(1002===c)return a.MIRRORED_REPEAT;if(1003===c)return a.NEAREST;if(1004===c)return a.NEAREST_MIPMAP_NEAREST;if(1005===c)return a.NEAREST_MIPMAP_LINEAR;if(1006===c)return a.LINEAR;if(1007===c)return a.LINEAR_MIPMAP_NEAREST;if(1008===c)return a.LINEAR_MIPMAP_LINEAR; +if(1009===c)return a.UNSIGNED_BYTE;if(1017===c)return a.UNSIGNED_SHORT_4_4_4_4;if(1018===c)return a.UNSIGNED_SHORT_5_5_5_1;if(1019===c)return a.UNSIGNED_SHORT_5_6_5;if(1010===c)return a.BYTE;if(1011===c)return a.SHORT;if(1012===c)return a.UNSIGNED_SHORT;if(1013===c)return a.INT;if(1014===c)return a.UNSIGNED_INT;if(1015===c)return a.FLOAT;if(1016===c){var d=b.get("OES_texture_half_float");if(null!==d)return d.HALF_FLOAT_OES}if(1021===c)return a.ALPHA;if(1022===c)return a.RGB;if(1023===c)return a.RGBA; +if(1024===c)return a.LUMINANCE;if(1025===c)return a.LUMINANCE_ALPHA;if(1026===c)return a.DEPTH_COMPONENT;if(1027===c)return a.DEPTH_STENCIL;if(100===c)return a.FUNC_ADD;if(101===c)return a.FUNC_SUBTRACT;if(102===c)return a.FUNC_REVERSE_SUBTRACT;if(200===c)return a.ZERO;if(201===c)return a.ONE;if(202===c)return a.SRC_COLOR;if(203===c)return a.ONE_MINUS_SRC_COLOR;if(204===c)return a.SRC_ALPHA;if(205===c)return a.ONE_MINUS_SRC_ALPHA;if(206===c)return a.DST_ALPHA;if(207===c)return a.ONE_MINUS_DST_ALPHA; +if(208===c)return a.DST_COLOR;if(209===c)return a.ONE_MINUS_DST_COLOR;if(210===c)return a.SRC_ALPHA_SATURATE;if(33776===c||33777===c||33778===c||33779===c)if(d=b.get("WEBGL_compressed_texture_s3tc"),null!==d){if(33776===c)return d.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===c)return d.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===c)return d.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===c)return d.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===c||35841===c||35842===c||35843===c)if(d=b.get("WEBGL_compressed_texture_pvrtc"), +null!==d){if(35840===c)return d.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===c)return d.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===c)return d.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===c)return d.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===c&&(d=b.get("WEBGL_compressed_texture_etc1"),null!==d))return d.COMPRESSED_RGB_ETC1_WEBGL;if(37808===c||37809===c||37810===c||37811===c||37812===c||37813===c||37814===c||37815===c||37816===c||37817===c||37818===c||37819===c||37820===c||37821===c)if(d=b.get("WEBGL_compressed_texture_astc"), +null!==d)return c;if(103===c||104===c)if(d=b.get("EXT_blend_minmax"),null!==d){if(103===c)return d.MIN_EXT;if(104===c)return d.MAX_EXT}return 1020===c&&(d=b.get("WEBGL_depth_texture"),null!==d)?d.UNSIGNED_INT_24_8_WEBGL:0}}}function la(a,b,c,d){Qa.call(this);this.type="PerspectiveCamera";this.fov=void 0!==a?a:50;this.zoom=1;this.near=void 0!==c?c:.1;this.far=void 0!==d?d:2E3;this.focus=10;this.aspect=void 0!==b?b:1;this.view=null;this.filmGauge=35;this.filmOffset=0;this.updateProjectionMatrix()}function qd(a){la.call(this); +this.cameras=a||[]}function We(a){function b(){if(null!==d&&d.isPresenting){var b=d.getEyeParameters("left"),e=b.renderWidth;b=b.renderHeight;v=a.getPixelRatio();q=a.getSize();a.setDrawingBufferSize(2*e,b,1)}else c.enabled&&a.setDrawingBufferSize(q.width,q.height,v)}var c=this,d=null,e=null,f=null,g=new M,h=new M;"undefined"!==typeof window&&"VRFrameData"in window&&(e=new window.VRFrameData);var l=new M,m=new ja,u=new p,n=new la;n.bounds=new ea(0,0,.5,1);n.layers.enable(1);var t=new la;t.bounds=new ea(.5, +0,.5,1);t.layers.enable(2);var k=new qd([n,t]);k.layers.enable(1);k.layers.enable(2);var q,v;"undefined"!==typeof window&&window.addEventListener("vrdisplaypresentchange",b,!1);this.enabled=!1;this.userHeight=1.6;this.getDevice=function(){return d};this.setDevice=function(a){void 0!==a&&(d=a)};this.setPoseTarget=function(a){void 0!==a&&(f=a)};this.getCamera=function(a){if(null===d)return a;d.depthNear=a.near;d.depthFar=a.far;d.getFrameData(e);var b=d.stageParameters;b?g.fromArray(b.sittingToStandingTransform): +g.makeTranslation(0,c.userHeight,0);b=e.pose;var r=null!==f?f:a;r.matrix.copy(g);r.matrix.decompose(r.position,r.quaternion,r.scale);null!==b.orientation&&(m.fromArray(b.orientation),r.quaternion.multiply(m));null!==b.position&&(m.setFromRotationMatrix(g),u.fromArray(b.position),u.applyQuaternion(m),r.position.add(u));r.updateMatrixWorld();if(!1===d.isPresenting)return a;n.near=a.near;t.near=a.near;n.far=a.far;t.far=a.far;k.matrixWorld.copy(a.matrixWorld);k.matrixWorldInverse.copy(a.matrixWorldInverse); +n.matrixWorldInverse.fromArray(e.leftViewMatrix);t.matrixWorldInverse.fromArray(e.rightViewMatrix);h.getInverse(g);n.matrixWorldInverse.multiply(h);t.matrixWorldInverse.multiply(h);a=r.parent;null!==a&&(l.getInverse(a.matrixWorld),n.matrixWorldInverse.multiply(l),t.matrixWorldInverse.multiply(l));n.matrixWorld.getInverse(n.matrixWorldInverse);t.matrixWorld.getInverse(t.matrixWorldInverse);n.projectionMatrix.fromArray(e.leftProjectionMatrix);t.projectionMatrix.fromArray(e.rightProjectionMatrix);k.projectionMatrix.copy(n.projectionMatrix); +a=d.getLayers();a.length&&(a=a[0],null!==a.leftBounds&&4===a.leftBounds.length&&n.bounds.fromArray(a.leftBounds),null!==a.rightBounds&&4===a.rightBounds.length&&t.bounds.fromArray(a.rightBounds));return k};this.getStandingMatrix=function(){return g};this.submitFrame=function(){d&&d.isPresenting&&d.submitFrame()};this.dispose=function(){"undefined"!==typeof window&&window.removeEventListener("vrdisplaypresentchange",b)}}function Xd(a){function b(){ka=new Hf(D);ka.get("WEBGL_depth_texture");ka.get("OES_texture_float"); +ka.get("OES_texture_float_linear");ka.get("OES_texture_half_float");ka.get("OES_texture_half_float_linear");ka.get("OES_standard_derivatives");ka.get("OES_element_index_uint");ka.get("ANGLE_instanced_arrays");ia=new Ve(D,ka);Ra=new Ff(D,ka,a);ba=new Eg(D,ka,ia);ba.scissor(V.copy(ca).multiplyScalar(R));ba.viewport(ob.copy(Y).multiplyScalar(R));da=new Kf(D);X=new tg;fa=new Fg(D,ka,ba,X,Ra,ia,da);qa=new yf(D);ra=new If(D,qa,da);sa=new Nf(ra,da);wa=new Mf(D);oa=new sg(A,ka,Ra);ua=new xg;pa=new Cg;ma= +new Df(A,ba,ra,P);xa=new Ef(D,ka,da);za=new Jf(D,ka,da);Aa=new Dg(A,D,ba,fa,Ra);da.programs=oa.programs;A.context=D;A.capabilities=Ra;A.extensions=ka;A.properties=X;A.renderLists=ua;A.state=ba;A.info=da}function c(a){a.preventDefault();console.log("THREE.WebGLRenderer: Context Lost.");E=!0}function d(){console.log("THREE.WebGLRenderer: Context Restored.");E=!1;b()}function e(a){a=a.target;a.removeEventListener("dispose",e);f(a);X.remove(a)}function f(a){var b=X.get(a).program;a.program=void 0;void 0!== +b&&oa.releaseProgram(b)}function g(a,b,c){a.render(function(a){A.renderBufferImmediate(a,b,c)})}function h(){var a=na.getDevice();a&&a.isPresenting?a.requestAnimationFrame(l):window.requestAnimationFrame(l)}function l(a){!1!==va&&(Ba(a),h())}function m(a,b,c){if(!1!==a.visible){if(a.layers.test(b.layers))if(a.isLight)Z.pushLight(a),a.castShadow&&Z.pushShadow(a);else if(a.isSprite)a.frustumCulled&&!ha.intersectsSprite(a)||Z.pushSprite(a);else if(a.isImmediateRenderObject)c&&Nb.setFromMatrixPosition(a.matrixWorld).applyMatrix4(pd), +z.push(a,null,a.material,Nb.z,null);else if(a.isMesh||a.isLine||a.isPoints)if(a.isSkinnedMesh&&a.skeleton.update(),!a.frustumCulled||ha.intersectsObject(a)){c&&Nb.setFromMatrixPosition(a.matrixWorld).applyMatrix4(pd);var d=sa.update(a),e=a.material;if(Array.isArray(e))for(var f=d.groups,g=0,h=f.length;ga.matrixWorld.determinant();ba.setMaterial(e,h);h=k(c,b.fog,e,a);N="";g(a,h,e)}else A.renderBufferDirect(c,b.fog,d,e,a,f);a.onAfterRender(A,b,c,d,e,f);Z=pa.get(b,T||c)}function t(a,b,c){var d=X.get(a),g=Z.state.lights;c=oa.getParameters(a,g.state,Z.state.shadowsArray,b,Ga.numPlanes,Ga.numIntersection,c);var h=oa.getProgramCode(a,c),l=d.program,m=!0;if(void 0===l)a.addEventListener("dispose",e);else if(l.code!==h)f(a);else{if(d.lightsHash!==g.state.hash)X.update(a, +"lightsHash",g.state.hash);else if(void 0!==c.shaderID)return;m=!1}m&&(c.shaderID?(l=rb[c.shaderID],d.shader={name:a.type,uniforms:Da.clone(l.uniforms),vertexShader:l.vertexShader,fragmentShader:l.fragmentShader}):d.shader={name:a.type,uniforms:a.uniforms,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader},a.onBeforeCompile(d.shader,A),l=oa.acquireProgram(a,d.shader,c,h),d.program=l,a.program=l);c=l.getAttributes();if(a.morphTargets)for(h=a.numSupportedMorphTargets=0;he.matrixWorld.determinant();ba.setMaterial(d,g);var h=k(a,b,d,e);a=c.id+"_"+h.id+"_"+(!0===d.wireframe);var l=!1;a!==N&&(N=a,l=!0);e.morphTargetInfluences&&(wa.update(e,c,d,h),l=!0);g=c.index;var m=c.attributes.position;b=1;!0===d.wireframe&&(g=ra.getWireframeAttribute(c),b=2);a=xa;if(null!==g){var n=qa.get(g);a=za;a.setIndex(n)}if(l){l=void 0;if(c&&c.isInstancedBufferGeometry&&null===ka.get("ANGLE_instanced_arrays"))console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."); +else{void 0===l&&(l=0);ba.initAttributes();var u=c.attributes;h=h.getAttributes();var t=d.defaultAttributeValues;for(K in h){var r=h[K];if(0<=r){var q=u[K];if(void 0!==q){var p=q.normalized,v=q.itemSize,x=qa.get(q);if(void 0!==x){var w=x.buffer,B=x.type;x=x.bytesPerElement;if(q.isInterleavedBufferAttribute){var y=q.data,G=y.stride;q=q.offset;y&&y.isInstancedInterleavedBuffer?(ba.enableAttributeAndDivisor(r,y.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=y.meshPerAttribute*y.count)): +ba.enableAttribute(r);D.bindBuffer(D.ARRAY_BUFFER,w);D.vertexAttribPointer(r,v,B,p,G*x,(l*G+q)*x)}else q.isInstancedBufferAttribute?(ba.enableAttributeAndDivisor(r,q.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=q.meshPerAttribute*q.count)):ba.enableAttribute(r),D.bindBuffer(D.ARRAY_BUFFER,w),D.vertexAttribPointer(r,v,B,p,0,l*v*x)}}else if(void 0!==t&&(p=t[K],void 0!==p))switch(p.length){case 2:D.vertexAttrib2fv(r,p);break;case 3:D.vertexAttrib3fv(r,p);break;case 4:D.vertexAttrib4fv(r, +p);break;default:D.vertexAttrib1fv(r,p)}}}ba.disableUnusedAttributes()}null!==g&&D.bindBuffer(D.ELEMENT_ARRAY_BUFFER,n.buffer)}n=Infinity;null!==g?n=g.count:void 0!==m&&(n=m.count);g=c.drawRange.start*b;m=null!==f?f.start*b:0;var K=Math.max(g,m);f=Math.max(0,Math.min(n,g+c.drawRange.count*b,m+(null!==f?f.count*b:Infinity))-1-K+1);if(0!==f){if(e.isMesh)if(!0===d.wireframe)ba.setLineWidth(d.wireframeLinewidth*(null===F?R:1)),a.setMode(D.LINES);else switch(e.drawMode){case 0:a.setMode(D.TRIANGLES);break; +case 1:a.setMode(D.TRIANGLE_STRIP);break;case 2:a.setMode(D.TRIANGLE_FAN)}else e.isLine?(d=d.linewidth,void 0===d&&(d=1),ba.setLineWidth(d*(null===F?R:1)),e.isLineSegments?a.setMode(D.LINES):e.isLineLoop?a.setMode(D.LINE_LOOP):a.setMode(D.LINE_STRIP)):e.isPoints&&a.setMode(D.POINTS);c&&c.isInstancedBufferGeometry?0=Ra.maxTextures&&console.warn("THREE.WebGLRenderer: Trying to use "+ +a+" texture units while this GPU supports only "+Ra.maxTextures);aa+=1;return a};this.setTexture2D=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTarget&&(a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);fa.setTexture2D(b,c)}}();this.setTexture=function(){var a=!1;return function(b,c){a||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),a=!0);fa.setTexture2D(b, +c)}}();this.setTextureCube=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);b&&b.isCubeTexture||Array.isArray(b.image)&&6===b.image.length?fa.setTextureCube(b,c):fa.setTextureCubeDynamic(b,c)}}();this.getRenderTarget=function(){return F};this.setRenderTarget=function(a){(F=a)&&void 0===X.get(a).__webglFramebuffer&&fa.setupRenderTarget(a); +var b=null,c=!1;a?(b=X.get(a).__webglFramebuffer,a.isWebGLRenderTargetCube&&(b=b[a.activeCubeFace],c=!0),ob.copy(a.viewport),V.copy(a.scissor),U=a.scissorTest):(ob.copy(Y).multiplyScalar(R),V.copy(ca).multiplyScalar(R),U=ja);I!==b&&(D.bindFramebuffer(D.FRAMEBUFFER,b),I=b);ba.viewport(ob);ba.scissor(V);ba.setScissorTest(U);c&&(c=X.get(a.texture),D.framebufferTexture2D(D.FRAMEBUFFER,D.COLOR_ATTACHMENT0,D.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,c.__webglTexture,a.activeMipMapLevel))};this.readRenderTargetPixels= +function(a,b,c,d,e,f){if(a&&a.isWebGLRenderTarget){var g=X.get(a).__webglFramebuffer;if(g){var h=!1;g!==I&&(D.bindFramebuffer(D.FRAMEBUFFER,g),h=!0);try{var l=a.texture,m=l.format,n=l.type;1023!==m&&ia.convert(m)!==D.getParameter(D.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===n||ia.convert(n)===D.getParameter(D.IMPLEMENTATION_COLOR_READ_TYPE)||1015===n&&(ka.get("OES_texture_float")|| +ka.get("WEBGL_color_buffer_float"))||1016===n&&ka.get("EXT_color_buffer_half_float")?D.checkFramebufferStatus(D.FRAMEBUFFER)===D.FRAMEBUFFER_COMPLETE?0<=b&&b<=a.width-d&&0<=c&&c<=a.height-e&&D.readPixels(b,c,d,e,ia.convert(m),ia.convert(n),f):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."):console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.")}finally{h&& +D.bindFramebuffer(D.FRAMEBUFFER,I)}}}else console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.")};this.copyFramebufferToTexture=function(a,b,c){var d=b.image.width,e=b.image.height,f=ia.convert(b.format);this.setTexture2D(b,0);D.copyTexImage2D(D.TEXTURE_2D,c||0,f,a.x,a.y,d,e,0)};this.copyTextureToTexture=function(a,b,c,d){var e=b.image.width,f=b.image.height,g=ia.convert(c.format),h=ia.convert(c.type);b=b.isDataTexture?b.image.data:b.image;this.setTexture2D(c, +0);D.texSubImage2D(D.TEXTURE_2D,d||0,a.x,a.y,e,f,g,h,b)}}function Ob(a,b){this.name="";this.color=new I(a);this.density=void 0!==b?b:2.5E-4}function Pb(a,b,c){this.name="";this.color=new I(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function rd(){A.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function eb(a){O.call(this);this.type="SpriteMaterial";this.color=new I(16777215);this.map=null;this.rotation=0;this.lights=this.fog=!1;this.setValues(a)} +function Ac(a){A.call(this);this.type="Sprite";this.material=void 0!==a?a:new eb;this.center=new C(.5,.5)}function Bc(){A.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function Cc(a,b){a=a||[];this.bones=a.slice(0);this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===b)this.calculateInverses();else if(this.bones.length===b.length)this.boneInverses=b.slice(0);else for(console.warn("THREE.Skeleton boneInverses is the wrong length."),this.boneInverses= +[],a=0,b=this.bones.length;ac;c++){var n=u[h[c]];var t=u[h[(c+1)%3]];f[0]=Math.min(n,t);f[1]=Math.max(n,t);n=f[0]+","+f[1];void 0===g[n]&&(g[n]={index1:f[0],index2:f[1]})}}for(n in g)m=g[n],h=a.vertices[m.index1],b.push(h.x,h.y,h.z),h=a.vertices[m.index2],b.push(h.x,h.y,h.z)}else if(a&&a.isBufferGeometry)if(h=new p,null!==a.index){l=a.attributes.position;u=a.index;var k=a.groups;0===k.length&&(k=[{start:0,count:u.count,materialIndex:0}]);a=0;for(e=k.length;ac;c++)n=u.getX(m+c),t=u.getX(m+(c+1)%3),f[0]=Math.min(n,t),f[1]=Math.max(n,t),n=f[0]+","+f[1],void 0===g[n]&&(g[n]={index1:f[0],index2:f[1]});for(n in g)m=g[n],h.fromBufferAttribute(l,m.index1),b.push(h.x,h.y,h.z),h.fromBufferAttribute(l,m.index2),b.push(h.x,h.y,h.z)}else for(l=a.attributes.position,m=0,d=l.count/3;mc;c++)g=3*m+c,h.fromBufferAttribute(l,g),b.push(h.x,h.y,h.z),g=3*m+(c+1)%3,h.fromBufferAttribute(l,g),b.push(h.x, +h.y,h.z);this.addAttribute("position",new z(b,3))}function Ec(a,b,c){N.call(this);this.type="ParametricGeometry";this.parameters={func:a,slices:b,stacks:c};this.fromBufferGeometry(new Tb(a,b,c));this.mergeVertices()}function Tb(a,b,c){F.call(this);this.type="ParametricBufferGeometry";this.parameters={func:a,slices:b,stacks:c};var d=[],e=[],f=[],g=[],h=new p,l=new p,m=new p,u=new p,n=new p,t,k,q=b+1;for(t=0;t<=c;t++){var v=t/c;for(k=0;k<=b;k++){var x=k/b;a(x,v,l);e.push(l.x,l.y,l.z);0<=x-1E-5?(a(x- +1E-5,v,m),u.subVectors(l,m)):(a(x+1E-5,v,m),u.subVectors(m,l));0<=v-1E-5?(a(x,v-1E-5,m),n.subVectors(l,m)):(a(x,v+1E-5,m),n.subVectors(m,l));h.crossVectors(u,n).normalize();f.push(h.x,h.y,h.z);g.push(x,v)}}for(t=0;td&&1===a.x&&(l[b]=a.x-1);0===c.x&&0===c.z&&(l[b]=d/2/Math.PI+.5)}F.call(this);this.type="PolyhedronBufferGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};c=c||1;d=d||0;var h=[],l=[];(function(a){for(var c=new p,d=new p,g=new p,h=0;h< +b.length;h+=3){f(b[h+0],c);f(b[h+1],d);f(b[h+2],g);var l,m,k=c,y=d,w=g,B=Math.pow(2,a),G=[];for(m=0;m<=B;m++){G[m]=[];var K=k.clone().lerp(w,m/B),P=y.clone().lerp(w,m/B),H=B-m;for(l=0;l<=H;l++)G[m][l]=0===l&&m===B?K:K.clone().lerp(P,l/H)}for(m=0;me&&(.2>b&&(l[a+0]+=1),.2>c&&(l[a+2]+=1),.2>d&&(l[a+4]+=1))})();this.addAttribute("position",new z(h,3));this.addAttribute("normal",new z(h.slice(),3));this.addAttribute("uv",new z(l,2));0===d?this.computeVertexNormals():this.normalizeNormals()}function Gc(a,b){N.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Ub(a, +b));this.mergeVertices()}function Ub(a,b){pa.call(this,[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],a,b);this.type="TetrahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Hc(a,b){N.call(this);this.type="OctahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new sb(a,b));this.mergeVertices()}function sb(a,b){pa.call(this,[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],a,b);this.type="OctahedronBufferGeometry"; +this.parameters={radius:a,detail:b}}function Ic(a,b){N.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Vb(a,b));this.mergeVertices()}function Vb(a,b){var c=(1+Math.sqrt(5))/2;pa.call(this,[-1,c,0,1,c,0,-1,-c,0,1,-c,0,0,-1,c,0,1,c,0,-1,-c,0,1,-c,c,0,-1,c,0,1,-c,0,-1,-c,0,1],[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],a,b);this.type="IcosahedronBufferGeometry"; +this.parameters={radius:a,detail:b}}function Jc(a,b){N.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Wb(a,b));this.mergeVertices()}function Wb(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;pa.call(this,[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-d,-c,0,-d,c,0,d,-c,0,d,c,-d,-c,0,-d,c,0,d,-c,0,d,c,0,-c,0,-d,c,0,-d,-c,0,d,c,0,d],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18, +0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],a,b);this.type="DodecahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Kc(a,b,c,d,e,f){N.call(this);this.type="TubeGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};void 0!==f&&console.warn("THREE.TubeGeometry: taper has been removed.");a=new Xb(a,b,c,d,e);this.tangents=a.tangents; +this.normals=a.normals;this.binormals=a.binormals;this.fromBufferGeometry(a);this.mergeVertices()}function Xb(a,b,c,d,e){function f(e){u=a.getPointAt(e/b,u);var f=g.normals[e];e=g.binormals[e];for(k=0;k<=d;k++){var m=k/d*Math.PI*2,n=Math.sin(m);m=-Math.cos(m);l.x=m*f.x+n*e.x;l.y=m*f.y+n*e.y;l.z=m*f.z+n*e.z;l.normalize();q.push(l.x,l.y,l.z);h.x=u.x+c*l.x;h.y=u.y+c*l.y;h.z=u.z+c*l.z;r.push(h.x,h.y,h.z)}}F.call(this);this.type="TubeBufferGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d, +closed:e};b=b||64;c=c||1;d=d||8;e=e||!1;var g=a.computeFrenetFrames(b,e);this.tangents=g.tangents;this.normals=g.normals;this.binormals=g.binormals;var h=new p,l=new p,m=new C,u=new p,n,k,r=[],q=[],v=[],x=[];for(n=0;n=b;e-=d)f=Ye(e,a[e],a[e+1],f);f&&tb(f,f.next)&&(Nc(f),f=f.next);return f}function Oc(a,b){if(!a)return a;b||(b=a);do{var c=!1;if(a.steiner||!tb(a,a.next)&&0!==ra(a.prev,a,a.next))a=a.next;else{Nc(a);a=b=a.prev;if(a===a.next)break;c=!0}}while(c||a!==b);return b}function Pc(a,b,c,d,e,f,g){if(a){if(!g&&f){var h=a,l=h;do null===l.z&&(l.z=Zd(l.x,l.y,d,e,f)),l.prevZ=l.prev,l=l.nextZ= +l.next;while(l!==h);l.prevZ.nextZ=null;l.prevZ=null;h=l;var m,u,n,k,r=1;do{l=h;var q=h=null;for(u=0;l;){u++;var p=l;for(m=n=0;mn.x?u.x>r.x?u.x:r.x:n.x>r.x?n.x:r.x,B=u.y>n.y?u.y>r.y?u.y:r.y:n.y> +r.y?n.y:r.y;m=Zd(u.x=m;){if(x!==q.prev&&x!==q.next&&wd(u.x,u.y,n.x,n.y,r.x,r.y,x.x,x.y)&&0<=ra(x.prev,x,x.next)){q=!1;break a}x=x.prevZ}q=!0}}else a:if(q=a,u=q.prev,n=q,r=q.next,0<=ra(u,n,r))q=!1;else{for(m=q.next.next;m!==q.prev;){if(wd(u.x,u.y, +n.x,n.y,r.x,r.y,m.x,m.y)&&0<=ra(m.prev,m,m.next)){q=!1;break a}m=m.next}q=!0}if(q)b.push(l.i/c),b.push(a.i/c),b.push(p.i/c),Nc(a),h=a=p.next;else if(a=p,a===h){if(!g)Pc(Oc(a),b,c,d,e,f,1);else if(1===g){g=b;h=c;l=a;do p=l.prev,q=l.next.next,!tb(p,q)&&Ze(p,l,l.next,q)&&Qc(p,q)&&Qc(q,p)&&(g.push(p.i/h),g.push(l.i/h),g.push(q.i/h),Nc(l),Nc(l.next),l=a=q),l=l.next;while(l!==a);a=l;Pc(a,b,c,d,e,f,2)}else if(2===g)a:{g=a;do{for(h=g.next.next;h!==g.prev;){if(l=g.i!==h.i){l=g;p=h;if(q=l.next.i!==p.i&&l.prev.i!== +p.i){b:{q=l;do{if(q.i!==l.i&&q.next.i!==l.i&&q.i!==p.i&&q.next.i!==p.i&&Ze(q,q.next,l,p)){q=!0;break b}q=q.next}while(q!==l);q=!1}q=!q}if(q=q&&Qc(l,p)&&Qc(p,l)){q=l;u=!1;n=(l.x+p.x)/2;p=(l.y+p.y)/2;do q.y>p!==q.next.y>p&&q.next.y!==q.y&&n<(q.next.x-q.x)*(p-q.y)/(q.next.y-q.y)+q.x&&(u=!u),q=q.next;while(q!==l);q=u}l=q}if(l){a=$e(g,h);g=Oc(g,g.next);a=Oc(a,a.next);Pc(g,b,c,d,e,f);Pc(a,b,c,d,e,f);break a}h=h.next}g=g.next}while(g!==a)}break}}}}function Hg(a,b){return a.x-b.x}function Ig(a,b){var c=b, +d=a.x,e=a.y,f=-Infinity;do{if(e<=c.y&&e>=c.next.y&&c.next.y!==c.y){var g=c.x+(e-c.y)*(c.next.x-c.x)/(c.next.y-c.y);if(g<=d&&g>f){f=g;if(g===d){if(e===c.y)return c;if(e===c.next.y)return c.next}var h=c.x=c.x&&c.x>=g&&d!==c.x&&wd(eh.x)&&Qc(c,a)&&(h=c,m=u)}c=c.next}return h}function Zd(a, +b,c,d,e){a=32767*(a-c)*e;b=32767*(b-d)*e;a=(a|a<<8)&16711935;a=(a|a<<4)&252645135;a=(a|a<<2)&858993459;b=(b|b<<8)&16711935;b=(b|b<<4)&252645135;b=(b|b<<2)&858993459;return(a|a<<1)&1431655765|((b|b<<1)&1431655765)<<1}function Jg(a){var b=a,c=a;do b.xra(a.prev,a,a.next)?0<=ra(a,b,a.next)&&0<=ra(a,a.prev,b):0>ra(a,b,a.prev)||0>ra(a,a.next,b)}function $e(a,b){var c=new $d(a.i,a.x,a.y),d=new $d(b.i,b.x,b.y),e=a.next,f=b.prev;a.next=b;b.prev=a;c.next=e;e.prev=c;d.next=c;c.prev=d;f.next=d;d.prev=f;return d}function Ye(a,b,c,d){a=new $d(a,b,c);d?(a.next=d.next,a.prev=d,d.next.prev=a,d.next=a): +(a.prev=a,a.next=a);return a}function Nc(a){a.next.prev=a.prev;a.prev.next=a.next;a.prevZ&&(a.prevZ.nextZ=a.nextZ);a.nextZ&&(a.nextZ.prevZ=a.prevZ)}function $d(a,b,c){this.i=a;this.x=b;this.y=c;this.nextZ=this.prevZ=this.z=this.next=this.prev=null;this.steiner=!1}function af(a){var b=a.length;2k;k++){var n=m[f[k]];var t=m[f[(k+1)%3]];d[0]=Math.min(n,t);d[1]=Math.max(n,t);n=d[0]+","+d[1];void 0===e[n]?e[n]={index1:d[0],index2:d[1],face1:h,face2:void 0}:e[n].face2=h}for(n in e)if(d=e[n],void 0===d.face2||g[d.face1].normal.dot(g[d.face2].normal)<=b)f=a[d.index1],c.push(f.x,f.y,f.z),f=a[d.index2],c.push(f.x,f.y,f.z);this.addAttribute("position",new z(c,3))}function xb(a,b,c,d,e,f,g,h){N.call(this);this.type="CylinderGeometry";this.parameters={radiusTop:a, +radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};this.fromBufferGeometry(new Ya(a,b,c,d,e,f,g,h));this.mergeVertices()}function Ya(a,b,c,d,e,f,g,h){function l(c){var e,f=new C,l=new p,u=0,v=!0===c?a:b,w=!0===c?1:-1;var A=q;for(e=1;e<=d;e++)n.push(0,x*w,0),t.push(0,w,0),r.push(.5,.5),q++;var z=q;for(e=0;e<=d;e++){var E=e/d*h+g,F=Math.cos(E);E=Math.sin(E);l.x=v*E;l.y=x*w;l.z=v*F;n.push(l.x,l.y,l.z);t.push(0,w,0);f.x=.5*F+.5;f.y=.5*E*w+.5;r.push(f.x,f.y); +q++}for(e=0;ethis.duration&&this.resetDuration();this.optimize()}function Md(a){this.manager=void 0!==a?a:ma;this.textures={}}function ee(a){this.manager=void 0!==a?a:ma}function ic(){}function fe(a){"boolean"===typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),a=void 0);this.manager=void 0!==a?a:ma;this.withCredentials=!1}function ff(a){this.manager=void 0!==a?a:ma;this.texturePath=""} +function ge(a){"undefined"===typeof createImageBitmap&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported.");"undefined"===typeof fetch&&console.warn("THREE.ImageBitmapLoader: fetch() not supported.");this.manager=void 0!==a?a:ma;this.options=void 0}function he(){this.type="ShapePath";this.subPaths=[];this.currentPath=null}function ie(a){this.type="Font";this.data=a}function gf(a){this.manager=void 0!==a?a:ma}function je(a){this.manager=void 0!==a?a:ma}function hf(){this.type= +"StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new la;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new la;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=!1}function cd(a,b,c){A.call(this);this.type="CubeCamera";var d=new la(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new p(1,0,0));this.add(d);var e=new la(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new p(-1,0,0));this.add(e);var f=new la(90,1,a,b);f.up.set(0,0,1);f.lookAt(new p(0,1,0));this.add(f);var g=new la(90, +1,a,b);g.up.set(0,0,-1);g.lookAt(new p(0,-1,0));this.add(g);var h=new la(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new p(0,0,1));this.add(h);var l=new la(90,1,a,b);l.up.set(0,-1,0);l.lookAt(new p(0,0,-1));this.add(l);this.renderTarget=new Ib(c,c,{format:1022,magFilter:1006,minFilter:1006});this.renderTarget.texture.name="CubeCamera";this.update=function(a,b){null===this.parent&&this.updateMatrixWorld();var c=this.renderTarget,m=c.texture.generateMipmaps;c.texture.generateMipmaps=!1;c.activeCubeFace=0;a.render(b, +d,c);c.activeCubeFace=1;a.render(b,e,c);c.activeCubeFace=2;a.render(b,f,c);c.activeCubeFace=3;a.render(b,g,c);c.activeCubeFace=4;a.render(b,h,c);c.texture.generateMipmaps=m;c.activeCubeFace=5;a.render(b,l,c);a.setRenderTarget(null)};this.clear=function(a,b,c,d){for(var e=this.renderTarget,f=0;6>f;f++)e.activeCubeFace=f,a.setRenderTarget(e),a.clear(b,c,d);a.setRenderTarget(null)}}function ke(){A.call(this);this.type="AudioListener";this.context=le.getContext();this.gain=this.context.createGain();this.gain.connect(this.context.destination); +this.filter=null}function jc(a){A.call(this);this.type="Audio";this.context=a.context;this.gain=this.context.createGain();this.gain.connect(a.getInput());this.autoplay=!1;this.buffer=null;this.loop=!1;this.offset=this.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";this.filters=[]}function me(a){jc.call(this,a);this.panner=this.context.createPanner();this.panner.connect(this.gain)}function ne(a,b){this.analyser=a.context.createAnalyser();this.analyser.fftSize= +void 0!==b?b:2048;this.data=new Uint8Array(this.analyser.frequencyBinCount);a.getOutput().connect(this.analyser)}function oe(a,b,c){this.binding=a;this.valueSize=c;a=Float64Array;switch(b){case "quaternion":b=this._slerp;break;case "string":case "bool":a=Array;b=this._select;break;default:b=this._lerp}this.buffer=new a(4*c);this._mixBufferRegion=b;this.referenceCount=this.useCount=this.cumulativeWeight=0}function jf(a,b,c){c=c||qa.parseTrackName(b);this._targetGroup=a;this._bindings=a.subscribe_(b, +c)}function qa(a,b,c){this.path=b;this.parsedPath=c||qa.parseTrackName(b);this.node=qa.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function kf(){this.uuid=S.generateUUID();this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var a={};this._indicesByUUID=a;for(var b=0,c=arguments.length;b!==c;++b)a[arguments[b].uuid]=b;this._paths=[];this._parsedPaths=[];this._bindings=[];this._bindingsIndicesByPath={};var d=this;this.stats={objects:{get total(){return d._objects.length}, +get inUse(){return this.total-d.nCachedObjects_}},get bindingsPerObject(){return d._bindings.length}}}function lf(a,b,c){this._mixer=a;this._clip=b;this._localRoot=c||null;a=b.tracks;b=a.length;c=Array(b);for(var d={endingStart:2400,endingEnd:2400},e=0;e!==b;++e){var f=a[e].createInterpolant(null);c[e]=f;f.settings=d}this._interpolantSettings=d;this._interpolants=c;this._propertyBindings=Array(b);this._weightInterpolant=this._timeScaleInterpolant=this._byClipCacheIndex=this._cacheIndex=null;this.loop= +2201;this._loopCount=-1;this._startTime=null;this.time=0;this._effectiveWeight=this.weight=this._effectiveTimeScale=this.timeScale=1;this.repetitions=Infinity;this.paused=!1;this.enabled=!0;this.clampWhenFinished=!1;this.zeroSlopeAtEnd=this.zeroSlopeAtStart=!0}function pe(a){this._root=a;this._initMemoryManager();this.time=this._accuIndex=0;this.timeScale=1}function Nd(a,b){"string"===typeof a&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),a=b);this.value=a}function qe(){F.call(this); +this.type="InstancedBufferGeometry";this.maxInstancedCount=void 0}function re(a,b,c,d){this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0===d}function kc(a,b){this.array=a;this.stride=b;this.count=void 0!==a?a.length/b:0;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.version=0}function se(a,b,c){kc.call(this,a,b);this.meshPerAttribute=c||1}function te(a,b,c){T.call(this,a,b);this.meshPerAttribute=c||1}function mf(a,b,c,d){this.ray=new qb(a,b);this.near=c||0;this.far=d||Infinity; +this.params={Mesh:{},Line:{},LOD:{},Points:{threshold:1},Sprite:{}};Object.defineProperties(this.params,{PointCloud:{get:function(){console.warn("THREE.Raycaster: params.PointCloud has been renamed to params.Points.");return this.Points}}})}function nf(a,b){return a.distance-b.distance}function ue(a,b,c,d){if(!1!==a.visible&&(a.raycast(b,c),!0===d)){a=a.children;d=0;for(var e=a.length;dc;c++,d++){var e= +c/32*Math.PI*2,f=d/32*Math.PI*2;b.push(Math.cos(e),Math.sin(e),1,Math.cos(f),Math.sin(f),1)}a.addAttribute("position",new z(b,3));b=new U({fog:!1});this.cone=new aa(a,b);this.add(this.cone);this.update()}function rf(a){var b=[];a&&a.isBone&&b.push(a);for(var c=0;ca?-1:0e;e++)8===e||13===e||18===e||23===e?b[e]="-":14===e?b[e]="4":(2>=c&&(c=33554432+16777216*Math.random()|0),d=c&15,c>>=4,b[e]=a[19===e?d&3|8:d]);return b.join("")}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a,b){return(a%b+b)%b},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},lerp:function(a, -b,c){return(1-c)*a+c*b},smoothstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*(3-2*a)},smootherstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*a*(a*(6*a-15)+10)},randInt:function(a,b){return a+Math.floor(Math.random()*(b-a+1))},randFloat:function(a,b){return a+Math.random()*(b-a)},randFloatSpread:function(a){return a*(.5-Math.random())},degToRad:function(a){return a*Y.DEG2RAD},radToDeg:function(a){return a*Y.RAD2DEG},isPowerOfTwo:function(a){return 0=== -(a&a-1)&&0!==a},nearestPowerOfTwo:function(a){return Math.pow(2,Math.round(Math.log(a)/Math.LN2))},nextPowerOfTwo:function(a){a--;a|=a>>1;a|=a>>2;a|=a>>4;a|=a>>8;a|=a>>16;a++;return a}};Object.defineProperties(C.prototype,{width:{get:function(){return this.x},set:function(a){this.x=a}},height:{get:function(){return this.y},set:function(a){this.y=a}}});Object.assign(C.prototype,{isVector2:!0,set:function(a,b){this.x=a;this.y=b;return this},setScalar:function(a){this.y=this.x=a;return this},setX:function(a){this.x= -a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."), -this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this},addScalar:function(a){this.x+=a;this.y+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;return this},subScalar:function(a){this.x-=a;this.y-=a;return this}, -subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this},multiply:function(a){this.x*=a.x;this.y*=a.y;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;return this},divide:function(a){this.x/=a.x;this.y/=a.y;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);return this},clamp:function(a,b){this.x=Math.max(a.x, -Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));return this},clampScalar:function(){var a=new C,b=new C;return function(c,d){a.set(c,c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this},round:function(){this.x=Math.round(this.x); -this.y=Math.round(this.y);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);return this},negate:function(){this.x=-this.x;this.y=-this.y;return this},dot:function(a){return this.x*a.x+this.y*a.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length()|| -1)},angle:function(){var a=Math.atan2(this.y,this.x);0>a&&(a+=2*Math.PI);return a},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x;a=this.y-a.y;return b*b+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b, -a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);return this},rotateAround:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=this.x- -a.x,f=this.y-a.y;this.x=e*c-f*d+a.x;this.y=e*d+f*c+a.y;return this}});var hf=0;ba.DEFAULT_IMAGE=void 0;ba.DEFAULT_MAPPING=300;Object.defineProperty(ba.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(ba.prototype,xa.prototype,{constructor:ba,isTexture:!0,clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.image=a.image;this.mipmaps=a.mipmaps.slice(0);this.mapping=a.mapping;this.wrapS=a.wrapS;this.wrapT=a.wrapT;this.magFilter= -a.magFilter;this.minFilter=a.minFilter;this.anisotropy=a.anisotropy;this.format=a.format;this.type=a.type;this.offset.copy(a.offset);this.repeat.copy(a.repeat);this.generateMipmaps=a.generateMipmaps;this.premultiplyAlpha=a.premultiplyAlpha;this.flipY=a.flipY;this.unpackAlignment=a.unpackAlignment;this.encoding=a.encoding;return this},toJSON:function(a){if(void 0!==a.textures[this.uuid])return a.textures[this.uuid];var b={metadata:{version:4.5,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid, -name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var c=this.image;void 0===c.uuid&&(c.uuid=Y.generateUUID());if(void 0===a.images[c.uuid]){var d=a.images,e=c.uuid,f=c.uuid,g;void 0!==c.toDataURL?g=c:(g=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),g.width=c.width,g.height= -c.height,g.getContext("2d").drawImage(c,0,0,c.width,c.height));g=2048a.x||1a.x?0:1;break;case 1002:a.x=1===Math.abs(Math.floor(a.x)% -2)?Math.ceil(a.x)-a.x:a.x-Math.floor(a.x)}if(0>a.y||1a.y?0:1;break;case 1002:a.y=1===Math.abs(Math.floor(a.y)%2)?Math.ceil(a.y)-a.y:a.y-Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}});Object.assign(fa.prototype,{isVector4:!0,set:function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.w=d;return this},setScalar:function(a){this.w=this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this}, -setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;case 3:this.w=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z, -this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addScaledVector:function(a, -b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;this.w-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(a){this.x*= -a;this.y*=a;this.z*=a;this.w*=a;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12]*e;this.y=a[1]*b+a[5]*c+a[9]*d+a[13]*e;this.z=a[2]*b+a[6]*c+a[10]*d+a[14]*e;this.w=a[3]*b+a[7]*c+a[11]*d+a[15]*e;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},setAxisAngleFromQuaternion:function(a){this.w=2*Math.acos(a.w);var b=Math.sqrt(1-a.w*a.w);1E-4>b?(this.x=1,this.z=this.y=0):(this.x=a.x/b,this.y=a.y/b,this.z=a.z/ -b);return this},setAxisAngleFromRotationMatrix:function(a){var b,c,d;a=a.elements;var e=a[0];d=a[4];var f=a[8],g=a[1],h=a[5],k=a[9];c=a[2];b=a[6];var m=a[10];if(.01>Math.abs(d-g)&&.01>Math.abs(f-c)&&.01>Math.abs(k-b)){if(.1>Math.abs(d+g)&&.1>Math.abs(f+c)&&.1>Math.abs(k+b)&&.1>Math.abs(e+h+m-3))return this.set(1,0,0,0),this;a=Math.PI;e=(e+1)/2;h=(h+1)/2;m=(m+1)/2;d=(d+g)/4;f=(f+c)/4;k=(k+b)/4;e>h&&e>m?.01>e?(b=0,d=c=.707106781):(b=Math.sqrt(e),c=d/b,d=f/b):h>m?.01>h?(b=.707106781,c=0,d=.707106781): -(c=Math.sqrt(h),b=d/c,d=k/c):.01>m?(c=b=.707106781,d=0):(d=Math.sqrt(m),b=f/d,c=k/d);this.set(b,c,d,a);return this}a=Math.sqrt((b-k)*(b-k)+(f-c)*(f-c)+(g-d)*(g-d));.001>Math.abs(a)&&(a=1);this.x=(b-k)/a;this.y=(f-c)/a;this.z=(g-d)/a;this.w=Math.acos((e+h+m-1)/2);return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);this.w=Math.min(this.w,a.w);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z, -a.z);this.w=Math.max(this.w,a.w);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));this.w=Math.max(a.w,Math.min(b.w,this.w));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new fa,b=new fa);a.set(c,c,c,c);b.set(d,d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b, -c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);this.w=Math.floor(this.w);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);this.w=Math.ceil(this.w);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);this.w=Math.round(this.w);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y): -Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);this.w=0>this.w?Math.ceil(this.w):Math.floor(this.w);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z+this.w*a.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},lengthManhattan:function(){return Math.abs(this.x)+ -Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;this.w+=(a.w-this.w)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){void 0=== -b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];this.w=a[b+3];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;a[b+3]=this.w;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);this.w=a.getW(b);return this}});Object.assign(Cb.prototype,xa.prototype,{isWebGLRenderTarget:!0,setSize:function(a,b){if(this.width!== -a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0,0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone();this.depthBuffer=a.depthBuffer;this.stencilBuffer=a.stencilBuffer;this.depthTexture=a.depthTexture;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Db.prototype=Object.create(Cb.prototype); -Db.prototype.constructor=Db;Db.prototype.isWebGLRenderTargetCube=!0;Object.assign(oa,{slerp:function(a,b,c,d){return c.copy(a).slerp(b,d)},slerpFlat:function(a,b,c,d,e,f,g){var h=c[d+0],k=c[d+1],m=c[d+2];c=c[d+3];d=e[f+0];var q=e[f+1],l=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==q||m!==l){f=1-g;var p=h*d+k*q+m*l+c*e,r=0<=p?1:-1,n=1-p*p;n>Number.EPSILON&&(n=Math.sqrt(n),p=Math.atan2(n,p*r),f=Math.sin(f*p)/n,g=Math.sin(g*p)/n);r*=g;h=h*f+d*r;k=k*f+q*r;m=m*f+l*r;c=c*f+e*r;f===1-g&&(g=1/Math.sqrt(h*h+k*k+m* -m+c*c),h*=g,k*=g,m*=g,c*=g)}a[b]=h;a[b+1]=k;a[b+2]=m;a[b+3]=c}});Object.defineProperties(oa.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},w:{get:function(){return this._w},set:function(a){this._w=a;this.onChangeCallback()}}});Object.assign(oa.prototype,{set:function(a,b,c,d){this._x= -a;this._y=b;this._z=c;this._w=d;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._w)},copy:function(a){this._x=a.x;this._y=a.y;this._z=a.z;this._w=a.w;this.onChangeCallback();return this},setFromEuler:function(a,b){if(!a||!a.isEuler)throw Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var c=a._x,d=a._y,e=a._z,f=a.order,g=Math.cos,h=Math.sin,k=g(c/2),m=g(d/2),g=g(e/2),c=h(c/2),d= -h(d/2),e=h(e/2);"XYZ"===f?(this._x=c*m*g+k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g-c*d*e):"YXZ"===f?(this._x=c*m*g+k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g+c*d*e):"ZXY"===f?(this._x=c*m*g-k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g-c*d*e):"ZYX"===f?(this._x=c*m*g-k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g+c*d*e):"YZX"===f?(this._x=c*m*g+k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g-c*d*e):"XZY"===f&&(this._x=c*m*g- -k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g+c*d*e);if(!1!==b)this.onChangeCallback();return this},setFromAxisAngle:function(a,b){var c=b/2,d=Math.sin(c);this._x=a.x*d;this._y=a.y*d;this._z=a.z*d;this._w=Math.cos(c);this.onChangeCallback();return this},setFromRotationMatrix:function(a){var b=a.elements,c=b[0];a=b[4];var d=b[8],e=b[1],f=b[5],g=b[9],h=b[2],k=b[6],b=b[10],m=c+f+b;0f&&c>b?(c=2*Math.sqrt(1+ -c-f-b),this._w=(k-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y=.25*c,this._z=(g+k)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+h)/c,this._y=(g+k)/c,this._z=.25*c);this.onChangeCallback();return this},setFromUnitVectors:function(){var a=new n,b;return function(c,d){void 0===a&&(a=new n);b=c.dot(d)+1;1E-6>b?(b=0,Math.abs(c.x)>Math.abs(c.z)?a.set(-c.y,c.x,0):a.set(0,-c.z,c.y)):a.crossVectors(c,d);this._x=a.x;this._y= -a.y;this._z=a.z;this._w=b;return this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){this._x*=-1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(a){return this._x*a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length(); -0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this},multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z,f=a._w,g=b._x,h=b._y, -k=b._z,m=b._w;this._x=c*m+f*g+d*k-e*h;this._y=d*m+f*h+e*g-c*k;this._z=e*m+f*k+c*h-d*g;this._w=f*m-c*g-d*h-e*k;this.onChangeCallback();return this},slerp:function(a,b){if(0===b)return this;if(1===b)return this.copy(a);var c=this._x,d=this._y,e=this._z,f=this._w,g=f*a._w+c*a._x+d*a._y+e*a._z;0>g?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a);if(1<=g)return this._w=f,this._x=c,this._y=d,this._z=e,this;var h=Math.sqrt(1-g*g);if(.001>Math.abs(h))return this._w=.5*(f+this._w), -this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var k=Math.atan2(h,g),g=Math.sin((1-b)*k)/h,h=Math.sin(b*k)/h;this._w=f*g+this._w*h;this._x=c*g+this._x*h;this._y=d*g+this._y*h;this._z=e*g+this._z*h;this.onChangeCallback();return this},equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+1];this._z=a[b+2];this._w=a[b+3];this.onChangeCallback();return this},toArray:function(a, -b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(n.prototype,{isVector3:!0,set:function(a,b,c){this.x=a;this.y=b;this.z=c;return this},setScalar:function(a){this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setComponent:function(a,b){switch(a){case 0:this.x= -b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."), -this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z; -return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this},multiply:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(a,b);this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;return this},multiplyVectors:function(a,b){this.x=a.x* -b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},applyEuler:function(){var a=new oa;return function(b){b&&b.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a=new oa;return function(b,c){return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[3]*c+a[6]*d;this.y=a[1]* -b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;var e=1/(a[3]*b+a[7]*c+a[11]*d+a[15]);this.x=(a[0]*b+a[4]*c+a[8]*d+a[12])*e;this.y=(a[1]*b+a[5]*c+a[9]*d+a[13])*e;this.z=(a[2]*b+a[6]*c+a[10]*d+a[14])*e;return this},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a=a.w;var h=a*b+f*d-g*c,k=a*c+g*b-e*d,m=a*d+e*c-f*b,b=-e*b-f*c-g*d;this.x=h*a+b*-e+k*-g-m*-f;this.y=k*a+b*-f+m*-e-h*-g;this.z=m*a+b* --g+h*-f-k*-e;return this},project:function(){var a=new K;return function(b){a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyMatrix4(a)}}(),unproject:function(){var a=new K;return function(b){a.multiplyMatrices(b.matrixWorld,a.getInverse(b.projectionMatrix));return this.applyMatrix4(a)}}(),transformDirection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d;this.y=a[1]*b+a[5]*c+a[9]*d;this.z=a[2]*b+a[6]*c+a[10]*d;return this.normalize()}, -divide:function(a){this.x/=a.x;this.y/=a.y;this.z/=a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));return this}, -clampScalar:function(){var a=new n,b=new n;return function(c,d){a.set(c,c,c);b.set(d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y); -this.z=Math.round(this.z);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z* -this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."), -this.crossVectors(a,b);var c=this.x,d=this.y,e=this.z;this.x=d*a.z-e*a.y;this.y=e*a.x-c*a.z;this.z=c*a.y-d*a.x;return this},crossVectors:function(a,b){var c=a.x,d=a.y,e=a.z,f=b.x,g=b.y,h=b.z;this.x=d*h-e*g;this.y=e*f-c*h;this.z=c*g-d*f;return this},projectOnVector:function(a){var b=a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a=new n;return function(b){a.copy(this).projectOnVector(b);return this.sub(a)}}(),reflect:function(){var a=new n;return function(b){return this.sub(a.copy(b).multiplyScalar(2* -this.dot(b)))}}(),angleTo:function(a){a=this.dot(a)/Math.sqrt(this.lengthSq()*a.lengthSq());return Math.acos(Y.clamp(a,-1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x,c=this.y-a.y;a=this.z-a.z;return b*b+c*c+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)*a.radius;this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)* -a.radius;this.z=b*Math.cos(a.theta);return this},setFromCylindrical:function(a){this.x=a.radius*Math.sin(a.theta);this.y=a.y;this.z=a.radius*Math.cos(a.theta);return this},setFromMatrixPosition:function(a){a=a.elements;this.x=a[12];this.y=a[13];this.z=a[14];return this},setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),c=this.setFromMatrixColumn(a,1).length();a=this.setFromMatrixColumn(a,2).length();this.x=b;this.y=c;this.z=a;return this},setFromMatrixColumn:function(a,b){return this.fromArray(a.elements, -4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);return this}});Object.assign(K.prototype, -{isMatrix4:!0,set:function(a,b,c,d,e,f,g,h,k,m,q,l,p,r,n,t){var y=this.elements;y[0]=a;y[4]=b;y[8]=c;y[12]=d;y[1]=e;y[5]=f;y[9]=g;y[13]=h;y[2]=k;y[6]=m;y[10]=q;y[14]=l;y[3]=p;y[7]=r;y[11]=n;y[15]=t;return this},identity:function(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this},clone:function(){return(new K).fromArray(this.elements)},copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10]; -b[11]=a[11];b[12]=a[12];b[13]=a[13];b[14]=a[14];b[15]=a[15];return this},copyPosition:function(a){var b=this.elements;a=a.elements;b[12]=a[12];b[13]=a[13];b[14]=a[14];return this},extractBasis:function(a,b,c){a.setFromMatrixColumn(this,0);b.setFromMatrixColumn(this,1);c.setFromMatrixColumn(this,2);return this},makeBasis:function(a,b,c){this.set(a.x,b.x,c.x,0,a.y,b.y,c.y,0,a.z,b.z,c.z,0,0,0,0,1);return this},extractRotation:function(){var a=new n;return function(b){var c=this.elements,d=b.elements, -e=1/a.setFromMatrixColumn(b,0).length(),f=1/a.setFromMatrixColumn(b,1).length();b=1/a.setFromMatrixColumn(b,2).length();c[0]=d[0]*e;c[1]=d[1]*e;c[2]=d[2]*e;c[4]=d[4]*f;c[5]=d[5]*f;c[6]=d[6]*f;c[8]=d[8]*b;c[9]=d[9]*b;c[10]=d[10]*b;return this}}(),makeRotationFromEuler:function(a){a&&a.isEuler||console.error("THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var b=this.elements,c=a.x,d=a.y,e=a.z,f=Math.cos(c),c=Math.sin(c),g=Math.cos(d),d=Math.sin(d), -h=Math.cos(e),e=Math.sin(e);if("XYZ"===a.order){a=f*h;var k=f*e,m=c*h,q=c*e;b[0]=g*h;b[4]=-g*e;b[8]=d;b[1]=k+m*d;b[5]=a-q*d;b[9]=-c*g;b[2]=q-a*d;b[6]=m+k*d;b[10]=f*g}else"YXZ"===a.order?(a=g*h,k=g*e,m=d*h,q=d*e,b[0]=a+q*c,b[4]=m*c-k,b[8]=f*d,b[1]=f*e,b[5]=f*h,b[9]=-c,b[2]=k*c-m,b[6]=q+a*c,b[10]=f*g):"ZXY"===a.order?(a=g*h,k=g*e,m=d*h,q=d*e,b[0]=a-q*c,b[4]=-f*e,b[8]=m+k*c,b[1]=k+m*c,b[5]=f*h,b[9]=q-a*c,b[2]=-f*d,b[6]=c,b[10]=f*g):"ZYX"===a.order?(a=f*h,k=f*e,m=c*h,q=c*e,b[0]=g*h,b[4]=m*d-k,b[8]=a* -d+q,b[1]=g*e,b[5]=q*d+a,b[9]=k*d-m,b[2]=-d,b[6]=c*g,b[10]=f*g):"YZX"===a.order?(a=f*g,k=f*d,m=c*g,q=c*d,b[0]=g*h,b[4]=q-a*e,b[8]=m*e+k,b[1]=e,b[5]=f*h,b[9]=-c*h,b[2]=-d*h,b[6]=k*e+m,b[10]=a-q*e):"XZY"===a.order&&(a=f*g,k=f*d,m=c*g,q=c*d,b[0]=g*h,b[4]=-e,b[8]=d*h,b[1]=a*e+q,b[5]=f*h,b[9]=k*e-m,b[2]=m*e-k,b[6]=c*h,b[10]=q*e+a);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},makeRotationFromQuaternion:function(a){var b=this.elements,c=a._x,d=a._y,e=a._z,f=a._w,g=c+c,h=d+d,k=e+e;a= -c*g;var m=c*h,c=c*k,q=d*h,d=d*k,e=e*k,g=f*g,h=f*h,f=f*k;b[0]=1-(q+e);b[4]=m-f;b[8]=c+h;b[1]=m+f;b[5]=1-(a+e);b[9]=d-g;b[2]=c-h;b[6]=d+g;b[10]=1-(a+q);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},lookAt:function(){var a=new n,b=new n,c=new n;return function(d,e,f){var g=this.elements;c.subVectors(d,e);0===c.lengthSq()&&(c.z=1);c.normalize();a.crossVectors(f,c);0===a.lengthSq()&&(1===Math.abs(f.z)?c.x+=1E-4:c.z+=1E-4,c.normalize(),a.crossVectors(f,c));a.normalize();b.crossVectors(c, -a);g[0]=a.x;g[4]=b.x;g[8]=c.x;g[1]=a.y;g[5]=b.y;g[9]=c.y;g[2]=a.z;g[6]=b.z;g[10]=c.z;return this}}(),multiply:function(a,b){return void 0!==b?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(a,b)):this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements,e=this.elements,f=c[0],g=c[4],h=c[8],k=c[12],m=c[1],q=c[5],l=c[9], -p=c[13],r=c[2],n=c[6],t=c[10],y=c[14],x=c[3],u=c[7],H=c[11],c=c[15],w=d[0],I=d[4],W=d[8],D=d[12],O=d[1],B=d[5],F=d[9],C=d[13],z=d[2],E=d[6],G=d[10],K=d[14],P=d[3],M=d[7],V=d[11],d=d[15];e[0]=f*w+g*O+h*z+k*P;e[4]=f*I+g*B+h*E+k*M;e[8]=f*W+g*F+h*G+k*V;e[12]=f*D+g*C+h*K+k*d;e[1]=m*w+q*O+l*z+p*P;e[5]=m*I+q*B+l*E+p*M;e[9]=m*W+q*F+l*G+p*V;e[13]=m*D+q*C+l*K+p*d;e[2]=r*w+n*O+t*z+y*P;e[6]=r*I+n*B+t*E+y*M;e[10]=r*W+n*F+t*G+y*V;e[14]=r*D+n*C+t*K+y*d;e[3]=x*w+u*O+H*z+c*P;e[7]=x*I+u*B+H*E+c*M;e[11]=x*W+u*F+H*G+ -c*V;e[15]=x*D+u*C+H*K+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[4]*=a;b[8]*=a;b[12]*=a;b[1]*=a;b[5]*=a;b[9]*=a;b[13]*=a;b[2]*=a;b[6]*=a;b[10]*=a;b[14]*=a;b[3]*=a;b[7]*=a;b[11]*=a;b[15]*=a;return this},applyToBufferAttribute:function(){var a=new n;return function(b){for(var c=0,d=b.count;cthis.determinant()&&(g=-g);c.x=f[12];c.y=f[13];c.z=f[14];b.copy(this);c=1/g;var f=1/h,m=1/k;b.elements[0]*=c;b.elements[1]*=c;b.elements[2]*=c;b.elements[4]*=f;b.elements[5]*=f;b.elements[6]*=f;b.elements[8]*=m;b.elements[9]*=m;b.elements[10]*=m;d.setFromRotationMatrix(b);e.x=g;e.y=h;e.z=k;return this}}(),makePerspective:function(a,b,c,d,e,f){void 0===f&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs."); -var g=this.elements;g[0]=2*e/(b-a);g[4]=0;g[8]=(b+a)/(b-a);g[12]=0;g[1]=0;g[5]=2*e/(c-d);g[9]=(c+d)/(c-d);g[13]=0;g[2]=0;g[6]=0;g[10]=-(f+e)/(f-e);g[14]=-2*f*e/(f-e);g[3]=0;g[7]=0;g[11]=-1;g[15]=0;return this},makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=1/(b-a),k=1/(c-d),m=1/(f-e);g[0]=2*h;g[4]=0;g[8]=0;g[12]=-((b+a)*h);g[1]=0;g[5]=2*k;g[9]=0;g[13]=-((c+d)*k);g[2]=0;g[6]=0;g[10]=-2*m;g[14]=-((f+e)*m);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b=this.elements; -a=a.elements;for(var c=0;16>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;16>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];a[b+9]=c[9];a[b+10]=c[10];a[b+11]=c[11];a[b+12]=c[12];a[b+13]=c[13];a[b+14]=c[14];a[b+15]=c[15];return a}});db.prototype=Object.create(ba.prototype); -db.prototype.constructor=db;db.prototype.isDataTexture=!0;Xa.prototype=Object.create(ba.prototype);Xa.prototype.constructor=Xa;Xa.prototype.isCubeTexture=!0;Object.defineProperty(Xa.prototype,"images",{get:function(){return this.image},set:function(a){this.image=a}});var Ce=new ba,De=new Xa,xe=[],ze=[],Be=new Float32Array(16),Ae=new Float32Array(9);He.prototype.setValue=function(a,b){for(var c=this.seq,d=0,e=c.length;d!==e;++d){var f=c[d];f.setValue(a,b[f.id])}};var Pd=/([\w\d_]+)(\])?(\[|\.)?/g; -eb.prototype.setValue=function(a,b,c){b=this.map[b];void 0!==b&&b.setValue(a,c,this.renderer)};eb.prototype.setOptional=function(a,b,c){b=b[c];void 0!==b&&this.setValue(a,c,b)};eb.upload=function(a,b,c,d){for(var e=0,f=b.length;e!==f;++e){var g=b[e],h=c[g.id];!1!==h.needsUpdate&&g.setValue(a,h.value,d)}};eb.seqWithValue=function(a,b){for(var c=[],d=0,e=a.length;d!==e;++d){var f=a[d];f.id in b&&c.push(f)}return c};var lg={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175, -beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410, -darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200, -khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322, -mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673, -peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285, -yellow:16776960,yellowgreen:10145074};Object.assign(G.prototype,{isColor:!0,r:1,g:1,b:1,set:function(a){a&&a.isColor?this.copy(a):"number"===typeof a?this.setHex(a):"string"===typeof a&&this.setStyle(a);return this},setScalar:function(a){this.b=this.g=this.r=a;return this},setHex:function(a){a=Math.floor(a);this.r=(a>>16&255)/255;this.g=(a>>8&255)/255;this.b=(a&255)/255;return this},setRGB:function(a,b,c){this.r=a;this.g=b;this.b=c;return this},setHSL:function(){function a(a,c,d){0>d&&(d+=1);1d?c:d<2/3?a+6*(c-a)*(2/3-d):a}return function(b,c,d){b=Y.euclideanModulo(b,1);c=Y.clamp(c,0,1);d=Y.clamp(d,0,1);0===c?this.r=this.g=this.b=d:(c=.5>=d?d*(1+c):d+c-d*c,d=2*d-c,this.r=a(d,c,b+1/3),this.g=a(d,c,b),this.b=a(d,c,b-1/3));return this}}(),setStyle:function(a){function b(b){void 0!==b&&1>parseFloat(b)&&console.warn("THREE.Color: Alpha component of "+a+" will be ignored.")}var c;if(c=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(a)){var d=c[2];switch(c[1]){case "rgb":case "rgba":if(c= -/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(255,parseInt(c[1],10))/255,this.g=Math.min(255,parseInt(c[2],10))/255,this.b=Math.min(255,parseInt(c[3],10))/255,b(c[5]),this;if(c=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(100,parseInt(c[1],10))/100,this.g=Math.min(100,parseInt(c[2],10))/100,this.b=Math.min(100,parseInt(c[3],10))/100,b(c[5]),this;break;case "hsl":case "hsla":if(c=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d)){var d= -parseFloat(c[1])/360,e=parseInt(c[2],10)/100,f=parseInt(c[3],10)/100;b(c[5]);return this.setHSL(d,e,f)}}}else if(c=/^\#([A-Fa-f0-9]+)$/.exec(a)){c=c[1];d=c.length;if(3===d)return this.r=parseInt(c.charAt(0)+c.charAt(0),16)/255,this.g=parseInt(c.charAt(1)+c.charAt(1),16)/255,this.b=parseInt(c.charAt(2)+c.charAt(2),16)/255,this;if(6===d)return this.r=parseInt(c.charAt(0)+c.charAt(1),16)/255,this.g=parseInt(c.charAt(2)+c.charAt(3),16)/255,this.b=parseInt(c.charAt(4)+c.charAt(5),16)/255,this}a&&0=h?k/(e+f):k/(2-e-f);switch(e){case b:g=(c-d)/k+(c 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.86267 + (0.49788 + 0.01436 * y ) * y;\n\tfloat b = 3.45068 + (4.18814 + y) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt( 1.0 - x * x ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tvec3 result = vec3( LTC_ClippedSphereFormFactor( vectorFormFactor ) );\n\treturn result;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n", +hasEventListener:function(a,b){if(void 0===this._listeners)return!1;var c=this._listeners;return void 0!==c[a]&&-1!==c[a].indexOf(b)},removeEventListener:function(a,b){void 0!==this._listeners&&(a=this._listeners[a],void 0!==a&&(b=a.indexOf(b),-1!==b&&a.splice(b,1)))},dispatchEvent:function(a){if(void 0!==this._listeners){var b=this._listeners[a.type];if(void 0!==b){a.target=this;b=b.slice(0);for(var c=0,d=b.length;cb;b++)a[b]=(16>b?"0":"")+b.toString(16).toUpperCase();return function(){var b=4294967295*Math.random()|0,d=4294967295*Math.random()|0,e=4294967295*Math.random()|0,f=4294967295*Math.random()|0;return a[b&255]+a[b>>8&255]+a[b>>16&255]+a[b>>24&255]+"-"+a[d&255]+a[d>>8&255]+"-"+a[d>>16&15|64]+a[d>>24&255]+"-"+a[e&63|128]+a[e>>8&255]+"-"+a[e>>16&255]+a[e>>24&255]+a[f&255]+a[f>>8&255]+a[f>>16&255]+a[f>>24&255]}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a, +b){return(a%b+b)%b},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},lerp:function(a,b,c){return(1-c)*a+c*b},smoothstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*(3-2*a)},smootherstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*a*(a*(6*a-15)+10)},randInt:function(a,b){return a+Math.floor(Math.random()*(b-a+1))},randFloat:function(a,b){return a+Math.random()*(b-a)},randFloatSpread:function(a){return a*(.5-Math.random())},degToRad:function(a){return a* +S.DEG2RAD},radToDeg:function(a){return a*S.RAD2DEG},isPowerOfTwo:function(a){return 0===(a&a-1)&&0!==a},ceilPowerOfTwo:function(a){return Math.pow(2,Math.ceil(Math.log(a)/Math.LN2))},floorPowerOfTwo:function(a){return Math.pow(2,Math.floor(Math.log(a)/Math.LN2))}};Object.defineProperties(C.prototype,{width:{get:function(){return this.x},set:function(a){this.x=a}},height:{get:function(){return this.y},set:function(a){this.y=a}}});Object.assign(C.prototype,{isVector2:!0,set:function(a,b){this.x=a;this.y= +b;return this},setScalar:function(a){this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x= +a.x;this.y=a.y;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this},addScalar:function(a){this.x+=a;this.y+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."), +this.subVectors(a,b);this.x-=a.x;this.y-=a.y;return this},subScalar:function(a){this.x-=a;this.y-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this},multiply:function(a){this.x*=a.x;this.y*=a.y;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;return this},divide:function(a){this.x/=a.x;this.y/=a.y;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},applyMatrix3:function(a){var b=this.x,c=this.y;a=a.elements;this.x=a[0]*b+a[3]*c+a[6];this.y= +a[1]*b+a[4]*c+a[7];return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));return this},clampScalar:function(){var a=new C,b=new C;return function(c,d){a.set(c,c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c|| +1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);return this},negate:function(){this.x=-this.x;this.y=-this.y;return this},dot:function(a){return this.x* +a.x+this.y*a.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length()||1)},angle:function(){var a=Math.atan2(this.y,this.x);0>a&&(a+=2*Math.PI);return a},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x;a=this.y-a.y;return b*b+a*a},manhattanDistanceTo:function(a){return Math.abs(this.x- +a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;return a},fromBufferAttribute:function(a, +b,c){void 0!==c&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);return this},rotateAround:function(a,b){var c=Math.cos(b);b=Math.sin(b);var d=this.x-a.x,e=this.y-a.y;this.x=d*c-e*b+a.x;this.y=d*b+e*c+a.y;return this}});Object.assign(M.prototype,{isMatrix4:!0,set:function(a,b,c,d,e,f,g,h,l,m,k,n,t,r,q,p){var u=this.elements;u[0]=a;u[4]=b;u[8]=c;u[12]=d;u[1]=e;u[5]=f;u[9]=g;u[13]=h;u[2]=l;u[6]=m;u[10]=k;u[14]=n;u[3]=t;u[7]=r;u[11]= +q;u[15]=p;return this},identity:function(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this},clone:function(){return(new M).fromArray(this.elements)},copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];b[11]=a[11];b[12]=a[12];b[13]=a[13];b[14]=a[14];b[15]=a[15];return this},copyPosition:function(a){var b=this.elements;a=a.elements;b[12]=a[12];b[13]=a[13];b[14]=a[14];return this},extractBasis:function(a, +b,c){a.setFromMatrixColumn(this,0);b.setFromMatrixColumn(this,1);c.setFromMatrixColumn(this,2);return this},makeBasis:function(a,b,c){this.set(a.x,b.x,c.x,0,a.y,b.y,c.y,0,a.z,b.z,c.z,0,0,0,0,1);return this},extractRotation:function(){var a=new p;return function(b){var c=this.elements,d=b.elements,e=1/a.setFromMatrixColumn(b,0).length(),f=1/a.setFromMatrixColumn(b,1).length();b=1/a.setFromMatrixColumn(b,2).length();c[0]=d[0]*e;c[1]=d[1]*e;c[2]=d[2]*e;c[4]=d[4]*f;c[5]=d[5]*f;c[6]=d[6]*f;c[8]=d[8]*b; +c[9]=d[9]*b;c[10]=d[10]*b;return this}}(),makeRotationFromEuler:function(a){a&&a.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var b=this.elements,c=a.x,d=a.y,e=a.z,f=Math.cos(c);c=Math.sin(c);var g=Math.cos(d);d=Math.sin(d);var h=Math.cos(e);e=Math.sin(e);if("XYZ"===a.order){a=f*h;var l=f*e,m=c*h,k=c*e;b[0]=g*h;b[4]=-g*e;b[8]=d;b[1]=l+m*d;b[5]=a-k*d;b[9]=-c*g;b[2]=k-a*d;b[6]=m+l*d;b[10]=f*g}else"YXZ"===a.order?(a=g* +h,l=g*e,m=d*h,k=d*e,b[0]=a+k*c,b[4]=m*c-l,b[8]=f*d,b[1]=f*e,b[5]=f*h,b[9]=-c,b[2]=l*c-m,b[6]=k+a*c,b[10]=f*g):"ZXY"===a.order?(a=g*h,l=g*e,m=d*h,k=d*e,b[0]=a-k*c,b[4]=-f*e,b[8]=m+l*c,b[1]=l+m*c,b[5]=f*h,b[9]=k-a*c,b[2]=-f*d,b[6]=c,b[10]=f*g):"ZYX"===a.order?(a=f*h,l=f*e,m=c*h,k=c*e,b[0]=g*h,b[4]=m*d-l,b[8]=a*d+k,b[1]=g*e,b[5]=k*d+a,b[9]=l*d-m,b[2]=-d,b[6]=c*g,b[10]=f*g):"YZX"===a.order?(a=f*g,l=f*d,m=c*g,k=c*d,b[0]=g*h,b[4]=k-a*e,b[8]=m*e+l,b[1]=e,b[5]=f*h,b[9]=-c*h,b[2]=-d*h,b[6]=l*e+m,b[10]=a-k* +e):"XZY"===a.order&&(a=f*g,l=f*d,m=c*g,k=c*d,b[0]=g*h,b[4]=-e,b[8]=d*h,b[1]=a*e+k,b[5]=f*h,b[9]=l*e-m,b[2]=m*e-l,b[6]=c*h,b[10]=k*e+a);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},makeRotationFromQuaternion:function(a){var b=this.elements,c=a._x,d=a._y,e=a._z,f=a._w,g=c+c,h=d+d,l=e+e;a=c*g;var m=c*h;c*=l;var k=d*h;d*=l;e*=l;g*=f;h*=f;f*=l;b[0]=1-(k+e);b[4]=m-f;b[8]=c+h;b[1]=m+f;b[5]=1-(a+e);b[9]=d-g;b[2]=c-h;b[6]=d+g;b[10]=1-(a+k);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]= +0;b[15]=1;return this},lookAt:function(){var a=new p,b=new p,c=new p;return function(d,e,f){var g=this.elements;c.subVectors(d,e);0===c.lengthSq()&&(c.z=1);c.normalize();a.crossVectors(f,c);0===a.lengthSq()&&(1===Math.abs(f.z)?c.x+=1E-4:c.z+=1E-4,c.normalize(),a.crossVectors(f,c));a.normalize();b.crossVectors(c,a);g[0]=a.x;g[4]=b.x;g[8]=c.x;g[1]=a.y;g[5]=b.y;g[9]=c.y;g[2]=a.z;g[6]=b.z;g[10]=c.z;return this}}(),multiply:function(a,b){return void 0!==b?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."), +this.multiplyMatrices(a,b)):this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements;b=this.elements;a=c[0];var e=c[4],f=c[8],g=c[12],h=c[1],l=c[5],m=c[9],k=c[13],n=c[2],t=c[6],r=c[10],q=c[14],p=c[3],x=c[7],y=c[11];c=c[15];var w=d[0],B=d[4],G=d[8],K=d[12],P=d[1],H=d[5],C=d[9],A=d[13],z=d[2],E=d[6],F=d[10],I=d[14],L=d[3],Q=d[7],N=d[11];d=d[15];b[0]=a*w+e*P+f*z+g*L;b[4]=a*B+e*H+f*E+g*Q;b[8]=a*G+e*C+f*F+ +g*N;b[12]=a*K+e*A+f*I+g*d;b[1]=h*w+l*P+m*z+k*L;b[5]=h*B+l*H+m*E+k*Q;b[9]=h*G+l*C+m*F+k*N;b[13]=h*K+l*A+m*I+k*d;b[2]=n*w+t*P+r*z+q*L;b[6]=n*B+t*H+r*E+q*Q;b[10]=n*G+t*C+r*F+q*N;b[14]=n*K+t*A+r*I+q*d;b[3]=p*w+x*P+y*z+c*L;b[7]=p*B+x*H+y*E+c*Q;b[11]=p*G+x*C+y*F+c*N;b[15]=p*K+x*A+y*I+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[4]*=a;b[8]*=a;b[12]*=a;b[1]*=a;b[5]*=a;b[9]*=a;b[13]*=a;b[2]*=a;b[6]*=a;b[10]*=a;b[14]*=a;b[3]*=a;b[7]*=a;b[11]*=a;b[15]*=a;return this},applyToBufferAttribute:function(){var a= +new p;return function(b){for(var c=0,d=b.count;cthis.determinant()&&(g=-g);c.x=f[12];c.y=f[13];c.z=f[14];b.copy(this);c=1/g;f=1/h;var m=1/l;b.elements[0]*=c;b.elements[1]*=c;b.elements[2]*=c;b.elements[4]*=f;b.elements[5]*= +f;b.elements[6]*=f;b.elements[8]*=m;b.elements[9]*=m;b.elements[10]*=m;d.setFromRotationMatrix(b);e.x=g;e.y=h;e.z=l;return this}}(),makePerspective:function(a,b,c,d,e,f){void 0===f&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");var g=this.elements;g[0]=2*e/(b-a);g[4]=0;g[8]=(b+a)/(b-a);g[12]=0;g[1]=0;g[5]=2*e/(c-d);g[9]=(c+d)/(c-d);g[13]=0;g[2]=0;g[6]=0;g[10]=-(f+e)/(f-e);g[14]=-2*f*e/(f-e);g[3]=0;g[7]=0;g[11]=-1;g[15]=0;return this}, +makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=1/(b-a),l=1/(c-d),m=1/(f-e);g[0]=2*h;g[4]=0;g[8]=0;g[12]=-((b+a)*h);g[1]=0;g[5]=2*l;g[9]=0;g[13]=-((c+d)*l);g[2]=0;g[6]=0;g[10]=-2*m;g[14]=-((f+e)*m);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b=this.elements;a=a.elements;for(var c=0;16>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;16>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]); +void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];a[b+9]=c[9];a[b+10]=c[10];a[b+11]=c[11];a[b+12]=c[12];a[b+13]=c[13];a[b+14]=c[14];a[b+15]=c[15];return a}});Object.assign(ja,{slerp:function(a,b,c,d){return c.copy(a).slerp(b,d)},slerpFlat:function(a,b,c,d,e,f,g){var h=c[d+0],l=c[d+1],m=c[d+2];c=c[d+3];d=e[f+0];var k=e[f+1],n=e[f+2];e=e[f+3];if(c!==e||h!==d||l!==k||m!==n){f=1-g;var p=h*d+l*k+m*n+c*e,r=0<= +p?1:-1,q=1-p*p;q>Number.EPSILON&&(q=Math.sqrt(q),p=Math.atan2(q,p*r),f=Math.sin(f*p)/q,g=Math.sin(g*p)/q);r*=g;h=h*f+d*r;l=l*f+k*r;m=m*f+n*r;c=c*f+e*r;f===1-g&&(g=1/Math.sqrt(h*h+l*l+m*m+c*c),h*=g,l*=g,m*=g,c*=g)}a[b]=h;a[b+1]=l;a[b+2]=m;a[b+3]=c}});Object.defineProperties(ja.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z= +a;this.onChangeCallback()}},w:{get:function(){return this._w},set:function(a){this._w=a;this.onChangeCallback()}}});Object.assign(ja.prototype,{set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._w=d;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._w)},copy:function(a){this._x=a.x;this._y=a.y;this._z=a.z;this._w=a.w;this.onChangeCallback();return this},setFromEuler:function(a,b){if(!a||!a.isEuler)throw Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order."); +var c=a._x,d=a._y,e=a._z;a=a.order;var f=Math.cos,g=Math.sin,h=f(c/2),l=f(d/2);f=f(e/2);c=g(c/2);d=g(d/2);e=g(e/2);"XYZ"===a?(this._x=c*l*f+h*d*e,this._y=h*d*f-c*l*e,this._z=h*l*e+c*d*f,this._w=h*l*f-c*d*e):"YXZ"===a?(this._x=c*l*f+h*d*e,this._y=h*d*f-c*l*e,this._z=h*l*e-c*d*f,this._w=h*l*f+c*d*e):"ZXY"===a?(this._x=c*l*f-h*d*e,this._y=h*d*f+c*l*e,this._z=h*l*e+c*d*f,this._w=h*l*f-c*d*e):"ZYX"===a?(this._x=c*l*f-h*d*e,this._y=h*d*f+c*l*e,this._z=h*l*e-c*d*f,this._w=h*l*f+c*d*e):"YZX"===a?(this._x= +c*l*f+h*d*e,this._y=h*d*f+c*l*e,this._z=h*l*e-c*d*f,this._w=h*l*f-c*d*e):"XZY"===a&&(this._x=c*l*f-h*d*e,this._y=h*d*f-c*l*e,this._z=h*l*e+c*d*f,this._w=h*l*f+c*d*e);if(!1!==b)this.onChangeCallback();return this},setFromAxisAngle:function(a,b){b/=2;var c=Math.sin(b);this._x=a.x*c;this._y=a.y*c;this._z=a.z*c;this._w=Math.cos(b);this.onChangeCallback();return this},setFromRotationMatrix:function(a){var b=a.elements,c=b[0];a=b[4];var d=b[8],e=b[1],f=b[5],g=b[9],h=b[2],l=b[6];b=b[10];var m=c+f+b;0f&&c>b?(c=2*Math.sqrt(1+c-f-b),this._w=(l-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y=.25*c,this._z=(g+l)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+h)/c,this._y=(g+l)/c,this._z=.25*c);this.onChangeCallback();return this},setFromUnitVectors:function(){var a=new p,b;return function(c,d){void 0===a&&(a=new p);b=c.dot(d)+1;1E-6>b? +(b=0,Math.abs(c.x)>Math.abs(c.z)?a.set(-c.y,c.x,0):a.set(0,-c.z,c.y)):a.crossVectors(c,d);this._x=a.x;this._y=a.y;this._z=a.z;this._w=b;return this.normalize()}}(),inverse:function(){return this.conjugate()},conjugate:function(){this._x*=-1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(a){return this._x*a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x* +this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this},multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a, +this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z;a=a._w;var f=b._x,g=b._y,h=b._z;b=b._w;this._x=c*b+a*f+d*h-e*g;this._y=d*b+a*g+e*f-c*h;this._z=e*b+a*h+c*g-d*f;this._w=a*b-c*f-d*g-e*h;this.onChangeCallback();return this},slerp:function(a,b){if(0===b)return this;if(1===b)return this.copy(a);var c=this._x,d=this._y,e=this._z,f=this._w,g=f*a._w+c*a._x+d*a._y+e*a._z;0>g?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a);if(1<=g)return this._w=f,this._x=c,this._y= +d,this._z=e,this;a=Math.sqrt(1-g*g);if(.001>Math.abs(a))return this._w=.5*(f+this._w),this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var h=Math.atan2(a,g);g=Math.sin((1-b)*h)/a;b=Math.sin(b*h)/a;this._w=f*g+this._w*b;this._x=c*g+this._x*b;this._y=d*g+this._y*b;this._z=e*g+this._z*b;this.onChangeCallback();return this},equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+ +1];this._z=a[b+2];this._w=a[b+3];this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(p.prototype,{isVector3:!0,set:function(a,b,c){this.x=a;this.y=b;this.z=c;return this},setScalar:function(a){this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y= +a;return this},setZ:function(a){this.z=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this}, +add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."), +this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this},multiply:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(a,b);this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*= +a;return this},multiplyVectors:function(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},applyEuler:function(){var a=new ja;return function(b){b&&b.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a=new ja;return function(b,c){return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z; +a=a.elements;this.x=a[0]*b+a[3]*c+a[6]*d;this.y=a[1]*b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;var e=1/(a[3]*b+a[7]*c+a[11]*d+a[15]);this.x=(a[0]*b+a[4]*c+a[8]*d+a[12])*e;this.y=(a[1]*b+a[5]*c+a[9]*d+a[13])*e;this.z=(a[2]*b+a[6]*c+a[10]*d+a[14])*e;return this},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a=a.w;var h=a*b+f*d-g*c,l=a*c+g*b-e*d,m=a*d+e*c-f*b;b=-e*b-f*c-g*d;this.x=h*a+b* +-e+l*-g-m*-f;this.y=l*a+b*-f+m*-e-h*-g;this.z=m*a+b*-g+h*-f-l*-e;return this},project:function(){var a=new M;return function(b){a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyMatrix4(a)}}(),unproject:function(){var a=new M;return function(b){a.multiplyMatrices(b.matrixWorld,a.getInverse(b.projectionMatrix));return this.applyMatrix4(a)}}(),transformDirection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d;this.y=a[1]*b+a[5]*c+ +a[9]*d;this.z=a[2]*b+a[6]*c+a[10]*d;return this.normalize()},divide:function(a){this.x/=a.x;this.y/=a.y;this.z/=a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y, +this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));return this},clampScalar:function(){var a=new p,b=new p;return function(c,d){a.set(c,c,c);b.set(d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this}, +round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z}, +length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){return void 0!== +b?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(a,b)):this.crossVectors(this,a)},crossVectors:function(a,b){var c=a.x,d=a.y;a=a.z;var e=b.x,f=b.y;b=b.z;this.x=d*b-a*f;this.y=a*e-c*b;this.z=c*f-d*e;return this},projectOnVector:function(a){var b=a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a=new p;return function(b){a.copy(this).projectOnVector(b);return this.sub(a)}}(),reflect:function(){var a= +new p;return function(b){return this.sub(a.copy(b).multiplyScalar(2*this.dot(b)))}}(),angleTo:function(a){a=this.dot(a)/Math.sqrt(this.lengthSq()*a.lengthSq());return Math.acos(S.clamp(a,-1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x,c=this.y-a.y;a=this.z-a.z;return b*b+c*c+a*a},manhattanDistanceTo:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)* +a.radius;this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)*a.radius;this.z=b*Math.cos(a.theta);return this},setFromCylindrical:function(a){this.x=a.radius*Math.sin(a.theta);this.y=a.y;this.z=a.radius*Math.cos(a.theta);return this},setFromMatrixPosition:function(a){a=a.elements;this.x=a[12];this.y=a[13];this.z=a[14];return this},setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),c=this.setFromMatrixColumn(a,1).length();a=this.setFromMatrixColumn(a,2).length();this.x=b;this.y= +c;this.z=a;return this},setFromMatrixColumn:function(a,b){return this.fromArray(a.elements,4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute()."); +this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);return this}});Object.assign(sa.prototype,{isMatrix3:!0,set:function(a,b,c,d,e,f,g,h,l){var m=this.elements;m[0]=a;m[1]=d;m[2]=g;m[3]=b;m[4]=e;m[5]=h;m[6]=c;m[7]=f;m[8]=l;return this},identity:function(){this.set(1,0,0,0,1,0,0,0,1);return this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]= +a[8];return this},setFromMatrix4:function(a){a=a.elements;this.set(a[0],a[4],a[8],a[1],a[5],a[9],a[2],a[6],a[10]);return this},applyToBufferAttribute:function(){var a=new p;return function(b){for(var c=0,d=b.count;cc;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;9>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8]; +return a}});var xf=0;Y.DEFAULT_IMAGE=void 0;Y.DEFAULT_MAPPING=300;Y.prototype=Object.assign(Object.create(xa.prototype),{constructor:Y,isTexture:!0,clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.image=a.image;this.mipmaps=a.mipmaps.slice(0);this.mapping=a.mapping;this.wrapS=a.wrapS;this.wrapT=a.wrapT;this.magFilter=a.magFilter;this.minFilter=a.minFilter;this.anisotropy=a.anisotropy;this.format=a.format;this.type=a.type;this.offset.copy(a.offset);this.repeat.copy(a.repeat); +this.center.copy(a.center);this.rotation=a.rotation;this.matrixAutoUpdate=a.matrixAutoUpdate;this.matrix.copy(a.matrix);this.generateMipmaps=a.generateMipmaps;this.premultiplyAlpha=a.premultiplyAlpha;this.flipY=a.flipY;this.unpackAlignment=a.unpackAlignment;this.encoding=a.encoding;return this},toJSON:function(a){var b=void 0===a||"string"===typeof a;if(!b&&void 0!==a.textures[this.uuid])return a.textures[this.uuid];var c={metadata:{version:4.5,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid, +name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var d=this.image;void 0===d.uuid&&(d.uuid=S.generateUUID());if(!b&&void 0===a.images[d.uuid]){var e=a.images,f=d.uuid,g=d.uuid;if(d instanceof HTMLCanvasElement)var h= +d;else{h=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");h.width=d.width;h.height=d.height;var l=h.getContext("2d");d instanceof ImageData?l.putImageData(d,0,0):l.drawImage(d,0,0,d.width,d.height)}h=2048a.x||1a.x?0:1;break;case 1002:a.x=1===Math.abs(Math.floor(a.x)%2)?Math.ceil(a.x)-a.x:a.x-Math.floor(a.x)}if(0>a.y||1a.y?0:1;break;case 1002:a.y=1===Math.abs(Math.floor(a.y)%2)?Math.ceil(a.y)-a.y:a.y-Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}});Object.defineProperty(Y.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(ea.prototype, +{isVector4:!0,set:function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.w=d;return this},setScalar:function(a){this.w=this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;case 3:this.w=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x; +case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z,this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this}, +addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-= +a;this.y-=a;this.z-=a;this.w-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;this.w*=a;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12]*e;this.y=a[1]*b+a[5]*c+a[9]*d+a[13]*e;this.z=a[2]*b+a[6]*c+a[10]*d+a[14]*e;this.w=a[3]*b+a[7]*c+a[11]*d+a[15]*e;return this},divideScalar:function(a){return this.multiplyScalar(1/ +a)},setAxisAngleFromQuaternion:function(a){this.w=2*Math.acos(a.w);var b=Math.sqrt(1-a.w*a.w);1E-4>b?(this.x=1,this.z=this.y=0):(this.x=a.x/b,this.y=a.y/b,this.z=a.z/b);return this},setAxisAngleFromRotationMatrix:function(a){a=a.elements;var b=a[0];var c=a[4];var d=a[8],e=a[1],f=a[5],g=a[9];var h=a[2];var l=a[6];var m=a[10];if(.01>Math.abs(c-e)&&.01>Math.abs(d-h)&&.01>Math.abs(g-l)){if(.1>Math.abs(c+e)&&.1>Math.abs(d+h)&&.1>Math.abs(g+l)&&.1>Math.abs(b+f+m-3))return this.set(1,0,0,0),this;a=Math.PI; +b=(b+1)/2;f=(f+1)/2;m=(m+1)/2;c=(c+e)/4;d=(d+h)/4;g=(g+l)/4;b>f&&b>m?.01>b?(l=0,c=h=.707106781):(l=Math.sqrt(b),h=c/l,c=d/l):f>m?.01>f?(l=.707106781,h=0,c=.707106781):(h=Math.sqrt(f),l=c/h,c=g/h):.01>m?(h=l=.707106781,c=0):(c=Math.sqrt(m),l=d/c,h=g/c);this.set(l,h,c,a);return this}a=Math.sqrt((l-g)*(l-g)+(d-h)*(d-h)+(e-c)*(e-c));.001>Math.abs(a)&&(a=1);this.x=(l-g)/a;this.y=(d-h)/a;this.z=(e-c)/a;this.w=Math.acos((b+f+m-1)/2);return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y, +a.y);this.z=Math.min(this.z,a.z);this.w=Math.min(this.w,a.w);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);this.w=Math.max(this.w,a.w);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));this.w=Math.max(a.w,Math.min(b.w,this.w));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new ea,b=new ea);a.set(c, +c,c,c);b.set(d,d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);this.w=Math.floor(this.w);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);this.w=Math.ceil(this.w);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y); +this.z=Math.round(this.z);this.w=Math.round(this.w);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);this.w=0>this.w?Math.ceil(this.w):Math.floor(this.w);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z+this.w*a.w},lengthSq:function(){return this.x* +this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;this.w+=(a.w-this.w)*b;return this},lerpVectors:function(a, +b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];this.w=a[b+3];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;a[b+3]=this.w;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute()."); +this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);this.w=a.getW(b);return this}});hb.prototype=Object.assign(Object.create(xa.prototype),{constructor:hb,isWebGLRenderTarget:!0,setSize:function(a,b){if(this.width!==a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0,0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone(); +this.depthBuffer=a.depthBuffer;this.stencilBuffer=a.stencilBuffer;this.depthTexture=a.depthTexture;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Ib.prototype=Object.create(hb.prototype);Ib.prototype.constructor=Ib;Ib.prototype.isWebGLRenderTargetCube=!0;ib.prototype=Object.create(Y.prototype);ib.prototype.constructor=ib;ib.prototype.isDataTexture=!0;Object.assign(Va.prototype,{isBox3:!0,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromArray:function(a){for(var b= +Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,l=a.length;he&&(e=m);k>f&&(f=k);n>g&&(g=n)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromBufferAttribute:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,l=a.count;he&&(e=m);k>f&&(f=k);n>g&&(g=n)}this.min.set(b,c,d); +this.max.set(e,f,g);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;bthis.max.x||a.ythis.max.y||a.zthis.max.z?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y&&this.min.z<=a.min.z&& +a.max.z<=this.max.z},getParameter:function(a,b){void 0===b&&(console.warn("THREE.Box3: .getParameter() target is now required"),b=new p);return b.set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y),(a.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(a){return a.max.xthis.max.x||a.max.ythis.max.y||a.max.zthis.max.z?!1:!0},intersectsSphere:function(){var a=new p;return function(b){this.clampPoint(b.center, +a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){if(0=a.constant},intersectsTriangle:function(){function a(a){var e; +var f=0;for(e=a.length-3;f<=e;f+=3){h.fromArray(a,f);var g=m.x*Math.abs(h.x)+m.y*Math.abs(h.y)+m.z*Math.abs(h.z),l=b.dot(h),k=c.dot(h),n=d.dot(h);if(Math.max(-Math.max(l,k,n),Math.min(l,k,n))>g)return!1}return!0}var b=new p,c=new p,d=new p,e=new p,f=new p,g=new p,h=new p,l=new p,m=new p,k=new p;return function(h){if(this.isEmpty())return!1;this.getCenter(l);m.subVectors(this.max,l);b.subVectors(h.a,l);c.subVectors(h.b,l);d.subVectors(h.c,l);e.subVectors(c,b);f.subVectors(d,c);g.subVectors(b,d);h= +[0,-e.z,e.y,0,-f.z,f.y,0,-g.z,g.y,e.z,0,-e.x,f.z,0,-f.x,g.z,0,-g.x,-e.y,e.x,0,-f.y,f.x,0,-g.y,g.x,0];if(!a(h))return!1;h=[1,0,0,0,1,0,0,0,1];if(!a(h))return!1;k.crossVectors(e,f);h=[k.x,k.y,k.z];return a(h)}}(),clampPoint:function(a,b){void 0===b&&(console.warn("THREE.Box3: .clampPoint() target is now required"),b=new p);return b.copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new p;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),getBoundingSphere:function(){var a= +new p;return function(b){void 0===b&&(console.warn("THREE.Box3: .getBoundingSphere() target is now required"),b=new Ea);this.getCenter(b.center);b.radius=.5*this.getSize(a).length();return b}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);this.isEmpty()&&this.makeEmpty();return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},applyMatrix4:function(){var a=[new p,new p,new p,new p,new p,new p,new p,new p];return function(b){if(this.isEmpty())return this; +a[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(b);a[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(b);a[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(b);a[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(b);a[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(b);a[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(b);a[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(b);a[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(b);this.setFromPoints(a);return this}}(), +translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});Object.assign(Ea.prototype,{set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a=new Va;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).getCenter(d);for(var e=c=0,f=b.length;e=this.radius},containsPoint:function(a){return a.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(a){return a.distanceTo(this.center)-this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;return a.center.distanceToSquared(this.center)<=b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(a.distanceToPoint(this.center))<= +this.radius},clampPoint:function(a,b){var c=this.center.distanceToSquared(a);void 0===b&&(console.warn("THREE.Sphere: .clampPoint() target is now required"),b=new p);b.copy(a);c>this.radius*this.radius&&(b.sub(this.center).normalize(),b.multiplyScalar(this.radius).add(this.center));return b},getBoundingBox:function(a){void 0===a&&(console.warn("THREE.Sphere: .getBoundingBox() target is now required"),a=new Va);a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a); +this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&&a.radius===this.radius}});Object.assign(Fa.prototype,{set:function(a,b){this.normal.copy(a);this.constant=b;return this},setComponents:function(a,b,c,d){this.normal.set(a,b,c);this.constant=d;return this},setFromNormalAndCoplanarPoint:function(a,b){this.normal.copy(a);this.constant=-b.dot(this.normal);return this},setFromCoplanarPoints:function(){var a= +new p,b=new p;return function(c,d,e){d=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();this.setFromNormalAndCoplanarPoint(d,c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.normal.copy(a.normal);this.constant=a.constant;return this},normalize:function(){var a=1/this.normal.length();this.normal.multiplyScalar(a);this.constant*=a;return this},negate:function(){this.constant*=-1;this.normal.negate();return this},distanceToPoint:function(a){return this.normal.dot(a)+ +this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a,b){void 0===b&&(console.warn("THREE.Plane: .projectPoint() target is now required"),b=new p);return b.copy(this.normal).multiplyScalar(-this.distanceToPoint(a)).add(a)},intersectLine:function(){var a=new p;return function(b,c){void 0===c&&(console.warn("THREE.Plane: .intersectLine() target is now required"),c=new p);var d=b.delta(a),e=this.normal.dot(d);if(0===e){if(0===this.distanceToPoint(b.start))return c.copy(b.start)}else if(e= +-(b.start.dot(this.normal)+this.constant)/e,!(0>e||1b&&0a&&0c;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes,c=a.elements;a=c[0];var d=c[1],e=c[2],f=c[3],g=c[4],h=c[5],l=c[6],m=c[7],k=c[8],n=c[9],p=c[10],r=c[11],q=c[12],v=c[13],x=c[14];c=c[15];b[0].setComponents(f-a,m-g,r-k,c-q).normalize();b[1].setComponents(f+a,m+g,r+k,c+q).normalize();b[2].setComponents(f+d,m+h,r+n,c+v).normalize();b[3].setComponents(f- +d,m-h,r-n,c-v).normalize();b[4].setComponents(f-e,m-l,r-p,c-x).normalize();b[5].setComponents(f+e,m+l,r+p,c+x).normalize();return this},intersectsObject:function(){var a=new Ea;return function(b){var c=b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSprite:function(){var a=new Ea;return function(b){a.center.set(0,0,0);a.radius=.7071067811865476;a.applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(), +intersectsSphere:function(a){var b=this.planes,c=a.center;a=-a.radius;for(var d=0;6>d;d++)if(b[d].distanceToPoint(c)e;e++){var f=d[e];a.x=0 +g&&0>f)return!1}return!0}}(),containsPoint:function(a){for(var b=this.planes,c=0;6>c;c++)if(0>b[c].distanceToPoint(a))return!1;return!0}});var V={alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n",alphatest_fragment:"#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n", +aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",begin_vertex:"\nvec3 transformed = vec3( position );\n",beginnormal_vertex:"\nvec3 objectNormal = vec3( normal );\n",bsdfs:"float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n", bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n", -clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n", +clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t#endif\n#endif\n", clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n", -color_fragment:"#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n",color_pars_vertex:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif",color_vertex:"#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif",common:"#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transpose( const in mat3 v ) {\n\tmat3 tmp;\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\n\treturn tmp;\n}\n", +color_fragment:"#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n",color_pars_vertex:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif",color_vertex:"#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif",common:"#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\n", cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n", defaultnormal_vertex:"vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n", emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n",encodings_fragment:" gl_FragColor = linearToOutputTexel( gl_FragColor );\n",encodings_pars_fragment:"\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n\tXp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract(Le);\n\tvResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n", -envmap_fragment:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = asin( flipNormal * reflectVec.y ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n", -envmap_pars_fragment:"#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n", +envmap_fragment:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n", +envmap_pars_fragment:"#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n", envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n",envmap_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n", fog_vertex:"\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n varying float fogDepth;\n#endif\n",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif\n", gradientmap_pars_fragment:"#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif\n",lightmap_fragment:"#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n", -lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_vertex:"vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n", -lights_pars:"uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n", +lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_vertex:"vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n", +lights_pars_begin:"uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n", +lights_pars_maps:"#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n", lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n",lights_phong_pars_fragment:"varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n", lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n", -lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tfloat norm = texture2D( ltcMag, uv ).a;\n\t\tvec4 t = texture2D( ltcMat, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( 1, 0, t.y ),\n\t\t\tvec3( 0, t.z, 0 ),\n\t\t\tvec3( t.w, 0, t.x )\n\t\t);\n\t\treflectedLight.directSpecular += lightColor * material.specularColor * norm * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n", -lights_template:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n", -logdepthbuf_fragment:"#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n", -map_fragment:"#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n",map_particle_fragment:"#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n",map_particle_pars_fragment:"#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n", -metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n", -morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n", -normal_flip:"#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n",normal_fragment:"#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n", +lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n", +lights_fragment_begin:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearCoatRadiance = vec3( 0.0 );\n#endif\n", +lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), maxMipLevel );\n\t#ifndef STANDARD\n\t\tclearCoatRadiance += getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), maxMipLevel );\n\t#endif\n#endif\n", +lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n", +logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\tgl_Position.z *= gl_Position.w;\n\t#endif\n#endif\n",map_fragment:"#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n", +map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n",map_particle_fragment:"#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n",map_particle_pars_fragment:"#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif\n",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n", +metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif", +morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n", +normal_fragment_begin:"#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n#endif\n",normal_fragment_maps:"#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n", normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n", -packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n", +packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n", premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n",project_vertex:"vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n",dithering_fragment:"#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n",dithering_pars_fragment:"#if defined( DITHERING )\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif\n", -roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n", +roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n", shadowmap_pars_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n", -shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n", -shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n", +shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n", +shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n", skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n", skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif\n",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n", -specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n",tonemapping_pars_fragment:"#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n", -uv_pars_fragment:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n", -uv_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif", -uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n", -cube_vert:"varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n", +specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n",tonemapping_pars_fragment:"#ifndef saturate\n\t#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n", +uv_pars_fragment:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\n", +uv_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif", +uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n", +cube_vert:"varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}\n",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n", depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -distanceRGBA_frag:"uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include \n#include \n#include \nvoid main () {\n\t#include \n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n",distanceRGBA_vert:"varying vec4 vWorldPosition;\n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition;\n}\n", -equirect_frag:"uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n",equirect_vert:"varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n", +distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}\n", +distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}\n", +equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n",equirect_vert:"varying vec3 vWorldPosition;\n#include \nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}\n", linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}\n", -meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -meshlambert_frag:"uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -meshlambert_vert:"#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +meshlambert_frag:"uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +meshlambert_vert:"#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -meshphysical_frag:"#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", +meshphysical_frag:"#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", meshphysical_vert:"#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}\n", -normal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n", +normal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n", normal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n", points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}\n", points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n", -shadow_frag:"uniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n",shadow_vert:"#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n}\n"},$a={basic:{uniforms:Ca.merge([R.common, -R.aomap,R.lightmap,R.fog]),vertexShader:X.meshbasic_vert,fragmentShader:X.meshbasic_frag},lambert:{uniforms:Ca.merge([R.common,R.aomap,R.lightmap,R.emissivemap,R.fog,R.lights,{emissive:{value:new G(0)}}]),vertexShader:X.meshlambert_vert,fragmentShader:X.meshlambert_frag},phong:{uniforms:Ca.merge([R.common,R.aomap,R.lightmap,R.emissivemap,R.bumpmap,R.normalmap,R.displacementmap,R.gradientmap,R.fog,R.lights,{emissive:{value:new G(0)},specular:{value:new G(1118481)},shininess:{value:30}}]),vertexShader:X.meshphong_vert, -fragmentShader:X.meshphong_frag},standard:{uniforms:Ca.merge([R.common,R.aomap,R.lightmap,R.emissivemap,R.bumpmap,R.normalmap,R.displacementmap,R.roughnessmap,R.metalnessmap,R.fog,R.lights,{emissive:{value:new G(0)},roughness:{value:.5},metalness:{value:.5},envMapIntensity:{value:1}}]),vertexShader:X.meshphysical_vert,fragmentShader:X.meshphysical_frag},points:{uniforms:Ca.merge([R.points,R.fog]),vertexShader:X.points_vert,fragmentShader:X.points_frag},dashed:{uniforms:Ca.merge([R.common,R.fog,{scale:{value:1}, -dashSize:{value:1},totalSize:{value:2}}]),vertexShader:X.linedashed_vert,fragmentShader:X.linedashed_frag},depth:{uniforms:Ca.merge([R.common,R.displacementmap]),vertexShader:X.depth_vert,fragmentShader:X.depth_frag},normal:{uniforms:Ca.merge([R.common,R.bumpmap,R.normalmap,R.displacementmap,{opacity:{value:1}}]),vertexShader:X.normal_vert,fragmentShader:X.normal_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:X.cube_vert,fragmentShader:X.cube_frag},equirect:{uniforms:{tEquirect:{value:null}, -tFlip:{value:-1}},vertexShader:X.equirect_vert,fragmentShader:X.equirect_frag},distanceRGBA:{uniforms:{lightPos:{value:new n}},vertexShader:X.distanceRGBA_vert,fragmentShader:X.distanceRGBA_frag}};$a.physical={uniforms:Ca.merge([$a.standard.uniforms,{clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:X.meshphysical_vert,fragmentShader:X.meshphysical_frag};Object.assign(fd.prototype,{set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromPoints:function(a){this.makeEmpty(); -for(var b=0,c=a.length;bthis.max.x||a.ythis.max.y?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y},getParameter:function(a,b){return(b||new C).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(a){return a.max.xthis.max.x||a.max.ythis.max.y?!1:!0},clampPoint:function(a,b){return(b||new C).copy(a).clamp(this.min,this.max)}, -distanceToPoint:function(){var a=new C;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});var Jf=0;Object.assign(U.prototype,xa.prototype,{isMaterial:!0,onBeforeCompile:function(){}, -setValues:function(a){if(void 0!==a)for(var b in a){var c=a[b];if(void 0===c)console.warn("THREE.Material: '"+b+"' parameter is undefined.");else{var d=this[b];void 0===d?console.warn("THREE."+this.type+": '"+b+"' is not a property of this material."):d&&d.isColor?d.set(c):d&&d.isVector3&&c&&c.isVector3?d.copy(c):this[b]="overdraw"===b?Number(c):c}}},toJSON:function(a){function b(a){var b=[],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var c=void 0===a;c&&(a={textures:{},images:{}}); -var d={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};d.uuid=this.uuid;d.type=this.type;""!==this.name&&(d.name=this.name);this.color&&this.color.isColor&&(d.color=this.color.getHex());void 0!==this.roughness&&(d.roughness=this.roughness);void 0!==this.metalness&&(d.metalness=this.metalness);this.emissive&&this.emissive.isColor&&(d.emissive=this.emissive.getHex());this.specular&&this.specular.isColor&&(d.specular=this.specular.getHex());void 0!==this.shininess&&(d.shininess=this.shininess); -void 0!==this.clearCoat&&(d.clearCoat=this.clearCoat);void 0!==this.clearCoatRoughness&&(d.clearCoatRoughness=this.clearCoatRoughness);this.map&&this.map.isTexture&&(d.map=this.map.toJSON(a).uuid);this.alphaMap&&this.alphaMap.isTexture&&(d.alphaMap=this.alphaMap.toJSON(a).uuid);this.lightMap&&this.lightMap.isTexture&&(d.lightMap=this.lightMap.toJSON(a).uuid);this.bumpMap&&this.bumpMap.isTexture&&(d.bumpMap=this.bumpMap.toJSON(a).uuid,d.bumpScale=this.bumpScale);this.normalMap&&this.normalMap.isTexture&& -(d.normalMap=this.normalMap.toJSON(a).uuid,d.normalScale=this.normalScale.toArray());this.displacementMap&&this.displacementMap.isTexture&&(d.displacementMap=this.displacementMap.toJSON(a).uuid,d.displacementScale=this.displacementScale,d.displacementBias=this.displacementBias);this.roughnessMap&&this.roughnessMap.isTexture&&(d.roughnessMap=this.roughnessMap.toJSON(a).uuid);this.metalnessMap&&this.metalnessMap.isTexture&&(d.metalnessMap=this.metalnessMap.toJSON(a).uuid);this.emissiveMap&&this.emissiveMap.isTexture&& -(d.emissiveMap=this.emissiveMap.toJSON(a).uuid);this.specularMap&&this.specularMap.isTexture&&(d.specularMap=this.specularMap.toJSON(a).uuid);this.envMap&&this.envMap.isTexture&&(d.envMap=this.envMap.toJSON(a).uuid,d.reflectivity=this.reflectivity);this.gradientMap&&this.gradientMap.isTexture&&(d.gradientMap=this.gradientMap.toJSON(a).uuid);void 0!==this.size&&(d.size=this.size);void 0!==this.sizeAttenuation&&(d.sizeAttenuation=this.sizeAttenuation);1!==this.blending&&(d.blending=this.blending);2!== -this.shading&&(d.shading=this.shading);0!==this.side&&(d.side=this.side);0!==this.vertexColors&&(d.vertexColors=this.vertexColors);1>this.opacity&&(d.opacity=this.opacity);!0===this.transparent&&(d.transparent=this.transparent);d.depthFunc=this.depthFunc;d.depthTest=this.depthTest;d.depthWrite=this.depthWrite;0e&&(e=m);q>f&&(f=q); -l>g&&(g=l)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromBufferAttribute:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.count;he&&(e=m);q>f&&(f=q);l>g&&(g=l)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;bthis.max.x||a.ythis.max.y||a.zthis.max.z?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y&&this.min.z<=a.min.z&&a.max.z<=this.max.z},getParameter:function(a,b){return(b||new n).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y),(a.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(a){return a.max.xthis.max.x||a.max.ythis.max.y||a.max.z< -this.min.z||a.min.z>this.max.z?!1:!0},intersectsSphere:function(){var a=new n;return function(b){this.clampPoint(b.center,a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){var b,c;0=a.constant},clampPoint:function(a,b){return(b||new n).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new n;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),getBoundingSphere:function(){var a=new n;return function(b){b=b||new Ea;this.getCenter(b.center);b.radius=.5*this.getSize(a).length();return b}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max); -this.isEmpty()&&this.makeEmpty();return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},applyMatrix4:function(){var a=[new n,new n,new n,new n,new n,new n,new n,new n];return function(b){if(this.isEmpty())return this;a[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(b);a[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(b);a[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(b);a[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(b);a[4].set(this.max.x, -this.min.y,this.min.z).applyMatrix4(b);a[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(b);a[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(b);a[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(b);this.setFromPoints(a);return this}}(),translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});Object.assign(Ea.prototype,{set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a= -new Ra;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).getCenter(d);for(var e=0,f=0,g=b.length;f=this.radius},containsPoint:function(a){return a.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(a){return a.distanceTo(this.center)- -this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;return a.center.distanceToSquared(this.center)<=b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(this.center.dot(a.normal)-a.constant)<=this.radius},clampPoint:function(a,b){var c=this.center.distanceToSquared(a),d=b||new n;d.copy(a);c>this.radius*this.radius&&(d.sub(this.center).normalize(),d.multiplyScalar(this.radius).add(this.center));return d},getBoundingBox:function(a){a= -a||new Ra;a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a);this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&&a.radius===this.radius}});Object.assign(Ba.prototype,{isMatrix3:!0,set:function(a,b,c,d,e,f,g,h,k){var m=this.elements;m[0]=a;m[1]=d;m[2]=g;m[3]=b;m[4]=e;m[5]=h;m[6]=c;m[7]=f;m[8]=k;return this},identity:function(){this.set(1, -0,0,0,1,0,0,0,1);return this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];return this},setFromMatrix4:function(a){a=a.elements;this.set(a[0],a[4],a[8],a[1],a[5],a[9],a[2],a[6],a[10]);return this},applyToBufferAttribute:function(){var a=new n;return function(b){for(var c=0,d=b.count;cc;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;9>c;c++)this.elements[c]=a[c+b];return this}, -toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];return a}});Object.assign(Aa.prototype,{set:function(a,b){this.normal.copy(a);this.constant=b;return this},setComponents:function(a,b,c,d){this.normal.set(a,b,c);this.constant=d;return this},setFromNormalAndCoplanarPoint:function(a,b){this.normal.copy(a);this.constant=-b.dot(this.normal);return this},setFromCoplanarPoints:function(){var a= -new n,b=new n;return function(c,d,e){d=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();this.setFromNormalAndCoplanarPoint(d,c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.normal.copy(a.normal);this.constant=a.constant;return this},normalize:function(){var a=1/this.normal.length();this.normal.multiplyScalar(a);this.constant*=a;return this},negate:function(){this.constant*=-1;this.normal.negate();return this},distanceToPoint:function(a){return this.normal.dot(a)+ -this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a,b){return this.orthoPoint(a,b).sub(a).negate()},orthoPoint:function(a,b){var c=this.distanceToPoint(a);return(b||new n).copy(this.normal).multiplyScalar(c)},intersectLine:function(){var a=new n;return function(b,c){var d=c||new n,e=b.delta(a),f=this.normal.dot(e);if(0===f){if(0===this.distanceToPoint(b.start))return d.copy(b.start)}else return f=-(b.start.dot(this.normal)+this.constant)/ -f,0>f||1b&&0a&&0c;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes,c=a.elements;a=c[0];var d=c[1],e=c[2],f=c[3],g=c[4],h=c[5],k=c[6],m=c[7],q=c[8],l=c[9],p=c[10],r=c[11],n=c[12],t=c[13],y=c[14],c=c[15];b[0].setComponents(f-a,m-g,r-q,c-n).normalize();b[1].setComponents(f+a,m+g,r+q,c+n).normalize();b[2].setComponents(f+d,m+h,r+l,c+t).normalize();b[3].setComponents(f-d,m-h,r-l,c-t).normalize();b[4].setComponents(f-e,m-k,r-p,c-y).normalize();b[5].setComponents(f+e, -m+k,r+p,c+y).normalize();return this},intersectsObject:function(){var a=new Ea;return function(b){var c=b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSprite:function(){var a=new Ea;return function(b){a.center.set(0,0,0);a.radius=.7071067811865476;a.applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSphere:function(a){var b=this.planes,c=a.center;a=-a.radius;for(var d= -0;6>d;d++)if(b[d].distanceToPoint(c)e;e++){var f=d[e];a.x=0g&&0>f)return!1}return!0}}(),containsPoint:function(a){for(var b=this.planes,c=0;6> -c;c++)if(0>b[c].distanceToPoint(a))return!1;return!0}});ab.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" ");ab.DefaultOrder="XYZ";Object.defineProperties(ab.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},order:{get:function(){return this._order},set:function(a){this._order=a; -this.onChangeCallback()}}});Object.assign(ab.prototype,{isEuler:!0,set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._order=d||this._order;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._order)},copy:function(a){this._x=a._x;this._y=a._y;this._z=a._z;this._order=a._order;this.onChangeCallback();return this},setFromRotationMatrix:function(a,b,c){var d=Y.clamp,e=a.elements;a=e[0];var f=e[4],g=e[8],h=e[1],k=e[5],m=e[9],q=e[2],l=e[6], -e=e[10];b=b||this._order;"XYZ"===b?(this._y=Math.asin(d(g,-1,1)),.99999>Math.abs(g)?(this._x=Math.atan2(-m,e),this._z=Math.atan2(-f,a)):(this._x=Math.atan2(l,k),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(m,-1,1)),.99999>Math.abs(m)?(this._y=Math.atan2(g,e),this._z=Math.atan2(h,k)):(this._y=Math.atan2(-q,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(l,-1,1)),.99999>Math.abs(l)?(this._y=Math.atan2(-q,e),this._z=Math.atan2(-f,k)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(q, --1,1)),.99999>Math.abs(q)?(this._x=Math.atan2(l,e),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-f,k))):"YZX"===b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-m,k),this._y=Math.atan2(-q,a)):(this._x=0,this._y=Math.atan2(g,e))):"XZY"===b?(this._z=Math.asin(-d(f,-1,1)),.99999>Math.abs(f)?(this._x=Math.atan2(l,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-m,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order= -b;if(!1!==c)this.onChangeCallback();return this},setFromQuaternion:function(){var a=new K;return function(b,c,d){a.makeRotationFromQuaternion(b);return this.setFromRotationMatrix(a,c,d)}}(),setFromVector3:function(a,b){return this.set(a.x,a.y,a.z,b||this._order)},reorder:function(){var a=new oa;return function(b){a.setFromEuler(this);return this.setFromQuaternion(a,b)}}(),equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._order===this._order},fromArray:function(a){this._x= -a[0];this._y=a[1];this._z=a[2];void 0!==a[3]&&(this._order=a[3]);this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._order;return a},toVector3:function(a){return a?a.set(this._x,this._y,this._z):new n(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(Qd.prototype,{set:function(a){this.mask=1<d;d++)if(e[d]===e[(d+1)%3]){a.push(f);break}for(f=a.length-1;0<=f;f--)for(e=a[f],this.faces.splice(e,1),c=0,g=this.faceVertexUvs.length;c\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n}\n",shadow_vert:"#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}\n"}, +Da={merge:function(a){for(var b={},c=0;c>16&255)/255;this.g=(a>>8&255)/255;this.b=(a&255)/255;return this},setRGB:function(a,b,c){this.r=a;this.g=b;this.b=c;return this},setHSL:function(){function a(a,c,d){0>d&&(d+=1);1d?c:d<2/3?a+6*(c-a)*(2/3-d):a}return function(b, +c,d){b=S.euclideanModulo(b,1);c=S.clamp(c,0,1);d=S.clamp(d,0,1);0===c?this.r=this.g=this.b=d:(c=.5>=d?d*(1+c):d+c-d*c,d=2*d-c,this.r=a(d,c,b+1/3),this.g=a(d,c,b),this.b=a(d,c,b-1/3));return this}}(),setStyle:function(a){function b(b){void 0!==b&&1>parseFloat(b)&&console.warn("THREE.Color: Alpha component of "+a+" will be ignored.")}var c;if(c=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(a)){var d=c[2];switch(c[1]){case "rgb":case "rgba":if(c=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r= +Math.min(255,parseInt(c[1],10))/255,this.g=Math.min(255,parseInt(c[2],10))/255,this.b=Math.min(255,parseInt(c[3],10))/255,b(c[5]),this;if(c=/^(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(100,parseInt(c[1],10))/100,this.g=Math.min(100,parseInt(c[2],10))/100,this.b=Math.min(100,parseInt(c[3],10))/100,b(c[5]),this;break;case "hsl":case "hsla":if(c=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d)){d=parseFloat(c[1])/ +360;var e=parseInt(c[2],10)/100,f=parseInt(c[3],10)/100;b(c[5]);return this.setHSL(d,e,f)}}}else if(c=/^#([A-Fa-f0-9]+)$/.exec(a)){c=c[1];d=c.length;if(3===d)return this.r=parseInt(c.charAt(0)+c.charAt(0),16)/255,this.g=parseInt(c.charAt(1)+c.charAt(1),16)/255,this.b=parseInt(c.charAt(2)+c.charAt(2),16)/255,this;if(6===d)return this.r=parseInt(c.charAt(0)+c.charAt(1),16)/255,this.g=parseInt(c.charAt(2)+c.charAt(3),16)/255,this.b=parseInt(c.charAt(4)+c.charAt(5),16)/255,this}a&&0=h?l/(e+f):l/(2-e-f);switch(e){case b:g=(c-d)/l+(cMath.abs(g)?(this._x=Math.atan2(-m,e),this._z=Math.atan2(-f,a)):(this._x=Math.atan2(n,l),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(m,-1,1)),.99999>Math.abs(m)? +(this._y=Math.atan2(g,e),this._z=Math.atan2(h,l)):(this._y=Math.atan2(-k,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(n,-1,1)),.99999>Math.abs(n)?(this._y=Math.atan2(-k,e),this._z=Math.atan2(-f,l)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(k,-1,1)),.99999>Math.abs(k)?(this._x=Math.atan2(n,e),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-f,l))):"YZX"===b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-m,l),this._y=Math.atan2(-k,a)):(this._x= +0,this._y=Math.atan2(g,e))):"XZY"===b?(this._z=Math.asin(-d(f,-1,1)),.99999>Math.abs(f)?(this._x=Math.atan2(n,l),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-m,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order=b;if(!1!==c)this.onChangeCallback();return this},setFromQuaternion:function(){var a=new M;return function(b,c,d){a.makeRotationFromQuaternion(b);return this.setFromRotationMatrix(a,c,d)}}(),setFromVector3:function(a,b){return this.set(a.x, +a.y,a.z,b||this._order)},reorder:function(){var a=new ja;return function(b){a.setFromEuler(this);return this.setFromQuaternion(a,b)}}(),equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._order===this._order},fromArray:function(a){this._x=a[0];this._y=a[1];this._z=a[2];void 0!==a[3]&&(this._order=a[3]);this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._order;return a},toVector3:function(a){return a? +a.set(this._x,this._y,this._z):new p(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(Sd.prototype,{set:function(a){this.mask=1<g;g++)if(d[g]===d[(g+1)%3]){a.push(f);break}for(f=a.length-1;0<=f;f--)for(d=a[f],this.faces.splice(d,1),c=0,e=this.faceVertexUvs.length;cd?c.copy(this.origin):c.copy(this.direction).multiplyScalar(d).add(this.origin)}, -distanceToPoint:function(a){return Math.sqrt(this.distanceSqToPoint(a))},distanceSqToPoint:function(){var a=new n;return function(b){var c=a.subVectors(b,this.origin).dot(this.direction);if(0>c)return this.origin.distanceToSquared(b);a.copy(this.direction).multiplyScalar(c).add(this.origin);return a.distanceToSquared(b)}}(),distanceSqToSegment:function(){var a=new n,b=new n,c=new n;return function(d,e,f,g){a.copy(d).add(e).multiplyScalar(.5);b.copy(e).sub(d).normalize();c.copy(this.origin).sub(a); -var h=.5*d.distanceTo(e),k=-this.direction.dot(b),m=c.dot(this.direction),q=-c.dot(b),l=c.lengthSq(),p=Math.abs(1-k*k),r;0=-r?e<=r?(h=1/p,d*=h,e*=h,k=d*(d+k*e+2*m)+e*(k*d+e+2*q)+l):(e=h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*q)+l):(e=-h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*q)+l):e<=-r?(d=Math.max(0,-(-k*h+m)),e=0f)return null;f=Math.sqrt(f-e);e=d-f;d+=f;return 0>e&&0>d?null:0>e?this.at(d,c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<= -a.radius},distanceToPlane:function(a){var b=a.normal.dot(this.direction);if(0===b)return 0===a.distanceToPoint(this.origin)?0:null;a=-(this.origin.dot(a.normal)+a.constant)/b;return 0<=a?a:null},intersectPlane:function(a,b){var c=this.distanceToPlane(a);return null===c?null:this.at(c,b)},intersectsPlane:function(a){var b=a.distanceToPoint(this.origin);return 0===b||0>a.normal.dot(this.direction)*b?!0:!1},intersectBox:function(a,b){var c,d,e,f,g;d=1/this.direction.x;f=1/this.direction.y;g=1/this.direction.z; -var h=this.origin;0<=d?(c=(a.min.x-h.x)*d,d*=a.max.x-h.x):(c=(a.max.x-h.x)*d,d*=a.min.x-h.x);0<=f?(e=(a.min.y-h.y)*f,f*=a.max.y-h.y):(e=(a.max.y-h.y)*f,f*=a.min.y-h.y);if(c>f||e>d)return null;if(e>c||c!==c)c=e;if(fg||e>d)return null;if(e>c||c!==c)c=e;if(gd?null:this.at(0<=c?c:d,b)},intersectsBox:function(){var a=new n;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a= -new n,b=new n,c=new n,d=new n;return function(e,f,g,h,k){b.subVectors(f,e);c.subVectors(g,e);d.crossVectors(b,c);f=this.direction.dot(d);if(0f)h=-1,f=-f;else return null;a.subVectors(this.origin,e);e=h*this.direction.dot(c.crossVectors(a,c));if(0>e)return null;g=h*this.direction.dot(b.cross(a));if(0>g||e+g>f)return null;e=-h*a.dot(d);return 0>e?null:this.at(e/f,k)}}(),applyMatrix4:function(a){this.origin.applyMatrix4(a);this.direction.transformDirection(a);return this}, -equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}});Object.assign(Hb.prototype,{set:function(a,b){this.start.copy(a);this.end.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.start.copy(a.start);this.end.copy(a.end);return this},getCenter:function(a){return(a||new n).addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){return(a||new n).subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)}, -distance:function(){return this.start.distanceTo(this.end)},at:function(a,b){var c=b||new n;return this.delta(c).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new n,b=new n;return function(c,d){a.subVectors(c,this.start);b.subVectors(this.end,this.start);var e=b.dot(b),e=b.dot(a)/e;d&&(e=Y.clamp(e,0,1));return e}}(),closestPointToPoint:function(a,b,c){a=this.closestPointToPointParameter(a,b);c=c||new n;return this.delta(c).multiplyScalar(a).add(this.start)},applyMatrix4:function(a){this.start.applyMatrix4(a); -this.end.applyMatrix4(a);return this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)}});Object.assign(Ta,{normal:function(){var a=new n;return function(b,c,d,e){e=e||new n;e.subVectors(d,c);a.subVectors(b,c);e.cross(a);b=e.lengthSq();return 0=b.x+b.y}}()});Object.assign(Ta.prototype,{set:function(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this},setFromPointsAndIndices:function(a,b,c,d){this.a.copy(a[b]);this.b.copy(a[c]);this.c.copy(a[d]);return this},clone:function(){return(new this.constructor).copy(this)}, -copy:function(a){this.a.copy(a.a);this.b.copy(a.b);this.c.copy(a.c);return this},area:function(){var a=new n,b=new n;return function(){a.subVectors(this.c,this.b);b.subVectors(this.a,this.b);return.5*a.cross(b).length()}}(),midpoint:function(a){return(a||new n).addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(a){return Ta.normal(this.a,this.b,this.c,a)},plane:function(a){return(a||new Aa).setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return Ta.barycoordFromPoint(a, -this.a,this.b,this.c,b)},containsPoint:function(a){return Ta.containsPoint(a,this.a,this.b,this.c)},closestPointToPoint:function(){var a=new Aa,b=[new Hb,new Hb,new Hb],c=new n,d=new n;return function(e,f){var g=f||new n,h=Infinity;a.setFromCoplanarPoints(this.a,this.b,this.c);a.projectPoint(e,c);if(!0===this.containsPoint(c))g.copy(c);else{b[0].set(this.a,this.b);b[1].set(this.b,this.c);b[2].set(this.c,this.a);for(var k=0;kb.far?null:{distance:c,point:x.clone(),object:a}}function c(c,d,e,f,m,q,l,n){g.fromBufferAttribute(f,q);h.fromBufferAttribute(f,l);k.fromBufferAttribute(f,n);if(c=b(c,d,e,g,h,k,y))m&&(p.fromBufferAttribute(m,q),r.fromBufferAttribute(m, -l),ca.fromBufferAttribute(m,n),c.uv=a(y,g,h,k,p,r,ca)),c.face=new Sa(q,l,n,Ta.normal(g,h,k)),c.faceIndex=q;return c}var d=new K,e=new kb,f=new Ea,g=new n,h=new n,k=new n,m=new n,q=new n,l=new n,p=new C,r=new C,ca=new C,t=new n,y=new n,x=new n;return function(n,t){var w=this.geometry,x=this.material,B=this.matrixWorld;if(void 0!==x&&(null===w.boundingSphere&&w.computeBoundingSphere(),f.copy(w.boundingSphere),f.applyMatrix4(B),!1!==n.ray.intersectsSphere(f)&&(d.getInverse(B),e.copy(n.ray).applyMatrix4(d), -null===w.boundingBox||!1!==e.intersectsBox(w.boundingBox)))){var D;if(w.isBufferGeometry){var O,C,x=w.index,F=w.attributes.position,B=w.attributes.uv,z,T;if(null!==x)for(z=0,T=x.count;zf||(f=d.ray.origin.distanceTo(a),fd.far||e.push({distance:f,point:a.clone(),face:null,object:this}))}}(),clone:function(){return(new this.constructor(this.material)).copy(this)}});yc.prototype=Object.assign(Object.create(z.prototype),{constructor:yc,copy:function(a){z.prototype.copy.call(this,a, -!1);a=a.levels;for(var b=0,c=a.length;b=d[e].distance)d[e-1].object.visible=!1,d[e].object.visible=!0;else break;for(;ef||(q.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(q),td.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else for(g=0,ca=r.length/3-1;gf||(q.applyMatrix4(this.matrixWorld), -t=d.ray.origin.distanceTo(q),td.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else if(g.isGeometry)for(k=g.vertices,m=k.length,g=0;gf||(q.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(q),td.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry, -this.material)).copy(this)}});Q.prototype=Object.assign(Object.create(sa.prototype),{constructor:Q,isLineSegments:!0});od.prototype=Object.assign(Object.create(sa.prototype),{constructor:od,isLineLoop:!0});Fa.prototype=Object.create(U.prototype);Fa.prototype.constructor=Fa;Fa.prototype.isPointsMaterial=!0;Fa.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.size=a.size;this.sizeAttenuation=a.sizeAttenuation;return this};Kb.prototype=Object.assign(Object.create(z.prototype), -{constructor:Kb,isPoints:!0,raycast:function(){var a=new K,b=new kb,c=new Ea;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a);if(fd.far||e.push({distance:m,distanceToRay:Math.sqrt(f),point:h.clone(),index:c,face:null,object:g})}}var g=this,h=this.geometry,k=this.matrixWorld,m=d.params.Points.threshold;null===h.boundingSphere&&h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k); -c.radius+=m;if(!1!==d.ray.intersectsSphere(c)){a.getInverse(k);b.copy(d.ray).applyMatrix4(a);var m=m/((this.scale.x+this.scale.y+this.scale.z)/3),q=m*m,m=new n;if(h.isBufferGeometry){var l=h.index,h=h.attributes.position.array;if(null!==l)for(var p=l.array,l=0,r=p.length;lc)return null;var d=[],e=[],f=[],g,h,k;if(0=m--){console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()"); -break}g=h;c<=g&&(g=0);h=g+1;c<=h&&(h=0);k=h+1;c<=k&&(k=0);var q;a:{var l,p,r,n,t,y,x,u;l=a[e[g]].x;p=a[e[g]].y;r=a[e[h]].x;n=a[e[h]].y;t=a[e[k]].x;y=a[e[k]].y;if(0>=(r-l)*(y-p)-(n-p)*(t-l))q=!1;else{var H,w,I,z,D,O,B,C,E,G;H=t-r;w=y-n;I=l-t;z=p-y;D=r-l;O=n-p;for(q=0;q=-Number.EPSILON&&C>=-Number.EPSILON&&B>=-Number.EPSILON)){q=!1;break a}q=!0}}if(q){d.push([a[e[g]], -a[e[h]],a[e[k]]]);f.push([e[g],e[h],e[k]]);g=h;for(k=h+1;kNumber.EPSILON){if(0n||n>p)return[];k=m*q-k* -l;if(0>k||k>p)return[]}else{if(0c?[]:k===c?f?[]:[g]:a<=c?[g,h]:[g,m]}function f(a,b,c,d){var e=b.x-a.x,f=b.y-a.y;b=c.x-a.x;c=c.y-a.y;var g=d.x-a.x;d=d.y-a.y;a=e*c-f*b;e=e*d-f*g;return Math.abs(a)>Number.EPSILON?(b=g*c-d*b,0e&&(e=d);var g=a+1;g>d&&(g=0);d=f(h[a],h[e],h[g],k[b]);if(!d)return!1;d=k.length-1;e=b-1;0>e&&(e=d);g=b+1;g>d&&(g=0);return(d=f(k[b],k[e],k[g],h[a]))?!0:!1}function d(a,b){var c,f;for(c=0;cK){console.log("Infinite Loop! Holes left:"+m.length+", Probably Hole outside Shape!");break}for(l=C;lk;k++)q=m[k].x+":"+m[k].y,q=l[q],void 0!==q&&(m[k]=q);return p.concat()},isClockWise:function(a){return 0>Ia.area(a)}};cb.prototype=Object.create(J.prototype);cb.prototype.constructor=cb;Ga.prototype=Object.create(E.prototype);Ga.prototype.constructor=Ga;Ga.prototype.getArrays= -function(){var a=this.getAttribute("position"),a=a?Array.prototype.slice.call(a.array):[],b=this.getAttribute("uv"),b=b?Array.prototype.slice.call(b.array):[],c=this.index,c=c?Array.prototype.slice.call(c.array):[];return{position:a,uv:b,index:c}};Ga.prototype.addShapeList=function(a,b){var c=a.length;b.arrays=this.getArrays();for(var d=0;dNumber.EPSILON){var k=Math.sqrt(h),m=Math.sqrt(d*d+g*g),h=b.x-f/k;b=b.y+e/k;g=((c.x-g/m-h)*g-(c.y+d/m-b)*d)/(e*g-f*d);d=h+e*g-a.x;e=b+f*g-a.y;f=d*d+e*e;if(2>=f)return new C(d,e);f=Math.sqrt(f/2)}else a=!1,e>Number.EPSILON?d>Number.EPSILON&& -(a=!0):e<-Number.EPSILON?d<-Number.EPSILON&&(a=!0):Math.sign(f)===Math.sign(g)&&(a=!0),a?(d=-f,f=Math.sqrt(h)):(d=e,e=f,f=Math.sqrt(h/2));return new C(d/f,e/f)}function e(a,b){var c,d;for(L=a.length;0<=--L;){c=L;d=L-1;0>d&&(d=a.length-1);var e,f=H+2*y;for(e=0;eMath.abs(g-k)?[new C(a,1-c),new C(h,1-d),new C(m,1-e),new C(n,1-b)]:[new C(g,1-c),new C(k,1-d),new C(l,1-e),new C(p,1-b)]}};Lc.prototype=Object.create(J.prototype);Lc.prototype.constructor=Lc;Ub.prototype=Object.create(Ga.prototype);Ub.prototype.constructor=Ub;Mc.prototype= -Object.create(J.prototype);Mc.prototype.constructor=Mc;mb.prototype=Object.create(E.prototype);mb.prototype.constructor=mb;Nc.prototype=Object.create(J.prototype);Nc.prototype.constructor=Nc;Vb.prototype=Object.create(E.prototype);Vb.prototype.constructor=Vb;Oc.prototype=Object.create(J.prototype);Oc.prototype.constructor=Oc;Wb.prototype=Object.create(E.prototype);Wb.prototype.constructor=Wb;Xb.prototype=Object.create(J.prototype);Xb.prototype.constructor=Xb;Yb.prototype=Object.create(E.prototype); -Yb.prototype.constructor=Yb;Zb.prototype=Object.create(E.prototype);Zb.prototype.constructor=Zb;nb.prototype=Object.create(J.prototype);nb.prototype.constructor=nb;Ua.prototype=Object.create(E.prototype);Ua.prototype.constructor=Ua;Pc.prototype=Object.create(nb.prototype);Pc.prototype.constructor=Pc;Qc.prototype=Object.create(Ua.prototype);Qc.prototype.constructor=Qc;Rc.prototype=Object.create(J.prototype);Rc.prototype.constructor=Rc;$b.prototype=Object.create(E.prototype);$b.prototype.constructor= -$b;var Ma=Object.freeze({WireframeGeometry:Mb,ParametricGeometry:Cc,ParametricBufferGeometry:Nb,TetrahedronGeometry:Ec,TetrahedronBufferGeometry:Ob,OctahedronGeometry:Fc,OctahedronBufferGeometry:lb,IcosahedronGeometry:Gc,IcosahedronBufferGeometry:Pb,DodecahedronGeometry:Hc,DodecahedronBufferGeometry:Qb,PolyhedronGeometry:Dc,PolyhedronBufferGeometry:za,TubeGeometry:Ic,TubeBufferGeometry:Rb,TorusKnotGeometry:Jc,TorusKnotBufferGeometry:Sb,TorusGeometry:Kc,TorusBufferGeometry:Tb,TextGeometry:Lc,TextBufferGeometry:Ub, -SphereGeometry:Mc,SphereBufferGeometry:mb,RingGeometry:Nc,RingBufferGeometry:Vb,PlaneGeometry:vc,PlaneBufferGeometry:jb,LatheGeometry:Oc,LatheBufferGeometry:Wb,ShapeGeometry:Xb,ShapeBufferGeometry:Yb,ExtrudeGeometry:cb,ExtrudeBufferGeometry:Ga,EdgesGeometry:Zb,ConeGeometry:Pc,ConeBufferGeometry:Qc,CylinderGeometry:nb,CylinderBufferGeometry:Ua,CircleGeometry:Rc,CircleBufferGeometry:$b,BoxGeometry:Gb,BoxBufferGeometry:ib});ac.prototype=Object.create(ra.prototype);ac.prototype.constructor=ac;ac.prototype.isShadowMaterial= -!0;bc.prototype=Object.create(ra.prototype);bc.prototype.constructor=bc;bc.prototype.isRawShaderMaterial=!0;Pa.prototype=Object.create(U.prototype);Pa.prototype.constructor=Pa;Pa.prototype.isMeshStandardMaterial=!0;Pa.prototype.copy=function(a){U.prototype.copy.call(this,a);this.defines={STANDARD:""};this.color.copy(a.color);this.roughness=a.roughness;this.metalness=a.metalness;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity= -a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.roughnessMap=a.roughnessMap;this.metalnessMap=a.metalnessMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.envMapIntensity=a.envMapIntensity; -this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};ob.prototype=Object.create(Pa.prototype);ob.prototype.constructor=ob;ob.prototype.isMeshPhysicalMaterial=!0;ob.prototype.copy=function(a){Pa.prototype.copy.call(this,a);this.defines={PHYSICAL:""};this.reflectivity= -a.reflectivity;this.clearCoat=a.clearCoat;this.clearCoatRoughness=a.clearCoatRoughness;return this};Ja.prototype=Object.create(U.prototype);Ja.prototype.constructor=Ja;Ja.prototype.isMeshPhongMaterial=!0;Ja.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.specular.copy(a.specular);this.shininess=a.shininess;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive); -this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe; -this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};pb.prototype=Object.create(Ja.prototype);pb.prototype.constructor=pb;pb.prototype.isMeshToonMaterial=!0;pb.prototype.copy=function(a){Ja.prototype.copy.call(this,a);this.gradientMap=a.gradientMap;return this};qb.prototype=Object.create(U.prototype);qb.prototype.constructor= -qb;qb.prototype.isMeshNormalMaterial=!0;qb.prototype.copy=function(a){U.prototype.copy.call(this,a);this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this}; -rb.prototype=Object.create(U.prototype);rb.prototype.constructor=rb;rb.prototype.isMeshLambertMaterial=!0;rb.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap= -a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};sb.prototype=Object.create(U.prototype);sb.prototype.constructor=sb;sb.prototype.isLineDashedMaterial=!0;sb.prototype.copy=function(a){U.prototype.copy.call(this, -a);this.color.copy(a.color);this.linewidth=a.linewidth;this.scale=a.scale;this.dashSize=a.dashSize;this.gapSize=a.gapSize;return this};var mg=Object.freeze({ShadowMaterial:ac,SpriteMaterial:bb,RawShaderMaterial:bc,ShaderMaterial:ra,PointsMaterial:Fa,MeshPhysicalMaterial:ob,MeshStandardMaterial:Pa,MeshPhongMaterial:Ja,MeshToonMaterial:pb,MeshNormalMaterial:qb,MeshLambertMaterial:rb,MeshDepthMaterial:Za,MeshBasicMaterial:ya,LineDashedMaterial:sb,LineBasicMaterial:ea,Material:U}),ed={enabled:!1,files:{}, -add:function(a,b){!1!==this.enabled&&(this.files[a]=b)},get:function(a){if(!1!==this.enabled)return this.files[a]},remove:function(a){delete this.files[a]},clear:function(){this.files={}}},va=new Zd;Object.assign(Ka.prototype,{load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);var e=this,f=ed.get(a);if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;var g=a.match(/^data:(.*?)(;base64)?,(.*)$/);if(g){var h=g[1],k=!!g[2],g= -g[3],g=window.decodeURIComponent(g);k&&(g=window.atob(g));try{var m,l=(this.responseType||"").toLowerCase();switch(l){case "arraybuffer":case "blob":m=new ArrayBuffer(g.length);for(var n=new Uint8Array(m),k=0;k=e)break a;else{f=b[1];a=e)break b}d=c;c= -0}}for(;c>>1,ab;)--f;++f;if(0!==e||f!==d)e>=f&&(f=Math.max(f, -1),e=f-1),d=this.getValueSize(),this.times=ia.arraySlice(c,e,f),this.values=ia.arraySlice(this.values,e*d,f*d);return this},validate:function(){var a=!0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("THREE.KeyframeTrackPrototype: Invalid value size in track.",this),a=!1);var c=this.times,b=this.values,d=c.length;0===d&&(console.error("THREE.KeyframeTrackPrototype: Track is empty.",this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("THREE.KeyframeTrackPrototype: Time is not a valid number.", -this,f,g);a=!1;break}if(null!==e&&e>g){console.error("THREE.KeyframeTrackPrototype: Out of order keys.",this,f,g,e);a=!1;break}e=g}if(void 0!==b&&ia.isTypedArray(b))for(f=0,c=b.length;f!==c;++f)if(d=b[f],isNaN(d)){console.error("THREE.KeyframeTrackPrototype: Value is not a valid number.",this,f,d);a=!1;break}return a},optimize:function(){for(var a=this.times,b=this.values,c=this.getValueSize(),d=2302===this.getInterpolation(),e=1,f=a.length-1,g=1;gm.opacity&&(m.transparent=!0);d.setTextures(k);return d.parse(m)}}()});Object.assign(ce.prototype, -{load:function(a,b,c,d){var e=this,f=this.texturePath&&"string"===typeof this.texturePath?this.texturePath:ec.prototype.extractUrlBase(a),g=new Ka(this.manager);g.setWithCredentials(this.withCredentials);g.load(a,function(c){c=JSON.parse(c);var d=c.metadata;if(void 0!==d&&(d=d.type,void 0!==d)){if("object"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.ObjectLoader instead.");return}if("scene"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.SceneLoader instead."); -return}}c=e.parse(c,f);b(c.geometry,c.materials)},c,d)},setTexturePath:function(a){this.texturePath=a},parse:function(){return function(a,b){void 0!==a.data&&(a=a.data);a.scale=void 0!==a.scale?1/a.scale:1;var c=new J,d=a,e,f,g,h,k,m,l,v,p,r,z,t,y,x,u=d.faces;p=d.vertices;var B=d.normals,w=d.colors;m=d.scale;var I=0;if(void 0!==d.uvs){for(e=0;ef;f++)v=u[h++],x=y[2*v],v=y[2*v+1],x=new C(x,v),2!==f&&c.faceVertexUvs[e][g].push(x),0!==f&&c.faceVertexUvs[e][g+1].push(x);l&&(l=3*u[h++],r.normal.set(B[l++],B[l++],B[l]), -t.normal.copy(r.normal));if(z)for(e=0;4>e;e++)l=3*u[h++],z=new n(B[l++],B[l++],B[l]),2!==e&&r.vertexNormals.push(z),0!==e&&t.vertexNormals.push(z);m&&(m=u[h++],m=w[m],r.color.setHex(m),t.color.setHex(m));if(p)for(e=0;4>e;e++)m=u[h++],m=w[m],2!==e&&r.vertexColors.push(new G(m)),0!==e&&t.vertexColors.push(new G(m));c.faces.push(r);c.faces.push(t)}else{r=new Sa;r.a=u[h++];r.b=u[h++];r.c=u[h++];g&&(g=u[h++],r.materialIndex=g);g=c.faces.length;if(e)for(e=0;ef;f++)v=u[h++],x=y[2*v],v=y[2*v+1],x=new C(x,v),c.faceVertexUvs[e][g].push(x);l&&(l=3*u[h++],r.normal.set(B[l++],B[l++],B[l]));if(z)for(e=0;3>e;e++)l=3*u[h++],z=new n(B[l++],B[l++],B[l]),r.vertexNormals.push(z);m&&(m=u[h++],r.color.setHex(w[m]));if(p)for(e=0;3>e;e++)m=u[h++],r.vertexColors.push(new G(w[m]));c.faces.push(r)}d=a;h=void 0!==d.influencesPerVertex?d.influencesPerVertex:2;if(d.skinWeights)for(k=0,u=d.skinWeights.length;kk)g=d+1;else if(0b&&(b=0);1Number.EPSILON&&(g.normalize(),c=Math.acos(Y.clamp(d[k-1].dot(d[k]),-1,1)),e[k].applyMatrix4(h.makeRotationAxis(g,c))),f[k].crossVectors(d[k],e[k]);if(!0===b)for(c=Math.acos(Y.clamp(e[0].dot(e[a]),-1,1)),c/=a,0=b)return b=c[a]-b,a=this.curves[a],c=a.getLength(),a.getPointAt(0===c?0:1-b/c);a++}return null},getLength:function(){var a=this.getCurveLengths();return a[a.length-1]},updateArcLengths:function(){this.needsUpdate=!0;this.cacheLengths=null;this.getCurveLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths; -for(var a=[],b=0,c=0,d=this.curves.length;cc;)c+=b;for(;c>b;)c-=b;cb.length-2?b.length-1:a+1],b=b[a>b.length-3?b.length-1:a+2];return new C(Qe(c,d.x,e.x,f.x,b.x),Qe(c,d.y,e.y,f.y,b.y))};fc.prototype=Object.create(ua.prototype);fc.prototype.constructor=fc;fc.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2,e=this.v3;return new C(xb(a,b.x,c.x,d.x,e.x),xb(a,b.y,c.y,d.y,e.y))};gc.prototype=Object.create(ua.prototype); -gc.prototype.constructor=gc;gc.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2;return new C(wb(a,b.x,c.x,d.x),wb(a,b.y,c.y,d.y))};var te=Object.assign(Object.create(Vc.prototype),{fromPoints:function(a){this.moveTo(a[0].x,a[0].y);for(var b=1,c=a.length;bNumber.EPSILON){if(0>m&&(g=b[f],k=-k,h=b[e],m=-m),!(a.yh.y))if(a.y===g.y){if(a.x===g.x)return!0}else{e=m*(a.x-g.x)-k*(a.y-g.y);if(0===e)return!0; -0>e||(d=!d)}}else if(a.y===g.y&&(h.x<=a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=Ia.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);var g,h,k,m=[];if(1===f.length)return h=f[0],k=new zb,k.curves=h.curves,m.push(k),m;var l=!e(f[0].getPoints()),l=a?!l:l;k=[];var n=[],p=[],r=0,z;n[r]=void 0;p[r]=[];for(var t=0,y=f.length;td&& -this._mixBufferRegion(c,a,3*b,1-d,b);for(var d=b,f=b+b;d!==f;++d)if(c[d]!==c[d+b]){e.setValue(c,a);break}},saveOriginalState:function(){var a=this.buffer,b=this.valueSize,c=3*b;this.binding.getValue(a,c);for(var d=b;d!==c;++d)a[d]=a[c+d%b];this.cumulativeWeight=0},restoreOriginalState:function(){this.binding.setValue(this.buffer,3*this.valueSize)},_select:function(a,b,c,d,e){if(.5<=d)for(d=0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d){oa.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f= -1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}});Object.assign(Te.prototype,{getValue:function(a,b){this.bind();var c=this._bindings[this._targetGroup.nCachedObjects_];void 0!==c&&c.getValue(a,b)},setValue:function(a,b){for(var c=this._bindings,d=this._targetGroup.nCachedObjects_,e=c.length;d!==e;++d)c[d].setValue(a,b)},bind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].bind()},unbind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_, -c=a.length;b!==c;++b)a[b].unbind()}});Object.assign(ha,{Composite:Te,create:function(a,b,c){return a&&a.isAnimationObjectGroup?new ha.Composite(a,b,c):new ha(a,b,c)},sanitizeNodeName:function(a){return a.replace(/\s/g,"_").replace(/[^\w-]/g,"")},parseTrackName:function(){var a=new RegExp("^"+/((?:[\w-]+[\/:])*)/.source+/([\w-\.]+)?/.source+/(?:\.([\w-]+)(?:\[(.+)\])?)?/.source+/\.([\w-]+)(?:\[(.+)\])?/.source+"$"),b=["material","materials","bones"];return function(c){var d=a.exec(c);if(!d)throw Error("PropertyBinding: Cannot parse trackName: "+ -c);var d={nodeName:d[2],objectName:d[3],objectIndex:d[4],propertyName:d[5],propertyIndex:d[6]},e=d.nodeName&&d.nodeName.lastIndexOf(".");if(void 0!==e&&-1!==e){var f=d.nodeName.substring(e+1);-1!==b.indexOf(f)&&(d.nodeName=d.nodeName.substring(0,e),d.objectName=f)}if(null===d.propertyName||0===d.propertyName.length)throw Error("PropertyBinding: can not parse propertyName from trackName: "+c);return d}}(),findNode:function(a,b){if(!b||""===b||"root"===b||"."===b||-1===b||b===a.name||b===a.uuid)return a; -if(a.skeleton){var c=function(a){for(var c=0;cthis.opacity&&(d.opacity=this.opacity); +!0===this.transparent&&(d.transparent=this.transparent);d.depthFunc=this.depthFunc;d.depthTest=this.depthTest;d.depthWrite=this.depthWrite;0!==this.rotation&&(d.rotation=this.rotation);1!==this.linewidth&&(d.linewidth=this.linewidth);void 0!==this.dashSize&&(d.dashSize=this.dashSize);void 0!==this.gapSize&&(d.gapSize=this.gapSize);void 0!==this.scale&&(d.scale=this.scale);!0===this.dithering&&(d.dithering=!0);0 +a?b.copy(this.origin):b.copy(this.direction).multiplyScalar(a).add(this.origin)},distanceToPoint:function(a){return Math.sqrt(this.distanceSqToPoint(a))},distanceSqToPoint:function(){var a=new p;return function(b){var c=a.subVectors(b,this.origin).dot(this.direction);if(0>c)return this.origin.distanceToSquared(b);a.copy(this.direction).multiplyScalar(c).add(this.origin);return a.distanceToSquared(b)}}(),distanceSqToSegment:function(){var a=new p,b=new p,c=new p;return function(d,e,f,g){a.copy(d).add(e).multiplyScalar(.5); +b.copy(e).sub(d).normalize();c.copy(this.origin).sub(a);var h=.5*d.distanceTo(e),l=-this.direction.dot(b),m=c.dot(this.direction),k=-c.dot(b),n=c.lengthSq(),p=Math.abs(1-l*l);if(0=-r?e<=r?(h=1/p,d*=h,e*=h,l=d*(d+l*e+2*m)+e*(l*d+e+2*k)+n):(e=h,d=Math.max(0,-(l*e+m)),l=-d*d+e*(e+2*k)+n):(e=-h,d=Math.max(0,-(l*e+m)),l=-d*d+e*(e+2*k)+n):e<=-r?(d=Math.max(0,-(-l*h+m)),e=0b)return null;b=Math.sqrt(b-e);e=d-b;d+=b;return 0>e&&0>d?null:0>e?this.at(d, +c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<=a.radius},distanceToPlane:function(a){var b=a.normal.dot(this.direction);if(0===b)return 0===a.distanceToPoint(this.origin)?0:null;a=-(this.origin.dot(a.normal)+a.constant)/b;return 0<=a?a:null},intersectPlane:function(a,b){a=this.distanceToPlane(a);return null===a?null:this.at(a,b)},intersectsPlane:function(a){var b=a.distanceToPoint(this.origin);return 0===b||0>a.normal.dot(this.direction)*b?!0:!1},intersectBox:function(a, +b){var c=1/this.direction.x;var d=1/this.direction.y;var e=1/this.direction.z,f=this.origin;if(0<=c){var g=(a.min.x-f.x)*c;c*=a.max.x-f.x}else g=(a.max.x-f.x)*c,c*=a.min.x-f.x;if(0<=d){var h=(a.min.y-f.y)*d;d*=a.max.y-f.y}else h=(a.max.y-f.y)*d,d*=a.min.y-f.y;if(g>d||h>c)return null;if(h>g||g!==g)g=h;if(da||h>c)return null;if(h>g||g!==g)g=h;if(ac?null:this.at(0<=g?g:c,b)},intersectsBox:function(){var a= +new p;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a=new p,b=new p,c=new p,d=new p;return function(e,f,g,h,l){b.subVectors(f,e);c.subVectors(g,e);d.crossVectors(b,c);f=this.direction.dot(d);if(0f)h=-1,f=-f;else return null;a.subVectors(this.origin,e);e=h*this.direction.dot(c.crossVectors(a,c));if(0>e)return null;g=h*this.direction.dot(b.cross(a));if(0>g||e+g>f)return null;e=-h*a.dot(d);return 0>e?null:this.at(e/f,l)}}(), +applyMatrix4:function(a){this.origin.applyMatrix4(a);this.direction.transformDirection(a);return this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}});Object.assign(Lb.prototype,{set:function(a,b){this.start.copy(a);this.end.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.start.copy(a.start);this.end.copy(a.end);return this},getCenter:function(a){void 0===a&&(console.warn("THREE.Line3: .getCenter() target is now required"), +a=new p);return a.addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){void 0===a&&(console.warn("THREE.Line3: .delta() target is now required"),a=new p);return a.subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(a,b){void 0===b&&(console.warn("THREE.Line3: .at() target is now required"),b=new p);return this.delta(b).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a= +new p,b=new p;return function(c,d){a.subVectors(c,this.start);b.subVectors(this.end,this.start);c=b.dot(b);c=b.dot(a)/c;d&&(c=S.clamp(c,0,1));return c}}(),closestPointToPoint:function(a,b,c){a=this.closestPointToPointParameter(a,b);void 0===c&&(console.warn("THREE.Line3: .closestPointToPoint() target is now required"),c=new p);return this.delta(c).multiplyScalar(a).add(this.start)},applyMatrix4:function(a){this.start.applyMatrix4(a);this.end.applyMatrix4(a);return this},equals:function(a){return a.start.equals(this.start)&& +a.end.equals(this.end)}});Object.assign(Aa,{getNormal:function(){var a=new p;return function(b,c,d,e){void 0===e&&(console.warn("THREE.Triangle: .getNormal() target is now required"),e=new p);e.subVectors(d,c);a.subVectors(b,c);e.cross(a);b=e.lengthSq();return 0=a.x+a.y}}()});Object.assign(Aa.prototype,{set:function(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this},setFromPointsAndIndices:function(a,b,c,d){this.a.copy(a[b]);this.b.copy(a[c]); +this.c.copy(a[d]);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a.copy(a.a);this.b.copy(a.b);this.c.copy(a.c);return this},getArea:function(){var a=new p,b=new p;return function(){a.subVectors(this.c,this.b);b.subVectors(this.a,this.b);return.5*a.cross(b).length()}}(),getMidpoint:function(a){void 0===a&&(console.warn("THREE.Triangle: .getMidpoint() target is now required"),a=new p);return a.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},getNormal:function(a){return Aa.getNormal(this.a, +this.b,this.c,a)},getPlane:function(a){void 0===a&&(console.warn("THREE.Triangle: .getPlane() target is now required"),a=new p);return a.setFromCoplanarPoints(this.a,this.b,this.c)},getBarycoord:function(a,b){return Aa.getBarycoord(a,this.a,this.b,this.c,b)},containsPoint:function(a){return Aa.containsPoint(a,this.a,this.b,this.c)},intersectsBox:function(a){return a.intersectsTriangle(this)},closestPointToPoint:function(){var a=new Fa,b=[new Lb,new Lb,new Lb],c=new p,d=new p;return function(e,f){void 0=== +f&&(console.warn("THREE.Triangle: .closestPointToPoint() target is now required"),f=new p);var g=Infinity;a.setFromCoplanarPoints(this.a,this.b,this.c);a.projectPoint(e,c);if(!0===this.containsPoint(c))f.copy(c);else for(b[0].set(this.a,this.b),b[1].set(this.b,this.c),b[2].set(this.c,this.a),e=0;ec.far?null:{distance:b,point:y.clone(),object:a}}function c(c,d,e,f,m,k,n,p){g.fromBufferAttribute(f,k);h.fromBufferAttribute(f,n);l.fromBufferAttribute(f,p);if(c=b(c,c.material, +d,e,g,h,l,x))m&&(t.fromBufferAttribute(m,k),r.fromBufferAttribute(m,n),q.fromBufferAttribute(m,p),c.uv=a(x,g,h,l,t,r,q)),m=new Wa(k,n,p),Aa.getNormal(g,h,l,m.normal),c.face=m,c.faceIndex=k;return c}var d=new M,e=new qb,f=new Ea,g=new p,h=new p,l=new p,m=new p,k=new p,n=new p,t=new C,r=new C,q=new C,v=new p,x=new p,y=new p;return function(p,u){var v=this.geometry,w=this.material,y=this.matrixWorld;if(void 0!==w&&(null===v.boundingSphere&&v.computeBoundingSphere(),f.copy(v.boundingSphere),f.applyMatrix4(y), +!1!==p.ray.intersectsSphere(f)&&(d.getInverse(y),e.copy(p.ray).applyMatrix4(d),null===v.boundingBox||!1!==e.intersectsBox(v.boundingBox)))){var B;if(v.isBufferGeometry){w=v.index;var C=v.attributes.position;y=v.attributes.uv;var A;if(null!==w){var z=0;for(A=w.count;zf||(f=d.ray.origin.distanceTo(a),fd.far||e.push({distance:f,point:a.clone(),face:null,object:this}))}}(),clone:function(){return(new this.constructor(this.material)).copy(this)},copy:function(a){A.prototype.copy.call(this,a);void 0!==a.center&& +this.center.copy(a.center);return this}});Bc.prototype=Object.assign(Object.create(A.prototype),{constructor:Bc,copy:function(a){A.prototype.copy.call(this,a,!1);a=a.levels;for(var b=0,c=a.length;b=d[e].distance)d[e-1].object.visible= +!1,d[e].object.visible=!0;else break;for(;ef||(k.applyMatrix4(this.matrixWorld),v=d.ray.origin.distanceTo(k),vd.far||e.push({distance:v,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}else for(g=0,q=r.length/3-1;gf||(k.applyMatrix4(this.matrixWorld),v=d.ray.origin.distanceTo(k),vd.far||e.push({distance:v,point:h.clone().applyMatrix4(this.matrixWorld), +index:g,face:null,faceIndex:null,object:this}))}else if(g.isGeometry)for(l=g.vertices,m=l.length,g=0;gf||(k.applyMatrix4(this.matrixWorld),v=d.ray.origin.distanceTo(k),vd.far||e.push({distance:v,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});aa.prototype=Object.assign(Object.create(ua.prototype), +{constructor:aa,isLineSegments:!0,computeLineDistances:function(){var a=new p,b=new p;return function(){var c=this.geometry;if(c.isBufferGeometry)if(null===c.index){for(var d=c.attributes.position,e=[],f=0,g=d.count;fd.far||e.push({distance:a,distanceToRay:Math.sqrt(f),point:n.clone(),index:c,face:null,object:g}))}var g=this,h=this.geometry,l=this.matrixWorld,m=d.params.Points.threshold;null===h.boundingSphere&&h.computeBoundingSphere(); +c.copy(h.boundingSphere);c.applyMatrix4(l);c.radius+=m;if(!1!==d.ray.intersectsSphere(c)){a.getInverse(l);b.copy(d.ray).applyMatrix4(a);m/=(this.scale.x+this.scale.y+this.scale.z)/3;var k=m*m;m=new p;var n=new p;if(h.isBufferGeometry){var t=h.index;h=h.attributes.position.array;if(null!==t){var r=t.array;t=0;for(var q=r.length;t=a.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}});Rb.prototype=Object.create(Y.prototype);Rb.prototype.constructor=Rb;Rb.prototype.isCompressedTexture=!0;Dc.prototype=Object.create(Y.prototype);Dc.prototype.constructor=Dc;Dc.prototype.isDepthTexture=!0;Sb.prototype= +Object.create(F.prototype);Sb.prototype.constructor=Sb;Ec.prototype=Object.create(N.prototype);Ec.prototype.constructor=Ec;Tb.prototype=Object.create(F.prototype);Tb.prototype.constructor=Tb;Fc.prototype=Object.create(N.prototype);Fc.prototype.constructor=Fc;pa.prototype=Object.create(F.prototype);pa.prototype.constructor=pa;Gc.prototype=Object.create(N.prototype);Gc.prototype.constructor=Gc;Ub.prototype=Object.create(pa.prototype);Ub.prototype.constructor=Ub;Hc.prototype=Object.create(N.prototype); +Hc.prototype.constructor=Hc;sb.prototype=Object.create(pa.prototype);sb.prototype.constructor=sb;Ic.prototype=Object.create(N.prototype);Ic.prototype.constructor=Ic;Vb.prototype=Object.create(pa.prototype);Vb.prototype.constructor=Vb;Jc.prototype=Object.create(N.prototype);Jc.prototype.constructor=Jc;Wb.prototype=Object.create(pa.prototype);Wb.prototype.constructor=Wb;Kc.prototype=Object.create(N.prototype);Kc.prototype.constructor=Kc;Xb.prototype=Object.create(F.prototype);Xb.prototype.constructor= +Xb;Lc.prototype=Object.create(N.prototype);Lc.prototype.constructor=Lc;Yb.prototype=Object.create(F.prototype);Yb.prototype.constructor=Yb;Mc.prototype=Object.create(N.prototype);Mc.prototype.constructor=Mc;Zb.prototype=Object.create(F.prototype);Zb.prototype.constructor=Zb;var Lg={triangulate:function(a,b,c){c=c||2;var d=b&&b.length,e=d?b[0]*c:a.length,f=Xe(a,0,e,c,!0),g=[];if(!f)return g;var h;if(d){var l=c;d=[];var m;var k=0;for(m=b.length;k80*c){var r=h=a[0];var q=d=a[1];for(l=c;lh&&(h=k),b>d&&(d=b);h=Math.max(h-r,d-q);h=0!==h?1/h:0}Pc(f,g,c,r,q,h);return g}},Xa={area:function(a){for(var b=a.length,c=0,d=b-1,e=0;eXa.area(a)},triangulateShape:function(a, +b){var c=[],d=[],e=[];af(a);bf(c,a);var f=a.length;b.forEach(af);for(a=0;aNumber.EPSILON){var l=Math.sqrt(h),m=Math.sqrt(f*f+g*g);h=b.x-e/l;b=b.y+d/l;g=((c.x-g/m-h)*g-(c.y+f/m-b)*f)/(d*g-e*f);f=h+d*g-a.x;d=b+e*g-a.y;e=f*f+d*d;if(2>=e)return new C(f,d);e=Math.sqrt(e/2)}else a=!1,d>Number.EPSILON?f>Number.EPSILON&&(a=!0):d<-Number.EPSILON?f<-Number.EPSILON&&(a=!0):Math.sign(e)===Math.sign(g)&&(a=!0),a?(f=-e,e=Math.sqrt(h)):(f=d,d=e,e=Math.sqrt(h/2));return new C(f/e,d/ +e)}function e(a,b){for(J=a.length;0<=--J;){var c=J;var d=J-1;0>d&&(d=a.length-1);var e,f=B+2*x;for(e=0;eMath.abs(g-l)?[new C(a,1-c),new C(h,1-d),new C(m,1-e),new C(n,1-b)]:[new C(g,1-c),new C(l,1-d),new C(k,1-e),new C(p,1-b)]}};Rc.prototype=Object.create(N.prototype);Rc.prototype.constructor=Rc;$b.prototype=Object.create(Ia.prototype);$b.prototype.constructor=$b;Sc.prototype=Object.create(N.prototype);Sc.prototype.constructor=Sc;ub.prototype=Object.create(F.prototype);ub.prototype.constructor=ub;Tc.prototype=Object.create(N.prototype);Tc.prototype.constructor= +Tc;ac.prototype=Object.create(F.prototype);ac.prototype.constructor=ac;Uc.prototype=Object.create(N.prototype);Uc.prototype.constructor=Uc;bc.prototype=Object.create(F.prototype);bc.prototype.constructor=bc;vb.prototype=Object.create(N.prototype);vb.prototype.constructor=vb;vb.prototype.toJSON=function(){var a=N.prototype.toJSON.call(this);return cf(this.parameters.shapes,a)};wb.prototype=Object.create(F.prototype);wb.prototype.constructor=wb;wb.prototype.toJSON=function(){var a=F.prototype.toJSON.call(this); +return cf(this.parameters.shapes,a)};cc.prototype=Object.create(F.prototype);cc.prototype.constructor=cc;xb.prototype=Object.create(N.prototype);xb.prototype.constructor=xb;Ya.prototype=Object.create(F.prototype);Ya.prototype.constructor=Ya;Vc.prototype=Object.create(xb.prototype);Vc.prototype.constructor=Vc;Wc.prototype=Object.create(Ya.prototype);Wc.prototype.constructor=Wc;Xc.prototype=Object.create(N.prototype);Xc.prototype.constructor=Xc;dc.prototype=Object.create(F.prototype);dc.prototype.constructor= +dc;var Ca=Object.freeze({WireframeGeometry:Sb,ParametricGeometry:Ec,ParametricBufferGeometry:Tb,TetrahedronGeometry:Gc,TetrahedronBufferGeometry:Ub,OctahedronGeometry:Hc,OctahedronBufferGeometry:sb,IcosahedronGeometry:Ic,IcosahedronBufferGeometry:Vb,DodecahedronGeometry:Jc,DodecahedronBufferGeometry:Wb,PolyhedronGeometry:Fc,PolyhedronBufferGeometry:pa,TubeGeometry:Kc,TubeBufferGeometry:Xb,TorusKnotGeometry:Lc,TorusKnotBufferGeometry:Yb,TorusGeometry:Mc,TorusBufferGeometry:Zb,TextGeometry:Rc,TextBufferGeometry:$b, +SphereGeometry:Sc,SphereBufferGeometry:ub,RingGeometry:Tc,RingBufferGeometry:ac,PlaneGeometry:xc,PlaneBufferGeometry:pb,LatheGeometry:Uc,LatheBufferGeometry:bc,ShapeGeometry:vb,ShapeBufferGeometry:wb,ExtrudeGeometry:fb,ExtrudeBufferGeometry:Ia,EdgesGeometry:cc,ConeGeometry:Vc,ConeBufferGeometry:Wc,CylinderGeometry:xb,CylinderBufferGeometry:Ya,CircleGeometry:Xc,CircleBufferGeometry:dc,BoxGeometry:Kb,BoxBufferGeometry:mb});yb.prototype=Object.create(O.prototype);yb.prototype.constructor=yb;yb.prototype.isShadowMaterial= +!0;yb.prototype.copy=function(a){O.prototype.copy.call(this,a);this.color.copy(a.color);return this};ec.prototype=Object.create(va.prototype);ec.prototype.constructor=ec;ec.prototype.isRawShaderMaterial=!0;Sa.prototype=Object.create(O.prototype);Sa.prototype.constructor=Sa;Sa.prototype.isMeshStandardMaterial=!0;Sa.prototype.copy=function(a){O.prototype.copy.call(this,a);this.defines={STANDARD:""};this.color.copy(a.color);this.roughness=a.roughness;this.metalness=a.metalness;this.map=a.map;this.lightMap= +a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.roughnessMap=a.roughnessMap;this.metalnessMap= +a.metalnessMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.envMapIntensity=a.envMapIntensity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};zb.prototype=Object.create(Sa.prototype);zb.prototype.constructor=zb;zb.prototype.isMeshPhysicalMaterial= +!0;zb.prototype.copy=function(a){Sa.prototype.copy.call(this,a);this.defines={PHYSICAL:""};this.reflectivity=a.reflectivity;this.clearCoat=a.clearCoat;this.clearCoatRoughness=a.clearCoatRoughness;return this};Ja.prototype=Object.create(O.prototype);Ja.prototype.constructor=Ja;Ja.prototype.isMeshPhongMaterial=!0;Ja.prototype.copy=function(a){O.prototype.copy.call(this,a);this.color.copy(a.color);this.specular.copy(a.specular);this.shininess=a.shininess;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity= +a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine= +a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};Ab.prototype=Object.create(Ja.prototype);Ab.prototype.constructor=Ab;Ab.prototype.isMeshToonMaterial=!0;Ab.prototype.copy=function(a){Ja.prototype.copy.call(this, +a);this.gradientMap=a.gradientMap;return this};Bb.prototype=Object.create(O.prototype);Bb.prototype.constructor=Bb;Bb.prototype.isMeshNormalMaterial=!0;Bb.prototype.copy=function(a){O.prototype.copy.call(this,a);this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth; +this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};Cb.prototype=Object.create(O.prototype);Cb.prototype.constructor=Cb;Cb.prototype.isMeshLambertMaterial=!0;Cb.prototype.copy=function(a){O.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity= +a.emissiveIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};Db.prototype=Object.create(U.prototype);Db.prototype.constructor= +Db;Db.prototype.isLineDashedMaterial=!0;Db.prototype.copy=function(a){U.prototype.copy.call(this,a);this.scale=a.scale;this.dashSize=a.dashSize;this.gapSize=a.gapSize;return this};var Mg=Object.freeze({ShadowMaterial:yb,SpriteMaterial:eb,RawShaderMaterial:ec,ShaderMaterial:va,PointsMaterial:Ha,MeshPhysicalMaterial:zb,MeshStandardMaterial:Sa,MeshPhongMaterial:Ja,MeshToonMaterial:Ab,MeshNormalMaterial:Bb,MeshLambertMaterial:Cb,MeshDepthMaterial:cb,MeshDistanceMaterial:db,MeshBasicMaterial:za,LineDashedMaterial:Db, +LineBasicMaterial:U,Material:O}),Hb={enabled:!1,files:{},add:function(a,b){!1!==this.enabled&&(this.files[a]=b)},get:function(a){if(!1!==this.enabled)return this.files[a]},remove:function(a){delete this.files[a]},clear:function(){this.files={}}},ma=new ae,$a={};Object.assign(Ka.prototype,{load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);a=this.manager.resolveURL(a);var e=this,f=Hb.get(a);if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)}, +0),f;if(void 0!==$a[a])$a[a].push({onLoad:b,onProgress:c,onError:d});else{var g=a.match(/^data:(.*?)(;base64)?,(.*)$/);if(g){c=g[1];var h=!!g[2];g=g[3];g=window.decodeURIComponent(g);h&&(g=window.atob(g));try{var l=(this.responseType||"").toLowerCase();switch(l){case "arraybuffer":case "blob":var m=new Uint8Array(g.length);for(h=0;hg)e=a+1;else if(0b&&(b=0);1Number.EPSILON&&(g.normalize(),c=Math.acos(S.clamp(d[l-1].dot(d[l]),-1,1)),e[l].applyMatrix4(h.makeRotationAxis(g,c))),f[l].crossVectors(d[l],e[l]);if(!0===b)for(c=Math.acos(S.clamp(e[0].dot(e[a]),-1,1)),c/=a,0d;)d+=c;for(;d>c;)d-=c;de&&(e=1);1E-4>d&&(d=e);1E-4>l&&(l=e);ye.initNonuniformCatmullRom(f.x,g.x,h.x,c.x,d,e,l);ze.initNonuniformCatmullRom(f.y,g.y,h.y,c.y,d,e,l);Ae.initNonuniformCatmullRom(f.z,g.z,h.z,c.z,d,e,l)}else"catmullrom"===this.curveType&&(ye.initCatmullRom(f.x,g.x,h.x,c.x,this.tension),ze.initCatmullRom(f.y,g.y,h.y,c.y,this.tension),Ae.initCatmullRom(f.z,g.z,h.z,c.z,this.tension));b.set(ye.calc(a), +ze.calc(a),Ae.calc(a));return b};X.prototype.copy=function(a){E.prototype.copy.call(this,a);this.points=[];for(var b=0,c=a.points.length;bc.length-2?c.length-1:a+1];c=c[a>c.length-3?c.length-1:a+2];b.set(ef(d,e.x,f.x,g.x,c.x),ef(d,e.y,f.y,g.y,c.y));return b};Oa.prototype.copy=function(a){E.prototype.copy.call(this,a);this.points=[];for(var b=0,c=a.points.length;b=b)return b=c[a]-b,a=this.curves[a],c=a.getLength(),a.getPointAt(0===c?0:1-b/c);a++}return null},getLength:function(){var a=this.getCurveLengths(); +return a[a.length-1]},updateArcLengths:function(){this.needsUpdate=!0;this.cacheLengths=null;this.getCurveLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var a=[],b=0,c=0,d=this.curves.length;c=e)break a;else{f=b[1];a=e)break b}d=c;c=0}}for(;c>>1,ab;)--f;++f;if(0!==e||f!==d)e>=f&&(f=Math.max(f,1),e=f-1),a=this.getValueSize(),this.times=fa.arraySlice(c,e,f),this.values=fa.arraySlice(this.values,e*a,f*a);return this},validate:function(){var a=!0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),a=!1);var c=this.times;b=this.values;var d=c.length;0===d&&(console.error("THREE.KeyframeTrack: Track is empty.", +this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,f,g);a=!1;break}if(null!==e&&e>g){console.error("THREE.KeyframeTrack: Out of order keys.",this,f,g,e);a=!1;break}e=g}if(void 0!==b&&fa.isTypedArray(b))for(f=0,c=b.length;f!==c;++f)if(d=b[f],isNaN(d)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,f,d);a=!1;break}return a},optimize:function(){for(var a=this.times,b=this.values, +c=this.getValueSize(),d=2302===this.getInterpolation(),e=1,f=a.length-1,g=1;gk.opacity&&(k.transparent=!0);d.setTextures(l);return d.parse(k)}}()});var Be={decodeText:function(a){if("undefined"!==typeof TextDecoder)return(new TextDecoder).decode(a);for(var b="",c=0,d=a.length;cf;f++){var z=h[r++];var A=B[2*z];z=B[2*z+1];A=new C(A,z);2!==f&&c.faceVertexUvs[e][v].push(A);0!==f&&c.faceVertexUvs[e][v+1].push(A)}}x&&(x=3*h[r++],q.normal.set(k[x++],k[x++],k[x]),w.normal.copy(q.normal));if(y)for(e=0;4>e;e++)x=3*h[r++],y=new p(k[x++],k[x++],k[x]),2!==e&&q.vertexNormals.push(y),0!==e&&w.vertexNormals.push(y);n&&(n= +h[r++],n=u[n],q.color.setHex(n),w.color.setHex(n));if(l)for(e=0;4>e;e++)n=h[r++],n=u[n],2!==e&&q.vertexColors.push(new I(n)),0!==e&&w.vertexColors.push(new I(n));c.faces.push(q);c.faces.push(w)}else{q=new Wa;q.a=h[r++];q.b=h[r++];q.c=h[r++];v&&(v=h[r++],q.materialIndex=v);v=c.faces.length;if(e)for(e=0;ef;f++)z=h[r++],A=B[2*z],z=B[2*z+1],A=new C(A,z),c.faceVertexUvs[e][v].push(A);x&&(x=3*h[r++],q.normal.set(k[x++],k[x++],k[x]));if(y)for(e=0;3>e;e++)x= +3*h[r++],y=new p(k[x++],k[x++],k[x]),q.vertexNormals.push(y);n&&(n=h[r++],q.color.setHex(u[n]));if(l)for(e=0;3>e;e++)n=h[r++],q.vertexColors.push(new I(u[n]));c.faces.push(q)}}d=a;r=void 0!==d.influencesPerVertex?d.influencesPerVertex:2;if(d.skinWeights)for(g=0,h=d.skinWeights.length;gNumber.EPSILON){if(0>k&&(g=b[f],l=-l,h=b[e],k=-k),!(a.yh.y))if(a.y===g.y){if(a.x===g.x)return!0}else{e=k*(a.x-g.x)-l*(a.y-g.y);if(0===e)return!0;0>e||(d=!d)}}else if(a.y===g.y&&(h.x<=a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=Xa.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);b=[];if(1===f.length){var g=f[0]; +var h=new gb;h.curves=g.curves;b.push(h);return b}var l=!e(f[0].getPoints());l=a?!l:l;h=[];var k=[],p=[],n=0;k[n]=void 0;p[n]=[];for(var t=0,r=f.length;td&&this._mixBufferRegion(c,a,3*b,1-d,b);d=b;for(var f=b+b;d!==f;++d)if(c[d]!==c[d+b]){e.setValue(c,a);break}}, +saveOriginalState:function(){var a=this.buffer,b=this.valueSize,c=3*b;this.binding.getValue(a,c);for(var d=b;d!==c;++d)a[d]=a[c+d%b];this.cumulativeWeight=0},restoreOriginalState:function(){this.binding.setValue(this.buffer,3*this.valueSize)},_select:function(a,b,c,d,e){if(.5<=d)for(d=0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d){ja.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f=1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}});Object.assign(jf.prototype,{getValue:function(a, +b){this.bind();var c=this._bindings[this._targetGroup.nCachedObjects_];void 0!==c&&c.getValue(a,b)},setValue:function(a,b){for(var c=this._bindings,d=this._targetGroup.nCachedObjects_,e=c.length;d!==e;++d)c[d].setValue(a,b)},bind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].bind()},unbind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].unbind()}});Object.assign(qa,{Composite:jf,create:function(a, +b,c){return a&&a.isAnimationObjectGroup?new qa.Composite(a,b,c):new qa(a,b,c)},sanitizeNodeName:function(){var a=/[\[\]\.:\/]/g;return function(b){return b.replace(/\s/g,"_").replace(a,"")}}(),parseTrackName:function(){var a="[^"+"\\[\\]\\.:\\/".replace("\\.","")+"]",b=/((?:WC+[\/:])*)/.source.replace("WC","[^\\[\\]\\.:\\/]");a=/(WCOD+)?/.source.replace("WCOD",a);var c=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC","[^\\[\\]\\.:\\/]"),d=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC","[^\\[\\]\\.:\\/]"), +e=new RegExp("^"+b+a+c+d+"$"),f=["material","materials","bones"];return function(a){var b=e.exec(a);if(!b)throw Error("PropertyBinding: Cannot parse trackName: "+a);b={nodeName:b[2],objectName:b[3],objectIndex:b[4],propertyName:b[5],propertyIndex:b[6]};var c=b.nodeName&&b.nodeName.lastIndexOf(".");if(void 0!==c&&-1!==c){var d=b.nodeName.substring(c+1);-1!==f.indexOf(d)&&(b.nodeName=b.nodeName.substring(0,c),b.objectName=d)}if(null===b.propertyName||0===b.propertyName.length)throw Error("PropertyBinding: can not parse propertyName from trackName: "+ +a);return b}}(),findNode:function(a,b){if(!b||""===b||"root"===b||"."===b||-1===b||b===a.name||b===a.uuid)return a;if(a.skeleton){var c=a.skeleton.getBoneByName(b);if(void 0!==c)return c}if(a.children){var d=function(a){for(var c=0;c=c){var n=c++,p=b[n];d[p.uuid]=l;b[l]=p;d[m]=n;b[n]=k;k=0;for(m=f;k!==m;++k){var p=e[k],r=p[l];p[l]=p[n];p[n]=r}}}this.nCachedObjects_=c},uncache:function(a){for(var b=this._objects,c=b.length,d=this.nCachedObjects_,e=this._indicesByUUID,f=this._bindings,g=f.length,h=0,k=arguments.length;h!==k;++h){var l=arguments[h].uuid,n=e[l]; -if(void 0!==n)if(delete e[l],nb||0===c)return;this._startTime=null;b*=c}b*=this._updateTimeScale(a);c=this._updateTime(b);a=this._updateWeight(a);if(0c.parameterPositions[1]&&(this.stopFading(),0===d&&(this.enabled=!1))}}return this._effectiveWeight=b},_updateTimeScale:function(a){var b=0;if(!this.paused){var b=this.timeScale,c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.parameterPositions[1]&&(this.stopWarping(),0===b?this.paused=!0:this.timeScale=b)}}return this._effectiveTimeScale=b},_updateTime:function(a){var b=this.time+a;if(0===a)return b;var c=this._clip.duration,d=this.loop,e=this._loopCount;if(2200=== -d)a:{if(-1===e&&(this._loopCount=0,this._setEndings(!0,!0,!1)),b>=c)b=c;else if(0>b)b=0;else break a;this.clampWhenFinished?this.paused=!0:this.enabled=!1;this._mixer.dispatchEvent({type:"finished",action:this,direction:0>a?-1:1})}else{d=2202===d;-1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions,d)):this._setEndings(0===this.repetitions,!0,d));if(b>=c||0>b){var f=Math.floor(b/c),b=b-c*f,e=e+Math.abs(f),g=this.repetitions-e;0>g?(this.clampWhenFinished?this.paused=!0:this.enabled=!1,b=0a,this._setEndings(a,!a,d)):this._setEndings(!1,!1,d),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:f}))}if(d&&1===(e&1))return this.time=b,c-b}return this.time=b},_setEndings:function(a,b,c){var d=this._interpolantSettings;c?(d.endingStart=2401,d.endingEnd=2401):(d.endingStart=a?this.zeroSlopeAtStart?2401:2400:2402,d.endingEnd=b?this.zeroSlopeAtEnd?2401:2400:2402)},_scheduleFading:function(a, -b,c){var d=this._mixer,e=d.time,f=this._weightInterpolant;null===f&&(this._weightInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;f[0]=b;d[1]=e+a;f[1]=c;return this}});Object.assign(We.prototype,xa.prototype,{_bindAction:function(a,b){var c=a._localRoot||this._root,d=a._clip.tracks,e=d.length,f=a._propertyBindings,g=a._interpolants,h=c.uuid,k=this._bindingsByRootAndName,l=k[h];void 0===l&&(l={},k[h]=l);for(k=0;k!==e;++k){var n=d[k],v=n.name,p=l[v];if(void 0=== -p){p=f[k];if(void 0!==p){null===p._cacheIndex&&(++p.referenceCount,this._addInactiveBinding(p,h,v));continue}p=new ke(ha.create(c,v,b&&b._propertyBindings[k].binding.parsedPath),n.ValueTypeName,n.getValueSize());++p.referenceCount;this._addInactiveBinding(p,h,v)}f[k]=p;g[k].resultBuffer=p.buffer}},_activateAction:function(a){if(!this._isActiveAction(a)){if(null===a._cacheIndex){var b=(a._localRoot||this._root).uuid,c=a._clip.uuid,d=this._actionsByClip[c];this._bindAction(a,d&&d.knownActions[0]);this._addInactiveAction(a, -c,b)}b=a._propertyBindings;c=0;for(d=b.length;c!==d;++c){var e=b[c];0===e.useCount++&&(this._lendBinding(e),e.saveOriginalState())}this._lendAction(a)}},_deactivateAction:function(a){if(this._isActiveAction(a)){for(var b=a._propertyBindings,c=0,d=b.length;c!==d;++c){var e=b[c];0===--e.useCount&&(e.restoreOriginalState(),this._takeBackBinding(e))}this._takeBackAction(a)}},_initMemoryManager:function(){this._actions=[];this._nActiveActions=0;this._actionsByClip={};this._bindings=[];this._nActiveBindings= -0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var a=this;this.stats={actions:{get total(){return a._actions.length},get inUse(){return a._nActiveActions}},bindings:{get total(){return a._bindings.length},get inUse(){return a._nActiveBindings}},controlInterpolants:{get total(){return a._controlInterpolants.length},get inUse(){return a._nActiveControlInterpolants}}}},_isActiveAction:function(a){a=a._cacheIndex;return null!==a&&a=b){var p=b++,n=a[p];c[n.uuid]=m;a[m]=n;c[k]=p;a[p]=h;h=0;for(k=e;h!==k;++h){n=d[h];var t=n[m];n[m]=n[p];n[p]=t}}}this.nCachedObjects_=b},uncache:function(){for(var a=this._objects,b=a.length,c=this.nCachedObjects_,d=this._indicesByUUID,e=this._bindings,f=e.length,g=0,h=arguments.length;g!==h;++g){var k= +arguments[g].uuid,m=d[k];if(void 0!==m)if(delete d[k],mb||0===c)return;this._startTime=null;b*=c}b*=this._updateTimeScale(a);c=this._updateTime(b);a=this._updateWeight(a);if(0c.parameterPositions[1]&&(this.stopFading(),0===d&&(this.enabled=!1))}}return this._effectiveWeight=b},_updateTimeScale:function(a){var b=0;if(!this.paused){b=this.timeScale;var c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0];b*=d;a>c.parameterPositions[1]&&(this.stopWarping(),0===b?this.paused=!0:this.timeScale=b)}}return this._effectiveTimeScale=b},_updateTime:function(a){var b=this.time+a;if(0===a)return b;var c=this._clip.duration,d=this.loop,e=this._loopCount;if(2200=== +d)a:{if(-1===e&&(this._loopCount=0,this._setEndings(!0,!0,!1)),b>=c)b=c;else if(0>b)b=0;else break a;this.clampWhenFinished?this.paused=!0:this.enabled=!1;this._mixer.dispatchEvent({type:"finished",action:this,direction:0>a?-1:1})}else{d=2202===d;-1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions,d)):this._setEndings(0===this.repetitions,!0,d));if(b>=c||0>b){var f=Math.floor(b/c);b-=c*f;e+=Math.abs(f);var g=this.repetitions-e;0>=g?(this.clampWhenFinished?this.paused=!0:this.enabled=!1,b= +0a,this._setEndings(a,!a,d)):this._setEndings(!1,!1,d),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:f}))}if(d&&1===(e&1))return this.time=b,c-b}return this.time=b},_setEndings:function(a,b,c){var d=this._interpolantSettings;c?(d.endingStart=2401,d.endingEnd=2401):(d.endingStart=a?this.zeroSlopeAtStart?2401:2400:2402,d.endingEnd=b?this.zeroSlopeAtEnd?2401:2400:2402)},_scheduleFading:function(a, +b,c){var d=this._mixer,e=d.time,f=this._weightInterpolant;null===f&&(this._weightInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;f[0]=b;d[1]=e+a;f[1]=c;return this}});pe.prototype=Object.assign(Object.create(xa.prototype),{constructor:pe,_bindAction:function(a,b){var c=a._localRoot||this._root,d=a._clip.tracks,e=d.length,f=a._propertyBindings;a=a._interpolants;var g=c.uuid,h=this._bindingsByRootAndName,k=h[g];void 0===k&&(k={},h[g]=k);for(h=0;h!==e;++h){var m= +d[h],p=m.name,n=k[p];if(void 0===n){n=f[h];if(void 0!==n){null===n._cacheIndex&&(++n.referenceCount,this._addInactiveBinding(n,g,p));continue}n=new oe(qa.create(c,p,b&&b._propertyBindings[h].binding.parsedPath),m.ValueTypeName,m.getValueSize());++n.referenceCount;this._addInactiveBinding(n,g,p)}f[h]=n;a[h].resultBuffer=n.buffer}},_activateAction:function(a){if(!this._isActiveAction(a)){if(null===a._cacheIndex){var b=(a._localRoot||this._root).uuid,c=a._clip.uuid,d=this._actionsByClip[c];this._bindAction(a, +d&&d.knownActions[0]);this._addInactiveAction(a,c,b)}b=a._propertyBindings;c=0;for(d=b.length;c!==d;++c){var e=b[c];0===e.useCount++&&(this._lendBinding(e),e.saveOriginalState())}this._lendAction(a)}},_deactivateAction:function(a){if(this._isActiveAction(a)){for(var b=a._propertyBindings,c=0,d=b.length;c!==d;++c){var e=b[c];0===--e.useCount&&(e.restoreOriginalState(),this._takeBackBinding(e))}this._takeBackAction(a)}},_initMemoryManager:function(){this._actions=[];this._nActiveActions=0;this._actionsByClip= +{};this._bindings=[];this._nActiveBindings=0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var a=this;this.stats={actions:{get total(){return a._actions.length},get inUse(){return a._nActiveActions}},bindings:{get total(){return a._bindings.length},get inUse(){return a._nActiveBindings}},controlInterpolants:{get total(){return a._controlInterpolants.length},get inUse(){return a._nActiveControlInterpolants}}}},_isActiveAction:function(a){a=a._cacheIndex; +return null!==a&&ah.end&&(h.end=f);c||(c=k)}}for(k in d)h=d[k],this.createAnimation(k,h.start,h.end,a);this.firstAnimation=c};ta.prototype.setAnimationDirectionForward=function(a){if(a=this.animationsMap[a])a.direction=1,a.directionBackwards=!1};ta.prototype.setAnimationDirectionBackward=function(a){if(a=this.animationsMap[a])a.direction=-1,a.directionBackwards=!0};ta.prototype.setAnimationFPS= -function(a,b){var c=this.animationsMap[a];c&&(c.fps=b,c.duration=(c.end-c.start)/c.fps)};ta.prototype.setAnimationDuration=function(a,b){var c=this.animationsMap[a];c&&(c.duration=b,c.fps=(c.end-c.start)/c.duration)};ta.prototype.setAnimationWeight=function(a,b){var c=this.animationsMap[a];c&&(c.weight=b)};ta.prototype.setAnimationTime=function(a,b){var c=this.animationsMap[a];c&&(c.time=b)};ta.prototype.getAnimationTime=function(a){var b=0;if(a=this.animationsMap[a])b=a.time;return b};ta.prototype.getAnimationDuration= -function(a){var b=-1;if(a=this.animationsMap[a])b=a.duration;return b};ta.prototype.playAnimation=function(a){var b=this.animationsMap[a];b?(b.time=0,b.active=!0):console.warn("THREE.MorphBlendMesh: animation["+a+"] undefined in .playAnimation()")};ta.prototype.stopAnimation=function(a){if(a=this.animationsMap[a])a.active=!1};ta.prototype.update=function(a){for(var b=0,c=this.animationsList.length;b -d.duration||0>d.time)d.direction*=-1,d.time>d.duration&&(d.time=d.duration,d.directionBackwards=!0),0>d.time&&(d.time=0,d.directionBackwards=!1)}else d.time%=d.duration,0>d.time&&(d.time+=d.duration);var f=d.start+Y.clamp(Math.floor(d.time/e),0,d.length-1),g=d.weight;f!==d.currentFrame&&(this.morphTargetInfluences[d.lastFrame]=0,this.morphTargetInfluences[d.currentFrame]=1*g,this.morphTargetInfluences[f]=0,d.lastFrame=d.currentFrame,d.currentFrame=f);e=d.time%e/e;d.directionBackwards&&(e=1-e);d.currentFrame!== -d.lastFrame?(this.morphTargetInfluences[d.currentFrame]=e*g,this.morphTargetInfluences[d.lastFrame]=(1-e)*g):this.morphTargetInfluences[d.currentFrame]=g}}};Xc.prototype=Object.create(z.prototype);Xc.prototype.constructor=Xc;Xc.prototype.isImmediateRenderObject=!0;Yc.prototype=Object.create(Q.prototype);Yc.prototype.constructor=Yc;Yc.prototype.update=function(){var a=new n,b=new n,c=new Ba;return function(){var d=["a","b","c"];this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld); -var e=this.object.matrixWorld,f=this.geometry.attributes.position,g=this.object.geometry;if(g&&g.isGeometry)for(var h=g.vertices,k=g.faces,l=g=0,n=k.length;lc.y?this.quaternion.set(1,0,0,0):(a.set(c.z,0,-c.x).normalize(),b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a, -b))}}();Bb.prototype.setLength=function(a,b,c){void 0===b&&(b=.2*a);void 0===c&&(c=.2*b);this.line.scale.set(1,Math.max(0,a-b),1);this.line.updateMatrix();this.cone.scale.set(c,b,c);this.cone.position.y=a;this.cone.updateMatrix()};Bb.prototype.setColor=function(a){this.line.material.color.copy(a);this.cone.material.color.copy(a)};Ld.prototype=Object.create(Q.prototype);Ld.prototype.constructor=Ld;var Od=new n,ue=new re,ve=new re,we=new re;La.prototype=Object.create(ua.prototype);La.prototype.constructor= -La;La.prototype.getPoint=function(a){var b=this.points,c=b.length;a*=c-(this.closed?0:1);var d=Math.floor(a);a-=d;this.closed?d+=0d&&(d=1);1E-4>c&&(c=d);1E-4>h&&(h=d);ue.initNonuniformCatmullRom(e.x,f.x,g.x,b.x,c,d,h);ve.initNonuniformCatmullRom(e.y,f.y,g.y,b.y,c,d,h);we.initNonuniformCatmullRom(e.z,f.z,g.z,b.z,c,d,h)}else"catmullrom"===this.type&&(c=void 0!==this.tension?this.tension:.5,ue.initCatmullRom(e.x,f.x,g.x,b.x,c),ve.initCatmullRom(e.y,f.y,g.y,b.y,c),we.initCatmullRom(e.z,f.z,g.z,b.z,c));return new n(ue.calc(a), -ve.calc(a),we.calc(a))};bd.prototype=Object.create(ua.prototype);bd.prototype.constructor=bd;bd.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2,e=this.v3;return new n(xb(a,b.x,c.x,d.x,e.x),xb(a,b.y,c.y,d.y,e.y),xb(a,b.z,c.z,d.z,e.z))};cd.prototype=Object.create(ua.prototype);cd.prototype.constructor=cd;cd.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2;return new n(wb(a,b.x,c.x,d.x),wb(a,b.y,c.y,d.y),wb(a,b.z,c.z,d.z))};dd.prototype=Object.create(ua.prototype);dd.prototype.constructor= -dd;dd.prototype.getPoint=function(a){if(1===a)return this.v2.clone();var b=new n;b.subVectors(this.v2,this.v1);b.multiplyScalar(a);b.add(this.v1);return b};Md.prototype=Object.create(Va.prototype);Md.prototype.constructor=Md;ua.create=function(a,b){console.log("THREE.Curve.create() has been deprecated");a.prototype=Object.create(ua.prototype);a.prototype.constructor=a;a.prototype.getPoint=b;return a};cf.prototype=Object.create(La.prototype);df.prototype=Object.create(La.prototype);se.prototype=Object.create(La.prototype); -Object.assign(se.prototype,{initFromArray:function(a){console.error("THREE.Spline: .initFromArray() has been removed.")},getControlPointsArray:function(a){console.error("THREE.Spline: .getControlPointsArray() has been removed.")},reparametrizeByArcLength:function(a){console.error("THREE.Spline: .reparametrizeByArcLength() has been removed.")}});Zc.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")};kc.prototype.update= -function(){console.error("THREE.SkeletonHelper: update() no longer needs to be called.")};Object.assign(fd.prototype,{center:function(a){console.warn("THREE.Box2: .center() has been renamed to .getCenter().");return this.getCenter(a)},empty:function(){console.warn("THREE.Box2: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},size:function(a){console.warn("THREE.Box2: .size() has been renamed to .getSize()."); -return this.getSize(a)}});Object.assign(Ra.prototype,{center:function(a){console.warn("THREE.Box3: .center() has been renamed to .getCenter().");return this.getCenter(a)},empty:function(){console.warn("THREE.Box3: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionSphere:function(a){console.warn("THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere()."); -return this.intersectsSphere(a)},size:function(a){console.warn("THREE.Box3: .size() has been renamed to .getSize().");return this.getSize(a)}});Hb.prototype.center=function(a){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");return this.getCenter(a)};Y.random16=function(){console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead.");return Math.random()};Object.assign(Ba.prototype,{flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead."); -return this.toArray(a,b)},multiplyVector3:function(a){console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.");return a.applyMatrix3(this)},multiplyVector3Array:function(a){console.error("THREE.Matrix3: .multiplyVector3Array() has been removed.")},applyToBuffer:function(a,b,c){console.warn("THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");return this.applyToBufferAttribute(a)},applyToVector3Array:function(a, -b,c){console.error("THREE.Matrix3: .applyToVector3Array() has been removed.")}});Object.assign(K.prototype,{extractPosition:function(a){console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().");return this.copyPosition(a)},flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},getPosition:function(){var a;return function(){void 0===a&&(a=new n);console.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead."); -return a.setFromMatrixColumn(this,3)}}(),setRotationFromQuaternion:function(a){console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().");return this.makeRotationFromQuaternion(a)},multiplyToArray:function(){console.warn("THREE.Matrix4: .multiplyToArray() has been removed.")},multiplyVector3:function(a){console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.");return a.applyMatrix4(this)},multiplyVector4:function(a){console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead."); -return a.applyMatrix4(this)},multiplyVector3Array:function(a){console.error("THREE.Matrix4: .multiplyVector3Array() has been removed.")},rotateAxis:function(a){console.warn("THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.");a.transformDirection(this)},crossVector:function(a){console.warn("THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.");return a.applyMatrix4(this)},translate:function(){console.error("THREE.Matrix4: .translate() has been removed.")}, -rotateX:function(){console.error("THREE.Matrix4: .rotateX() has been removed.")},rotateY:function(){console.error("THREE.Matrix4: .rotateY() has been removed.")},rotateZ:function(){console.error("THREE.Matrix4: .rotateZ() has been removed.")},rotateByAxis:function(){console.error("THREE.Matrix4: .rotateByAxis() has been removed.")},applyToBuffer:function(a,b,c){console.warn("THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");return this.applyToBufferAttribute(a)}, -applyToVector3Array:function(a,b,c){console.error("THREE.Matrix4: .applyToVector3Array() has been removed.")},makeFrustum:function(a,b,c,d,e,f){console.warn("THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.");return this.makePerspective(a,b,d,c,e,f)}});Aa.prototype.isIntersectionLine=function(a){console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().");return this.intersectsLine(a)};oa.prototype.multiplyVector3= -function(a){console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.");return a.applyQuaternion(this)};Object.assign(kb.prototype,{isIntersectionBox:function(a){console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionPlane:function(a){console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().");return this.intersectsPlane(a)},isIntersectionSphere:function(a){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere()."); -return this.intersectsSphere(a)}});Object.assign(zb.prototype,{extrude:function(a){console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.");return new cb(this,a)},makeGeometry:function(a){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");return new Xb(this,a)}});Object.assign(C.prototype,{fromAttribute:function(a,b,c){console.error("THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a, -b,c)}});Object.assign(n.prototype,{setEulerFromRotationMatrix:function(){console.error("THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.")},setEulerFromQuaternion:function(){console.error("THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.")},getPositionFromMatrix:function(a){console.warn("THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().");return this.setFromMatrixPosition(a)}, -getScaleFromMatrix:function(a){console.warn("THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().");return this.setFromMatrixScale(a)},getColumnFromMatrix:function(a,b){console.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().");return this.setFromMatrixColumn(b,a)},applyProjection:function(a){console.warn("THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.");return this.applyMatrix4(a)},fromAttribute:function(a, -b,c){console.error("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)}});Object.assign(fa.prototype,{fromAttribute:function(a,b,c){console.error("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)}});J.prototype.computeTangents=function(){console.warn("THREE.Geometry: .computeTangents() has been removed.")};Object.assign(z.prototype,{getChildByName:function(a){console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName()."); -return this.getObjectByName(a)},renderDepth:function(){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.")},translate:function(a,b){console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.");return this.translateOnAxis(b,a)}});Object.defineProperties(z.prototype,{eulerOrder:{get:function(){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");return this.rotation.order},set:function(a){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order."); -this.rotation.order=a}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}});Object.defineProperties(yc.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Object.defineProperty(zc.prototype,"useVertexTexture",{get:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")}, -set:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")}});Object.defineProperty(ua.prototype,"__arcLengthDivisions",{get:function(){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");return this.arcLengthDivisions},set:function(a){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");this.arcLengthDivisions=a}});qa.prototype.setLens=function(a,b){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup."); -void 0!==b&&(this.filmGauge=b);this.setFocalLength(a)};Object.defineProperties(na.prototype,{onlyShadow:{set:function(){console.warn("THREE.Light: .onlyShadow has been removed.")}},shadowCameraFov:{set:function(a){console.warn("THREE.Light: .shadowCameraFov is now .shadow.camera.fov.");this.shadow.camera.fov=a}},shadowCameraLeft:{set:function(a){console.warn("THREE.Light: .shadowCameraLeft is now .shadow.camera.left.");this.shadow.camera.left=a}},shadowCameraRight:{set:function(a){console.warn("THREE.Light: .shadowCameraRight is now .shadow.camera.right."); -this.shadow.camera.right=a}},shadowCameraTop:{set:function(a){console.warn("THREE.Light: .shadowCameraTop is now .shadow.camera.top.");this.shadow.camera.top=a}},shadowCameraBottom:{set:function(a){console.warn("THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.");this.shadow.camera.bottom=a}},shadowCameraNear:{set:function(a){console.warn("THREE.Light: .shadowCameraNear is now .shadow.camera.near.");this.shadow.camera.near=a}},shadowCameraFar:{set:function(a){console.warn("THREE.Light: .shadowCameraFar is now .shadow.camera.far."); -this.shadow.camera.far=a}},shadowCameraVisible:{set:function(){console.warn("THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.")}},shadowBias:{set:function(a){console.warn("THREE.Light: .shadowBias is now .shadow.bias.");this.shadow.bias=a}},shadowDarkness:{set:function(){console.warn("THREE.Light: .shadowDarkness has been removed.")}},shadowMapWidth:{set:function(a){console.warn("THREE.Light: .shadowMapWidth is now .shadow.mapSize.width."); -this.shadow.mapSize.width=a}},shadowMapHeight:{set:function(a){console.warn("THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.");this.shadow.mapSize.height=a}}});Object.defineProperties(Z.prototype,{length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead.");return this.array.length}}});Object.assign(E.prototype,{addIndex:function(a){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().");this.setIndex(a)},addDrawCall:function(a, -b,c){void 0!==c&&console.warn("THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.");console.warn("THREE.BufferGeometry: .addDrawCall() is now .addGroup().");this.addGroup(a,b)},clearDrawCalls:function(){console.warn("THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().");this.clearGroups()},computeTangents:function(){console.warn("THREE.BufferGeometry: .computeTangents() has been removed.")},computeOffsets:function(){console.warn("THREE.BufferGeometry: .computeOffsets() has been removed.")}}); -Object.defineProperties(E.prototype,{drawcalls:{get:function(){console.error("THREE.BufferGeometry: .drawcalls has been renamed to .groups.");return this.groups}},offsets:{get:function(){console.warn("THREE.BufferGeometry: .offsets has been renamed to .groups.");return this.groups}}});Object.defineProperties(Id.prototype,{dynamic:{set:function(){console.warn("THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.")}},onUpdate:{value:function(){console.warn("THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead."); -return this}}});Object.defineProperties(U.prototype,{wrapAround:{get:function(){console.warn("THREE.Material: .wrapAround has been removed.")},set:function(){console.warn("THREE.Material: .wrapAround has been removed.")}},wrapRGB:{get:function(){console.warn("THREE.Material: .wrapRGB has been removed.");return new G}}});Object.defineProperties(Ja.prototype,{metal:{get:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.");return!1},set:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead")}}}); -Object.defineProperties(ra.prototype,{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");return this.extensions.derivatives},set:function(a){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=a}}});Object.assign(Xd.prototype,{getCurrentRenderTarget:function(){console.warn("THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().");return this.getRenderTarget()}, -supportsFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' ).");return this.extensions.get("OES_texture_float")},supportsHalfFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( 'OES_texture_half_float' ).");return this.extensions.get("OES_texture_half_float")},supportsStandardDerivatives:function(){console.warn("THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( 'OES_standard_derivatives' )."); +a;return this}});se.prototype=Object.assign(Object.create(kc.prototype),{constructor:se,isInstancedInterleavedBuffer:!0,copy:function(a){kc.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});te.prototype=Object.assign(Object.create(T.prototype),{constructor:te,isInstancedBufferAttribute:!0,copy:function(a){T.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});Object.assign(mf.prototype,{linePrecision:1,set:function(a,b){this.ray.set(a, +b)},setFromCamera:function(a,b){b&&b.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(b.matrixWorld),this.ray.direction.set(a.x,a.y,.5).unproject(b).sub(this.ray.origin).normalize()):b&&b.isOrthographicCamera?(this.ray.origin.set(a.x,a.y,(b.near+b.far)/(b.near-b.far)).unproject(b),this.ray.direction.set(0,0,-1).transformDirection(b.matrixWorld)):console.error("THREE.Raycaster: Unsupported camera type.")},intersectObject:function(a,b,c){c=c||[];ue(a,this,c,b);c.sort(nf);return c},intersectObjects:function(a, +b,c){c=c||[];if(!1===Array.isArray(a))return console.warn("THREE.Raycaster.intersectObjects: objects is not an Array."),c;for(var d=0,e=a.length;dthis.max.x||a.ythis.max.y?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y},getParameter:function(a, +b){void 0===b&&(console.warn("THREE.Box2: .getParameter() target is now required"),b=new C);return b.set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(a){return a.max.xthis.max.x||a.max.ythis.max.y?!1:!0},clampPoint:function(a,b){void 0===b&&(console.warn("THREE.Box2: .clampPoint() target is now required"),b=new C);return b.copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new C; +return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});dd.prototype=Object.create(A.prototype);dd.prototype.constructor=dd;dd.prototype.isImmediateRenderObject=!0;ed.prototype=Object.create(aa.prototype); +ed.prototype.constructor=ed;ed.prototype.update=function(){var a=new p,b=new p,c=new sa;return function(){var d=["a","b","c"];this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);var e=this.object.matrixWorld,f=this.geometry.attributes.position,g=this.object.geometry;if(g&&g.isGeometry)for(var h=g.vertices,k=g.faces,m=g=0,p=k.length;mMath.abs(b)&&(b=1E-8);this.scale.set(.5*this.size,.5*this.size,b);this.lookAt(this.plane.normal);A.prototype.updateMatrixWorld.call(this,a)};var Pd,we;Gb.prototype=Object.create(A.prototype);Gb.prototype.constructor=Gb;Gb.prototype.setDirection=function(){var a= +new p,b;return function(c){.99999c.y?this.quaternion.set(1,0,0,0):(a.set(c.z,0,-c.x).normalize(),b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a,b))}}();Gb.prototype.setLength=function(a,b,c){void 0===b&&(b=.2*a);void 0===c&&(c=.2*b);this.line.scale.set(1,Math.max(0,a-b),1);this.line.updateMatrix();this.cone.scale.set(c,b,c);this.cone.position.y=a;this.cone.updateMatrix()};Gb.prototype.setColor=function(a){this.line.material.color.copy(a);this.cone.material.color.copy(a)}; +kd.prototype=Object.create(aa.prototype);kd.prototype.constructor=kd;E.create=function(a,b){console.log("THREE.Curve.create() has been deprecated");a.prototype=Object.create(E.prototype);a.prototype.constructor=a;a.prototype.getPoint=b;return a};Object.assign(Za.prototype,{createPointsGeometry:function(a){console.warn("THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");a=this.getPoints(a);return this.createGeometry(a)},createSpacedPointsGeometry:function(a){console.warn("THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead."); +a=this.getSpacedPoints(a);return this.createGeometry(a)},createGeometry:function(a){console.warn("THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");for(var b=new N,c=0,d=a.length;c