text: // xg - http://alteredqualia.com/xg
  function getHttpRequest(e,t,a){var r={load:function(e){t(i,e)},progress:function(e){a(i,e)}},i=new XMLHttpRequest;addListeners(i,r),i.open("GET",e,!0),i.send(null)}function getJsonRequest(e,t){getHttpRequest(e,function(e){t(JSON.parse(e.responseText))},function(){})}function addListeners(e,t){for(var a in t)e.addEventListener(a,t[a])}var XG=XG||{VERSION:"0"};XG.elementIndexUintAvailable=!1,XG.CullFaceNone=0,XG.CullFaceBack=1,XG.CullFaceFront=2,XG.CullFaceFrontBack=3,XG.FrontFaceDirectionCW=0,XG.FrontFaceDirectionCCW=1,XG.BasicShadowMap=0,XG.PCFSoftShadowMap=1,XG.PCFSoftHQShadowMap=2,XG.FrontSide=0,XG.BackSide=1,XG.DoubleSide=2,XG.NoBlending=0,XG.NormalBlending=1,XG.AdditiveBlending=2,XG.SubtractiveBlending=3,XG.MultiplyBlending=4,XG.CustomBlending=5,XG.AddEquation=32774,XG.SubtractEquation=32778,XG.ReverseSubtractEquation=32779,XG.ZeroFactor=0,XG.OneFactor=1,XG.SrcColorFactor=768,XG.OneMinusSrcColorFactor=769,XG.SrcAlphaFactor=770,XG.OneMinusSrcAlphaFactor=771,XG.DstAlphaFactor=772,XG.OneMinusDstAlphaFactor=773,XG.DstColorFactor=774,XG.OneMinusDstColorFactor=775,XG.SrcAlphaSaturateFactor=776,XG.MultiplyOperation=0,XG.MixOperation=1,XG.AddOperation=2,XG.RepeatWrapping=10497,XG.ClampToEdgeWrapping=33071,XG.MirroredRepeatWrapping=33648,XG.NearestFilter=9728,XG.LinearFilter=9729,XG.NearestMipMapNearestFilter=9984,XG.LinearMipMapNearestFilter=9985,XG.NearestMipMapLinearFilter=9986,XG.LinearMipMapLinearFilter=9987,XG.ByteType=5120,XG.UnsignedByteType=5121,XG.ShortType=5122,XG.UnsignedShortType=5123,XG.IntType=5124,XG.UnsignedIntType=5125,XG.FloatType=5126,XG.HalfFloatType2=5131,XG.HalfFloatType1=36193,XG.UnsignedShort4444Type=32819,XG.UnsignedShort5551Type=32820,XG.UnsignedShort565Type=33635,XG.DepthComponentFormat=6402,XG.AlphaFormat=6406,XG.RGBFormat=6407,XG.RGBAFormat=6408,XG.LuminanceFormat=6409,XG.LuminanceAlphaFormat=6410,XG.RED=6403,XG.RGB8=32849,XG.RGBA8=32856,XG.RGB10_A2=32857,XG.UNSIGNED_INT_2_10_10_10_REV=33640,XG.DEPTH_COMPONENT24=33190,XG.SRGB=35904,XG.SRGB8=35905,XG.SRGB8_ALPHA8=35907,XG.RGBA32F=34836,XG.RGB32F=34837,XG.RGBA16F=34842,XG.RGB16F=34843,XG.R11F_G11F_B10F=35898,XG.UNSIGNED_INT_10F_11F_11F_REV=35899,XG.RGB9_E5=35901,XG.UNSIGNED_INT_5_9_9_9_REV=35902,XG.RGBA32UI=36208,XG.RGB32UI=36209,XG.RGBA16UI=36214,XG.RGB16UI=36215,XG.RGBA8UI=36220,XG.RGB8UI=36221,XG.RGBA32I=36226,XG.RGB32I=36227,XG.RGBA16I=36232,XG.RGB16I=36233,XG.RGBA8I=36238,XG.RGB8I=36239,XG.RED_INTEGER=36244,XG.RGB_INTEGER=36248,XG.RGBA_INTEGER=36249,XG.DEPTH_COMPONENT32F=36012,XG.DEPTH32F_STENCIL8=36013,XG.FLOAT_32_UNSIGNED_INT_24_8_REV=36269,XG.UNSIGNED_INT_24_8=34042,XG.DEPTH24_STENCIL8=35056,XG.RG=33319,XG.RG_INTEGER=33320,XG.R8=33321,XG.RG8=33323,XG.R16F=33325,XG.R32F=33326,XG.RG16F=33327,XG.RG32F=33328,XG.R8I=33329,XG.R8UI=33330,XG.R16I=33331,XG.R16UI=33332,XG.R32I=33333,XG.R32UI=33334,XG.RG8I=33335,XG.RG8UI=33336,XG.RG16I=33337,XG.RG16UI=33338,XG.RG32I=33339,XG.RG32UI=33340,XG.RGB_S3TC_DXT1_Format=33776,XG.RGBA_S3TC_DXT1_Format=33777,XG.RGBA_S3TC_DXT3_Format=33778,XG.RGBA_S3TC_DXT5_Format=33779,XG.RGB_PVRTC_4BPPV1_Format=35840,XG.RGB_PVRTC_2BPPV1_Format=35841,XG.RGBA_PVRTC_4BPPV1_Format=35842,XG.RGBA_PVRTC_2BPPV1_Format=35843,XG.RGB_ETC1_Format=36196,XG.RGB_ATC_Format=35986,XG.RGBA_ATC_EXPLICIT_ALPHA_Format=35987,XG.RGBA_ATC_INTERPOLATED_ALPHA_Format=34798,XG.NoOperator=0,XG.SimpleOperator=1,XG.LinearOperator=2,XG.ReinhardOperator=3,XG.FilmicOperator=4,XG.Filmic2015Operator=5,XG.UnchartedOperator=6,XG.LumaReinhardOperator=7,XG.WhitePreservingReinhardOperator=8,XG.PhotographicOperator=9,XG.SimpleBRDF=0,XG.BlinnPhongBRDF=1,XG.GGXBRDF=2,XG.xyzOrder=0,XG.yxzOrder=1,XG.zxyOrder=2,XG.zyxOrder=3,XG.yzxOrder=4,XG.xzyOrder=5,XG.DisplaceByNormal=0,XG.DisplaceByPosition=1,XG.paramTypedArrayToXG=function(e){var t;return e instanceof Float32Array?t=XG.FloatType:e instanceof Uint32Array?t=XG.UnsignedIntType:e instanceof Uint16Array?t=XG.UnsignedShortType:e instanceof Uint8Array?t=XG.UnsignedByteType:e instanceof Int32Array?t=XG.IntType:e instanceof Int16Array?t=XG.ShortType:e instanceof Int8Array&&(t=XG.ByteType),t},XG.paramXGToTypedArray=function(e){var t;return e===XG.FloatType?t=Float32Array:e===XG.UnsignedIntType?t=Uint32Array:e===XG.UnsignedShortType?t=Uint16Array:e===XG.UnsignedByteType?t=Uint8Array:e===XG.IntType?t=Int32Array:e===XG.ShortType?t=Int16Array:e===XG.ByteType&&(t=Int8Array),t},XG.Projector=function(){var e=new XG.Matrix4;this.projectVector=function(t,a){return a.matrixWorldInverse.getInverse(a.matrixWorld),e.multiply(a.projectionMatrix,a.matrixWorldInverse),e.multiplyVector3(t),t},this.unprojectVector=function(t,a){return a.projectionMatrixInverse.getInverse(a.projectionMatrix),e.multiply(a.matrixWorld,a.projectionMatrixInverse),e.multiplyVector3(t),t}},XG.Color=function(e){return void 0!==e&&this.set(e),this},XG.Color.prototype={constructor:XG.Color,r:1,g:1,b:1,copy:function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this},copyGammaToLinear:function(e){return this.r=e.r*e.r,this.g=e.g*e.g,this.b=e.b*e.b,this},copyLinearToGamma:function(e){return this.r=Math.sqrt(e.r),this.g=Math.sqrt(e.g),this.b=Math.sqrt(e.b),this},copyTonemapped:function(e,t,a,r){function i(e){return(e*(o*e+s*n)+l*h)/(e*(o*e+n)+l*d)-h/d}var o=.15,n=.5,s=.1,l=.2,h=.02,d=.3,c=11.2,u=1/2.2;switch(this.r=e.r*a,this.g=e.g*a,this.b=e.b*a,t){case XG.SimpleOperator:this.r=Math.sqrt(this.r),this.g=Math.sqrt(this.g),this.b=Math.sqrt(this.b);break;case XG.LinearOperator:this.r=Math.pow(this.r,u),this.g=Math.pow(this.g,u),this.b=Math.pow(this.b,u);break;case XG.ReinhardOperator:this.r=this.r/(1+this.r),this.g=this.g/(1+this.g),this.b=this.b/(1+this.b),this.r=Math.pow(this.r,u),this.g=Math.pow(this.g,u),this.b=Math.pow(this.b,u);break;case XG.FilmicOperator:var f=Math.max(0,this.r-.004),p=Math.max(0,this.g-.004),m=Math.max(0,this.b-.004);this.r=f*(6.2*f+.5)/(f*(6.2*f+1.7)+.06),this.g=p*(6.2*p+.5)/(p*(6.2*p+1.7)+.06),this.b=m*(6.2*m+.5)/(m*(6.2*m+1.7)+.06);break;case XG.Filmic2015Operator:var v=this.r,g=this.g,S=this.b,G=r,x=1.425*v+.05,M=1.425*g+.05,y=1.425*S+.05,X=1.425*G+.05,D=(v*x+.004)/(v*(x+.55)+.0491)-.0821,_=(g*M+.004)/(g*(M+.55)+.0491)-.0821,w=(S*y+.004)/(S*(y+.55)+.0491)-.0821,A=(G*X+.004)/(G*(X+.55)+.0491)-.0821;this.r=D/A,this.g=_/A,this.b=w/A,this.r=Math.pow(this.r,u),this.g=Math.pow(this.g,u),this.b=Math.pow(this.b,u);break;case XG.UnchartedOperator:var C=2,T=i(C*this.r),b=i(C*this.g),P=i(C*this.b),L=1/i(c*r);this.r=T*L,this.g=b*L,this.b=P*L,this.r=Math.pow(this.r,u),this.g=Math.pow(this.g,u),this.b=Math.pow(this.b,u)}return this},convertGammaToLinear:function(){var e=this.r,t=this.g,a=this.b;return this.r=e*e,this.g=t*t,this.b=a*a,this},convertLinearToGamma:function(){return this.r=Math.sqrt(this.r),this.g=Math.sqrt(this.g),this.b=Math.sqrt(this.b),this},set:function(e){switch(typeof e){case"number":this.setHex(e);break;case"string":this.setStyle(e)}},setRGB:function(e,t,a){return this.r=e,this.g=t,this.b=a,this},setHSV:function(e,t,a){var r,i,o,n,s;return 0===a?this.r=this.g=this.b=0:(r=Math.floor(6*e),i=6*e-r,o=a*(1-t),n=a*(1-t*i),s=a*(1-t*(1-i)),0===r?(this.r=a,this.g=s,this.b=o):1===r?(this.r=n,this.g=a,this.b=o):2===r?(this.r=o,this.g=a,this.b=s):3===r?(this.r=o,this.g=n,this.b=a):4===r?(this.r=s,this.g=o,this.b=a):5===r&&(this.r=a,this.g=o,this.b=n)),this},adjustHSV:function(e,t,a){var r=XG.__hsv;this.getHSV(r),r.h=XG.Math.clamp(r.h+e,0,1),r.s=XG.Math.clamp(r.s+t,0,1),r.v=XG.Math.clamp(r.v+a,0,1),this.setHSV(r.h,r.s,r.v)},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},setHex:function(e){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,this},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getStyle:function(){return"rgb("+(255*this.r|0)+","+(255*this.g|0)+","+(255*this.b|0)+")"},setStyle:function(e){if(/^rgb\((\d+),(\d+),(\d+)\)$/i.test(e)){var t=/^rgb\((\d+),(\d+),(\d+)\)$/i.exec(e);return this.r=Math.min(255,parseInt(t[1],10))/255,this.g=Math.min(255,parseInt(t[2],10))/255,this.b=Math.min(255,parseInt(t[3],10))/255,this}if(/^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test(e)){var t=/^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec(e);return this.r=Math.min(100,parseInt(t[1],10))/100,this.g=Math.min(100,parseInt(t[2],10))/100,this.b=Math.min(100,parseInt(t[3],10))/100,this}if(/^\#([0-9a-f]{6})$/i.test(e)){var t=/^\#([0-9a-f]{6})$/i.exec(e);return this.setHex(parseInt(t[1],16)),this}if(/^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test(e)){var t=/^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(e);return this.setHex(parseInt(t[1]+t[1]+t[2]+t[2]+t[3]+t[3],16)),this}return/^(\w+)$/i.test(e)?(this.setHex(XG.ColorKeywords[e]),this):void 0},getHSV:function(e){var t,a,r=this.r,i=this.g,o=this.b,n=Math.max(Math.max(r,i),o),s=Math.min(Math.min(r,i),o),l=n;if(s===n)t=0,a=0;else{var h=n-s;a=h/n,t=r===n?(i-o)/h:i===n?2+(o-r)/h:4+(r-i)/h,t/=6,0>t&&(t+=1),t>1&&(t-=1)}return void 0===e&&(e={h:0,s:0,v:0}),e.h=t,e.s=a,e.v=l,e},copyIntoArray:function(e,t){void 0===t&&(t=0),e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b},lerpSelf:function(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this},clone:function(){return(new XG.Color).setRGB(this.r,this.g,this.b)}},XG.ColorKeywords={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},XG.__hsv={h:0,s:0,v:0},XG.Math={clamp:function(e,t,a){return t>e?t:e>a?a:e},clampBottom:function(e,t){return t>e?t:e},mapLinear:function(e,t,a,r,i){return r+(e-t)*(i-r)/(a-t)},randomFloat16:function(){return(65280*Math.random()+255*Math.random())/65535},randomInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randomFloat:function(e,t){return e+Math.random()*(t-e)},randomFloatSpread:function(e){return e*(.5-Math.random())},sign:function(e){return 0>e?-1:e>0?1:0},degToRad:function(e){return e*XG.Math.__d2r},radToDeg:function(e){return e*XG.Math.__r2d},focalLengthToFov:function(e,t){return 2*Math.atan(.5*t/e)},fovToFocalLength:function(e,t){return.5*t/Math.tan(.5*e)},stopToFstop:function(e){return Math.pow(Math.SQRT2,e)},mapSquareToDisk:function(e,t,a,r,i){var o,n,s=XG.Math.__pi4;e>-t?e>t?(o=e,n=s*(t/e)):(o=t,n=s*(2-e/t)):t>e?(o=-e,n=s*(4+t/e)):(o=-t,n=0!==t?s*(6-e/t):0),void 0!==i&&(o*=Math.cos(Math.PI/i)/Math.cos(n-2*Math.PI/i*Math.floor((i*n+Math.PI)/(2*Math.PI))));var l=o*Math.cos(n),h=o*Math.sin(n);return void 0===a&&(a=[]),void 0===r&&(r=0),a[r]=l,a[r+1]=h,a},generateConcentricCircleSamples:function(e,t){for(var a=new Array(e*e*2),r=.5*(e-1),i=0,o=-r;r>=o;o++)for(var n=-r;r>=n;n++){var s=o/r,l=n/r;XG.Math.mapSquareToDisk(s,l,a,i,t),i+=2}return a},generatePoissonDiscSamples:function(e){for(var t=new Array(2*e),a=1/e,r=1-a/2,i=2.399963229728653,o=0,n=0,s=0;e>s;s++){var l=Math.sqrt(1-r),h=Math.cos(o)*l,d=Math.sin(o)*l;t[n]=h,t[n+1]=d,r-=a,o+=i,n+=2}return t},isPowerOfTwo:function(e){return 0!==e&&0===(e&e-1)}},XG.Math.__d2r=Math.PI/180,XG.Math.__r2d=180/Math.PI,XG.Math.__pi4=.25*Math.PI,XG.Quaternion=function(e,t,a,r){this.data=new Float32Array(4),this.data[0]=void 0!==e?e:0,this.data[1]=void 0!==t?t:0,this.data[2]=void 0!==a?a:0,this.data[3]=void 0!==r?r:1},XG.Quaternion.prototype={constructor:XG.Quaternion,set:function(e,t,a,r){var i=this.data;return i[0]=e,i[1]=t,i[2]=a,i[3]=r,this},setX:function(e){return this.data[0]=e,this},setY:function(e){return this.data[1]=e,this},setZ:function(e){return this.data[2]=e,this},setW:function(e){return this.data[3]=e,this},set x(e){this.data[0]=e},set y(e){this.data[1]=e},set z(e){this.data[2]=e},set w(e){this.data[3]=e},get x(){return this.data[0]},get y(){return this.data[1]},get z(){return this.data[2]},get w(){return this.data[3]},copy:function(e){return this.data.set(e.data),this},copyIntoArray:function(e,t){void 0===t&&(t=0),e.set(this.data,t)},setFromEuler:function(e,t){var a=this.data,r=e.data,i=Math.cos(r[0]/2),o=Math.cos(r[1]/2),n=Math.cos(r[2]/2),s=Math.sin(r[0]/2),l=Math.sin(r[1]/2),h=Math.sin(r[2]/2);return 0===t||void 0===t?(a[0]=s*o*n+i*l*h,a[1]=i*l*n-s*o*h,a[2]=i*o*h+s*l*n,a[3]=i*o*n-s*l*h):1===t?(a[0]=s*o*n+i*l*h,a[1]=i*l*n-s*o*h,a[2]=i*o*h-s*l*n,a[3]=i*o*n+s*l*h):2===t?(a[0]=s*o*n-i*l*h,a[1]=i*l*n+s*o*h,a[2]=i*o*h+s*l*n,a[3]=i*o*n-s*l*h):3===t?(a[0]=s*o*n-i*l*h,a[1]=i*l*n+s*o*h,a[2]=i*o*h-s*l*n,a[3]=i*o*n+s*l*h):4===t?(a[0]=s*o*n+i*l*h,a[1]=i*l*n+s*o*h,a[2]=i*o*h-s*l*n,a[3]=i*o*n-s*l*h):5===t&&(a[0]=s*o*n-i*l*h,a[1]=i*l*n-s*o*h,a[2]=i*o*h+s*l*n,a[3]=i*o*n+s*l*h),this},setFromAxisAngle:function(e,t){var a=this.data,r=e.data,i=t/2,o=Math.sin(i);return a[0]=r[0]*o,a[1]=r[1]*o,a[2]=r[2]*o,a[3]=Math.cos(i),this},setFromRotationMatrix:function(e){var t,a=this.data,r=e.elements,i=r[0],o=r[4],n=r[8],s=r[1],l=r[5],h=r[9],d=r[2],c=r[6],u=r[10],f=i+l+u;return f>0?(t=.5/Math.sqrt(f+1),a[0]=(c-h)*t,a[1]=(n-d)*t,a[2]=(s-o)*t,a[3]=.25/t):i>l&&i>u?(t=2*Math.sqrt(1+i-l-u),a[0]=.25*t,a[1]=(o+s)/t,a[2]=(n+d)/t,a[3]=(c-h)/t):l>u?(t=2*Math.sqrt(1+l-i-u),a[0]=(o+s)/t,a[1]=.25*t,a[2]=(h+c)/t,a[3]=(n-d)/t):(t=2*Math.sqrt(1+u-i-l),a[0]=(n+d)/t,a[1]=(h+c)/t,a[2]=.25*t,a[3]=(s-o)/t),this},inverse:function(){return this.conjugate().normalize(),this},conjugate:function(){var e=this.data;return e[0]*=-1,e[1]*=-1,e[2]*=-1,this},lengthSq:function(){var e=this.data;return e[0]*e[0]+e[1]*e[1]+e[2]*e[2]+e[3]*e[3]},length:function(){var e=this.data;return Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]+e[3]*e[3])},normalize:function(){var e=this.data,t=this.length();return 0===t?(e[0]=0,e[1]=0,e[2]=0,e[3]=1):(t=1/t,e[0]=e[0]*t,e[1]=e[1]*t,e[2]=e[2]*t,e[3]=e[3]*t),this},multiply:function(e,t){return this.copy(e),this.multiplySelf(t)},multiplySelf:function(e){var t=this.data,a=e.data,r=t[0],i=t[1],o=t[2],n=t[3],s=a[0],l=a[1],h=a[2],d=a[3];return t[0]=r*d+n*s+i*h-o*l,t[1]=i*d+n*l+o*s-r*h,t[2]=o*d+n*h+r*l-i*s,t[3]=n*d-r*s-i*l-o*h,this},multiplyVector3:function(e,t){t||(t=e);var a=this.data,r=e.data,i=t.data,o=r[0],n=r[1],s=r[2],l=a[0],h=a[1],d=a[2],c=a[3],u=c*o+h*s-d*n,f=c*n+d*o-l*s,p=c*s+l*n-h*o,m=-l*o-h*n-d*s;return i[0]=u*c+m*-l+f*-d-p*-h,i[1]=f*c+m*-h+p*-l-u*-d,i[2]=p*c+m*-d+u*-h-f*-l,t},slerpSelf:function(e,t){var a=this.data,r=e.data,i=a[0],o=a[1],n=a[2],s=a[3],l=r[0],h=r[1],d=r[2],c=r[3],u=s*c+i*l+o*h+n*d;if(0>u?(a[0]=-l,a[1]=-h,a[2]=-d,a[3]=-c,u=-u):this.copy(e),u>=1)return a[0]=i,a[1]=o,a[2]=n,a[3]=s,this;var f=Math.acos(u),p=Math.sqrt(1-u*u);if(Math.abs(p)<.001)return a[0]=.5*(i+a[0]),a[1]=.5*(o+a[1]),a[2]=.5*(n+a[2]),a[3]=.5*(s+a[3]),this;var m=Math.sin((1-t)*f)/p,v=Math.sin(t*f)/p;return a[0]=i*m+a[0]*v,a[1]=o*m+a[1]*v,a[2]=n*m+a[2]*v,a[3]=s*m+a[3]*v,this},equals:function(e){var t=this.data,a=e.data;return a[0]===t[0]&&a[1]===t[1]&&a[2]===t[2]&&a[3]===t[3]},clone:function(){return(new XG.Quaternion).copy(this)}},XG.Quaternion.slerp=function(e,t,a,r){return a.copy(e).slerpSelf(t,r)},XG.Vector2=function(e,t){this.data=new Float32Array(2),this.data[0]=void 0!==e?e:0,this.data[1]=void 0!==t?t:0},XG.Vector2.prototype={constructor:XG.Vector2,set:function(e,t){var a=this.data;return a[0]=e,a[1]=t,this},setX:function(e){return this.data[0]=e,this},setY:function(e){return this.data[1]=e,this},set x(e){this.data[0]=e},set y(e){this.data[1]=e},get x(){return this.data[0]},get y(){return this.data[1]},copy:function(e){return this.data.set(e.data),this},copyIntoArray:function(e,t){void 0===t&&(t=0),e.set(this.data,t)},addScalar:function(e){var t=this.data;return t[0]+=e,t[1]+=e,this},add:function(e,t){var a=this.data,r=e.data,i=t.data;return a[0]=r[0]+i[0],a[1]=r[1]+i[1],this},addSelf:function(e){var t=this.data,a=e.data;return t[0]+=a[0],t[1]+=a[1],this},sub:function(e,t){var a=this.data,r=e.data,i=t.data;return a[0]=r[0]-i[0],a[1]=r[1]-i[1],this},subSelf:function(e){var t=this.data,a=e.data;return t[0]-=a[0],t[1]-=a[1],this},multiplyScalar:function(e){var t=this.data;return t[0]*=e,t[1]*=e,this},divideScalar:function(e){var t=this.data;return 0!==e?(t[0]/=e,t[1]/=e):(t[0]=0,t[1]=0),this},negate:function(){return this.multiplyScalar(-1)},dot:function(e){var t=this.data,a=e.data;return t[0]*a[0]+t[1]*a[1]},lengthSq:function(){var e=this.data;return e[0]*e[0]+e[1]*e[1]},length:function(){var e=this.data;return Math.sqrt(e[0]*e[0]+e[1]*e[1])},normalize:function(){return this.divideScalar(this.length())},distanceTo:function(e){return Math.sqrt(this.distanceToSquared(e))},distanceToSquared:function(e){var t=this.data,a=e.data,r=t[0]-a[0],i=t[1]-a[1];return r*r+i*i},setLength:function(e){var t=this.length();return 0!==t&&e!==t&&this.multiplyScalar(e/t),this},lerpSelf:function(e,t){var a=this.data,r=e.data;return a[0]+=(r[0]-a[0])*t,a[1]+=(r[1]-a[1])*t,this},equals:function(e){var t=this.data,a=e.data;return a[0]===t[0]&&a[1]===t[1]},clone:function(){return(new XG.Vector2).copy(this)}},XG.Vector3=function(e,t,a){this.data=new Float32Array(3),this.data[0]=void 0!==e?e:0,this.data[1]=void 0!==t?t:0,this.data[2]=void 0!==a?a:0},XG.Vector3.prototype={constructor:XG.Vector3,set:function(e,t,a){var r=this.data;return r[0]=e,r[1]=t,r[2]=a,this},setX:function(e){return this.data[0]=e,this},setY:function(e){return this.data[1]=e,this},setZ:function(e){return this.data[2]=e,this},set x(e){this.data[0]=e},set y(e){this.data[1]=e},set z(e){this.data[2]=e},get x(){return this.data[0]},get y(){return this.data[1]},get z(){return this.data[2]},copy:function(e){return this.data.set(e.data),this},copyIntoArray:function(e,t){void 0===t&&(t=0),e.set(this.data,t)},add:function(e,t){var a=this.data,r=e.data,i=t.data;return a[0]=r[0]+i[0],a[1]=r[1]+i[1],a[2]=r[2]+i[2],this},addSelf:function(e){var t=this.data,a=e.data;return t[0]+=a[0],t[1]+=a[1],t[2]+=a[2],this},addScalar:function(e){var t=this.data;return t[0]+=e,t[1]+=e,t[2]+=e,this},sub:function(e,t){var a=this.data,r=e.data,i=t.data;return a[0]=r[0]-i[0],a[1]=r[1]-i[1],a[2]=r[2]-i[2],this},subSelf:function(e){var t=this.data,a=e.data;return t[0]-=a[0],t[1]-=a[1],t[2]-=a[2],this},multiply:function(e,t){var a=this.data,r=e.data,i=t.data;return a[0]=r[0]*i[0],a[1]=r[1]*i[1],a[2]=r[2]*i[2],this},multiplySelf:function(e){var t=this.data,a=e.data;return t[0]*=a[0],t[1]*=a[1],t[2]*=a[2],this},multiplyScalar:function(e){var t=this.data;return t[0]*=e,t[1]*=e,t[2]*=e,this},divideSelf:function(e){var t=this.data,a=e.data;return t[0]/=a[0],t[1]/=a[1],t[2]/=a[2],this},divideScalar:function(e){var t=this.data;return 0!==e?(t[0]/=e,t[1]/=e,t[2]/=e):(t[0]=0,t[1]=0,t[2]=0),this},negate:function(){return this.multiplyScalar(-1)},dot:function(e){var t=this.data,a=e.data;return t[0]*a[0]+t[1]*a[1]+t[2]*a[2]},lengthSq:function(){var e=this.data;return e[0]*e[0]+e[1]*e[1]+e[2]*e[2]},length:function(){var e=this.data;return Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2])},lengthManhattan:function(){var e=this.data;return Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2])},normalize:function(){return this.divideScalar(this.length())},setLength:function(e){var t=this.length();return 0!==t&&e!==t&&this.multiplyScalar(e/t),this},cross:function(e,t){var a=this.data,r=e.data,i=t.data;return a[0]=r[1]*i[2]-r[2]*i[1],a[1]=r[2]*i[0]-r[0]*i[2],a[2]=r[0]*i[1]-r[1]*i[0],this},crossSelf:function(e){var t=this.data,a=e.data,r=t[0],i=t[1],o=t[2];return t[0]=i*a[2]-o*a[1],t[1]=o*a[0]-r*a[2],t[2]=r*a[1]-i*a[0],this},minSelf:function(e){var t=this.data,a=e.data;return t[0]=Math.min(t[0],a[0]),t[1]=Math.min(t[1],a[1]),t[2]=Math.min(t[2],a[2]),this},maxSelf:function(e){var t=this.data,a=e.data;return t[0]=Math.max(t[0],a[0]),t[1]=Math.max(t[1],a[1]),t[2]=Math.max(t[2],a[2]),this},angleTo:function(e){return Math.acos(this.dot(e)/this.length()/e.length())},distanceTo:function(e){return Math.sqrt(this.distanceToSquared(e))},distanceToSquared:function(e){var t=this.data,a=e.data,r=t[0]-a[0],i=t[1]-a[1],o=t[2]-a[2];return r*r+i*i+o*o},getPositionFromMatrix:function(e){var t=this.data;return t[0]=e.elements[12],t[1]=e.elements[13],t[2]=e.elements[14],this},setEulerFromRotationMatrix:function(e,t){var a=this.data,r=XG.Math.clamp,i=e.elements,o=i[0],n=i[4],s=i[8],l=i[1],h=i[5],d=i[9],c=i[2],u=i[6],f=i[10];return 0===t||void 0===t?(a[1]=Math.asin(r(s,-1,1)),Math.abs(s)<.99999?(a[0]=Math.atan2(-d,f),a[2]=Math.atan2(-n,o)):(a[0]=Math.atan2(u,h),a[2]=0)):1===t?(a[0]=Math.asin(-r(d,-1,1)),Math.abs(d)<.99999?(a[1]=Math.atan2(s,f),a[2]=Math.atan2(l,h)):(a[1]=Math.atan2(-c,o),a[2]=0)):2===t?(a[0]=Math.asin(r(u,-1,1)),Math.abs(u)<.99999?(a[1]=Math.atan2(-c,f),a[2]=Math.atan2(-n,h)):(a[1]=0,a[2]=Math.atan2(l,o))):3===t?(a[1]=Math.asin(-r(c,-1,1)),Math.abs(c)<.99999?(a[0]=Math.atan2(u,f),a[2]=Math.atan2(l,o)):(a[0]=0,a[2]=Math.atan2(-n,h))):4===t?(a[2]=Math.asin(r(l,-1,1)),Math.abs(l)<.99999?(a[0]=Math.atan2(-d,h),a[1]=Math.atan2(-c,o)):(a[0]=0,a[1]=Math.atan2(s,f))):5===t&&(a[2]=Math.asin(-r(n,-1,1)),Math.abs(n)<.99999?(a[0]=Math.atan2(u,h),a[1]=Math.atan2(s,o)):(a[0]=Math.atan2(-d,f),a[1]=0)),this},setEulerFromQuaternion:function(e,t){var a=XG.Math.clamp,r=this.data,i=e.data[0],o=e.data[1],n=e.data[2],s=e.data[3],l=i*i,h=o*o,d=n*n,c=s*s;return 0===t||void 0===t?(r[0]=Math.atan2(2*(i*s-o*n),c-l-h+d),r[1]=Math.asin(a(2*(i*n+o*s),-1,1)),r[2]=Math.atan2(2*(n*s-i*o),c+l-h-d)):1===t?(r[0]=Math.asin(a(2*(i*s-o*n),-1,1)),r[1]=Math.atan2(2*(i*n+o*s),c-l-h+d),r[2]=Math.atan2(2*(i*o+n*s),c-l+h-d)):2===t?(r[0]=Math.asin(a(2*(i*s+o*n),-1,1)),r[1]=Math.atan2(2*(o*s-n*i),c-l-h+d),r[2]=Math.atan2(2*(n*s-i*o),c-l+h-d)):3===t?(r[0]=Math.atan2(2*(i*s+n*o),c-l-h+d),r[1]=Math.asin(a(2*(o*s-i*n),-1,1)),r[2]=Math.atan2(2*(i*o+n*s),c+l-h-d)):4===t?(r[0]=Math.atan2(2*(i*s-n*o),c-l+h-d),r[1]=Math.atan2(2*(o*s-i*n),c+l-h-d),r[2]=Math.asin(a(2*(i*o+n*s),-1,1))):5===t&&(r[0]=Math.atan2(2*(i*s+o*n),c-l+h-d),r[1]=Math.atan2(2*(i*n+o*s),c+l-h-d),r[2]=Math.asin(a(2*(n*s-i*o),-1,1))),this},getScaleFromMatrix:function(e){var t=this.data,a=this.set(e.elements[0],e.elements[1],e.elements[2]).length(),r=this.set(e.elements[4],e.elements[5],e.elements[6]).length(),i=this.set(e.elements[8],e.elements[9],e.elements[10]).length();return t[0]=a,t[1]=r,t[2]=i,this},projectOnVector:function(e){var t=XG.Vector3.__v1;t.copy(e),t.normalize();var a=this.dot(t);return this.copy(t),this.multiplyScalar(a),this},reflect:function(e){var t=XG.Vector3.__v2;return t.copy(this),t.projectOnVector(e),t.multiplyScalar(2),this.sub(t,this),this},equals:function(e){var t=this.data,a=e.data;return a[0]===t[0]&&a[1]===t[1]&&a[2]===t[2]},clone:function(){return(new XG.Vector3).copy(this)}},XG.Vector3.xAxis=new XG.Vector3(1,0,0),XG.Vector3.yAxis=new XG.Vector3(0,1,0),XG.Vector3.zAxis=new XG.Vector3(0,0,1),XG.Vector3.__v1=new XG.Vector3,XG.Vector3.__v2=new XG.Vector3,XG.Vector4=function(e,t,a,r){this.data=new Float32Array(4),this.data[0]=void 0!==e?e:0,this.data[1]=void 0!==t?t:0,this.data[2]=void 0!==a?a:0,this.data[3]=void 0!==r?r:1},XG.Vector4.prototype={constructor:XG.Vector4,set:function(e,t,a,r){var i=this.data;return i[0]=e,i[1]=t,i[2]=a,i[3]=r,this},setRGBA:function(e,t){var a=this.data;return a[0]=e.r,a[1]=e.g,a[2]=e.b,a[3]=t,this},setRGBAGamma:function(e,t){var a=this.data,r=e.r,i=e.g,o=e.b;return a[0]=r*r,a[1]=i*i,a[2]=o*o,a[3]=t,this},setX:function(e){return this.data[0]=e,this},setY:function(e){return this.data[1]=e,this},setZ:function(e){return this.data[2]=e,this},setW:function(e){return this.data[3]=e,this},set x(e){this.data[0]=e},set y(e){this.data[1]=e},set z(e){this.data[2]=e},set w(e){this.data[3]=e},get x(){return this.data[0]},get y(){return this.data[1]},get z(){return this.data[2]},get w(){return this.data[3]},copy:function(e){return this.data.set(e.data),this},copyIntoArray:function(e,t){void 0===t&&(t=0),e.set(this.data,t)},addScalar:function(e){var t=this.data;return t[0]+=e,t[1]+=e,t[2]+=e,t[3]+=e,this},add:function(e,t){var a=this.data,r=e.data,i=t.data;return a[0]=r[0]+i[0],a[1]=r[1]+i[1],a[2]=r[2]+i[2],a[3]=r[3]+i[3],this},addSelf:function(e){var t=this.data,a=e.data;return t[0]+=a[0],t[1]+=a[1],t[2]+=a[2],t[3]+=a[3],this},sub:function(e,t){var a=this.data,r=e.data,i=t.data;return a[0]=r[0]-i[0],a[1]=r[1]-i[1],a[2]=r[2]-i[2],a[3]=r[3]-i[3],this},subSelf:function(e){var t=this.data,a=e.data;return t[0]-=a[0],t[1]-=a[1],t[2]-=a[2],t[3]-=a[3],this},multiplyScalar:function(e){var t=this.data;return t[0]*=e,t[1]*=e,t[2]*=e,t[3]*=e,this},divideScalar:function(e){var t=this.data;return 0!==e?(t[0]/=e,t[1]/=e,t[2]/=e,t[3]/=e):(t[0]=0,t[1]=0,t[2]=0,t[3]=0),this},negate:function(){return this.multiplyScalar(-1)},dot:function(e){var t=this.data,a=e.data;return t[0]*a[0]+t[1]*a[1]+t[2]*a[2]+t[3]*a[3]},lengthSq:function(){var e=this.data;return e[0]*e[0]+e[1]*e[1]+e[2]*e[2]+e[3]*e[3]},length:function(){var e=this.data;return Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]+e[3]*e[3])},lengthManhattan:function(){var e=this.data;return Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2])+Math.abs(e[3])},normalize:function(){return this.divideScalar(this.length())},setLength:function(e){var t=this.length();return 0!==t&&e!==t&&this.multiplyScalar(e/t),this},lerpSelf:function(e,t){var a=this.data,r=e.data;return a[0]+=(r[0]-a[0])*t,a[1]+=(r[1]-a[1])*t,a[2]+=(r[2]-a[2])*t,a[3]+=(r[3]-a[3])*t,this},equals:function(e){var t=this.data,a=e.data;return a[0]===t[0]&&a[1]===t[1]&&a[2]===t[2]&&a[3]===t[3]},clone:function(){return(new XG.Vector4).copy(this)},setAxisAngleFromQuaternion:function(e){var t=e.data[0],a=e.data[1],r=e.data[2],i=e.data[3];this.data[3]=2*Math.acos(i);var o=Math.sqrt(1-i*i);return 1e-4>o?(this.data[0]=1,this.data[1]=0,this.data[2]=0):(this.data[0]=t/o,this.data[1]=a/o,this.data[2]=r/o),this},setAxisAngleFromRotationMatrix:function(e){var t,a,r,i,o=.01,n=.1,s=e.elements,l=s[0],h=s[4],d=s[8],c=s[1],u=s[5],f=s[9],p=s[2],m=s[6],v=s[10];if(Math.abs(h-c)<o&&Math.abs(d-p)<o&&Math.abs(f-m)<o){if(Math.abs(h+c)<n&&Math.abs(d+p)<n&&Math.abs(f+m)<n&&Math.abs(l+u+v-3)<n)return this.set(1,0,0,0),this;t=Math.PI;var g=(l+1)/2,S=(u+1)/2,G=(v+1)/2,x=(h+c)/4,M=(d+p)/4,y=(f+m)/4;return g>S&&g>G?o>g?(a=0,r=.707106781,i=.707106781):(a=Math.sqrt(g),r=x/a,i=M/a):S>G?o>S?(a=.707106781,r=0,i=.707106781):(r=Math.sqrt(S),a=x/r,i=y/r):o>G?(a=.707106781,r=.707106781,i=0):(i=Math.sqrt(G),a=M/i,r=y/i),this.set(a,r,i,t),this}var X=Math.sqrt((m-f)*(m-f)+(d-p)*(d-p)+(c-h)*(c-h));return Math.abs(X)<.001&&(X=1),this.data[0]=(m-f)/X,this.data[1]=(d-p)/X,this.data[2]=(c-h)/X,this.data[3]=Math.acos((l+u+v-1)/2),this}},XG.Matrix3=function(e,t,a,r,i,o,n,s,l){this.elements=new Float32Array(9),this.set(void 0!==e?e:1,t||0,a||0,r||0,void 0!==i?i:1,o||0,n||0,s||0,void 0!==l?l:1)},XG.Matrix3.prototype={constructor:XG.Matrix3,set:function(e,t,a,r,i,o,n,s,l){var h=this.elements;return h[0]=e,h[3]=t,h[6]=a,h[1]=r,h[4]=i,h[7]=o,h[2]=n,h[5]=s,h[8]=l,this},identity:function(){return this.set(1,0,0,0,1,0,0,0,1),this},copy:function(e){return this.elements.set(e.elements),this},multiplyVector3:function(e){var t=this.elements,a=e.data,r=a[0],i=a[1],o=a[2];return a[0]=t[0]*r+t[3]*i+t[6]*o,a[1]=t[1]*r+t[4]*i+t[7]*o,a[2]=t[2]*r+t[5]*i+t[8]*o,e},multiplyVector3Array:function(e,t,a){var r=XG.Matrix3.__v1,i=r.data;void 0===t&&(t=0),void 0===a&&(a=e.length);for(var o=t;a>o;o+=3)i[0]=e[o],i[1]=e[o+1],i[2]=e[o+2],this.multiplyVector3(r),e.set(i,o);return e},multiplyScalar:function(e){var t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this},getInverse:function(e){var t=e.elements,a=this.elements;a[0]=t[10]*t[5]-t[6]*t[9],a[1]=-t[10]*t[1]+t[2]*t[9],a[2]=t[6]*t[1]-t[2]*t[5],a[3]=-t[10]*t[4]+t[6]*t[8],a[4]=t[10]*t[0]-t[2]*t[8],a[5]=-t[6]*t[0]+t[2]*t[4],a[6]=t[9]*t[4]-t[5]*t[8],a[7]=-t[9]*t[0]+t[1]*t[8],a[8]=t[5]*t[0]-t[1]*t[4];var r=t[0]*a[0]+t[1]*a[3]+t[2]*a[6];return 0===r?(console.warn("Matrix3.getInverse(): can't invert matrix, determinant is 0"),this.identity(),this):(this.multiplyScalar(1/r),this)},transpose:function(){var e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this},transposeIntoArray:function(e){var t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this},getNormalMatrix:function(e){return this.getInverse(e).transpose(),this},clone:function(){return(new XG.Matrix3).copy(this)}},XG.Matrix3.__v1=new XG.Vector3,XG.Matrix4=function(e,t,a,r,i,o,n,s,l,h,d,c,u,f,p,m){this.elements=new Float32Array(16),this.set(void 0!==e?e:1,t||0,a||0,r||0,i||0,void 0!==o?o:1,n||0,s||0,l||0,h||0,void 0!==d?d:1,c||0,u||0,f||0,p||0,void 0!==m?m:1)},XG.Matrix4.prototype={constructor:XG.Matrix4,set:function(e,t,a,r,i,o,n,s,l,h,d,c,u,f,p,m){var v=this.elements;return v[0]=e,v[4]=t,v[8]=a,v[12]=r,v[1]=i,v[5]=o,v[9]=n,v[13]=s,v[2]=l,v[6]=h,v[10]=d,v[14]=c,v[3]=u,v[7]=f,v[11]=p,v[15]=m,this},identity:function(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this},copy:function(e){return this.elements.set(e.elements),this},setRotationFromEuler:function(e,t){var a=this.elements,r=e.data,i=r[0],o=r[1],n=r[2],s=Math.cos(i),l=Math.sin(i),h=Math.cos(o),d=Math.sin(o),c=Math.cos(n),u=Math.sin(n);if(0===t||void 0===t){var f=s*c,p=s*u,m=l*c,v=l*u;a[0]=h*c,a[4]=-h*u,a[8]=d,a[1]=p+m*d,a[5]=f-v*d,a[9]=-l*h,a[2]=v-f*d,a[6]=m+p*d,a[10]=s*h}else if(1===t){var g=h*c,S=h*u,G=d*c,x=d*u;a[0]=g+x*l,a[4]=G*l-S,a[8]=s*d,a[1]=s*u,a[5]=s*c,a[9]=-l,a[2]=S*l-G,a[6]=x+g*l,a[10]=s*h}else if(2===t){var g=h*c,S=h*u,G=d*c,x=d*u;a[0]=g-x*l,a[4]=-s*u,a[8]=G+S*l,a[1]=S+G*l,a[5]=s*c,a[9]=x-g*l,a[2]=-s*d,a[6]=l,a[10]=s*h}else if(3===t){var f=s*c,p=s*u,m=l*c,v=l*u;a[0]=h*c,a[4]=m*d-p,a[8]=f*d+v,a[1]=h*u,a[5]=v*d+f,a[9]=p*d-m,a[2]=-d,a[6]=l*h,a[10]=s*h}else if(4===t){var M=s*h,y=s*d,X=l*h,D=l*d;a[0]=h*c,a[4]=D-M*u,a[8]=X*u+y,a[1]=u,a[5]=s*c,a[9]=-l*c,a[2]=-d*c,a[6]=y*u+X,a[10]=M-D*u}else if(5===t){var M=s*h,y=s*d,X=l*h,D=l*d;
  a[0]=h*c,a[4]=-u,a[8]=d*c,a[1]=M*u+D,a[5]=s*c,a[9]=y*u-X,a[2]=X*u-y,a[6]=l*c,a[10]=D*u+M}return this},setRotationFromQuaternion:function(e){var t=this.elements,a=e.data,r=a[0],i=a[1],o=a[2],n=a[3],s=r+r,l=i+i,h=o+o,d=r*s,c=r*l,u=r*h,f=i*l,p=i*h,m=o*h,v=n*s,g=n*l,S=n*h;return t[0]=1-(f+m),t[4]=c-S,t[8]=u+g,t[1]=c+S,t[5]=1-(d+m),t[9]=p-v,t[2]=u-g,t[6]=p+v,t[10]=1-(d+f),this},lookAt:function(e,t,a){var r=this.elements,i=XG.Matrix4.__v1,o=XG.Matrix4.__v2,n=XG.Matrix4.__v3;n.sub(e,t).normalize(),0===n.length()&&(n.data[2]=1),i.cross(a,n).normalize(),0===i.length()&&(n.data[0]+=1e-4,i.cross(a,n).normalize()),o.cross(n,i);var s=i.data,l=o.data,h=n.data;return r[0]=s[0],r[4]=l[0],r[8]=h[0],r[1]=s[1],r[5]=l[1],r[9]=h[1],r[2]=s[2],r[6]=l[2],r[10]=h[2],this},addSelf:function(e){var t=this.elements,a=e.elements;return t[0]+=a[0],t[4]+=a[4],t[8]+=a[8],t[12]+=a[12],t[1]+=a[1],t[5]+=a[5],t[9]+=a[9],t[13]+=a[13],t[2]+=a[2],t[6]+=a[6],t[10]+=a[10],t[14]+=a[14],t[3]+=a[3],t[7]+=a[7],t[11]+=a[11],t[15]+=a[15],this},multiply:function(e,t){var a=e.elements,r=t.elements,i=this.elements,o=a[0],n=a[4],s=a[8],l=a[12],h=a[1],d=a[5],c=a[9],u=a[13],f=a[2],p=a[6],m=a[10],v=a[14],g=a[3],S=a[7],G=a[11],x=a[15],M=r[0],y=r[4],X=r[8],D=r[12],_=r[1],w=r[5],A=r[9],C=r[13],T=r[2],b=r[6],P=r[10],L=r[14],E=r[3],F=r[7],R=r[11],U=r[15];return i[0]=o*M+n*_+s*T+l*E,i[4]=o*y+n*w+s*b+l*F,i[8]=o*X+n*A+s*P+l*R,i[12]=o*D+n*C+s*L+l*U,i[1]=h*M+d*_+c*T+u*E,i[5]=h*y+d*w+c*b+u*F,i[9]=h*X+d*A+c*P+u*R,i[13]=h*D+d*C+c*L+u*U,i[2]=f*M+p*_+m*T+v*E,i[6]=f*y+p*w+m*b+v*F,i[10]=f*X+p*A+m*P+v*R,i[14]=f*D+p*C+m*L+v*U,i[3]=g*M+S*_+G*T+x*E,i[7]=g*y+S*w+G*b+x*F,i[11]=g*X+S*A+G*P+x*R,i[15]=g*D+S*C+G*L+x*U,this},multiplySelf:function(e){return this.multiply(this,e)},multiplyToArray:function(e,t,a){return this.multiply(e,t),a.set(this.elements),this},multiplyScalar:function(e){var t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this},multiplyVector3:function(e){var t=this.elements,a=e.data,r=a[0],i=a[1],o=a[2],n=1/(t[3]*r+t[7]*i+t[11]*o+t[15]);return a[0]=(t[0]*r+t[4]*i+t[8]*o+t[12])*n,a[1]=(t[1]*r+t[5]*i+t[9]*o+t[13])*n,a[2]=(t[2]*r+t[6]*i+t[10]*o+t[14])*n,e},multiplyVector4:function(e){var t=this.elements,a=e.data,r=a[0],i=a[1],o=a[2],n=a[3];return a[0]=t[0]*r+t[4]*i+t[8]*o+t[12]*n,a[1]=t[1]*r+t[5]*i+t[9]*o+t[13]*n,a[2]=t[2]*r+t[6]*i+t[10]*o+t[14]*n,a[3]=t[3]*r+t[7]*i+t[11]*o+t[15]*n,e},multiplyVector3Array:function(e,t,a){var r=XG.Matrix4.__v1,i=r.data;void 0===t&&(t=0),void 0===a&&(a=e.length);for(var o=t;a>o;o+=3)i[0]=e[o],i[1]=e[o+1],i[2]=e[o+2],this.multiplyVector3(r),e.set(i,o);return e},rotateAxis:function(e){var t=this.elements,a=e.data,r=a[0],i=a[1],o=a[2];return a[0]=r*t[0]+i*t[4]+o*t[8],a[1]=r*t[1]+i*t[5]+o*t[9],a[2]=r*t[2]+i*t[6]+o*t[10],e.normalize(),e},determinant:function(){var e=this.elements,t=e[0],a=e[4],r=e[8],i=e[12],o=e[1],n=e[5],s=e[9],l=e[13],h=e[2],d=e[6],c=e[10],u=e[14],f=e[3],p=e[7],m=e[11],v=e[15];return f*(+i*s*d-r*l*d-i*n*c+a*l*c+r*n*u-a*s*u)+p*(+t*s*u-t*l*c+i*o*c-r*o*u+r*l*h-i*s*h)+m*(+t*l*d-t*n*u-i*o*d+a*o*u+i*n*h-a*l*h)+v*(-r*n*h-t*s*d+t*n*c+r*o*d-a*o*c+a*s*h)},transpose:function(){var e,t=this.elements;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this},flattenToArray:function(e){return e.set(this.elements),e},flattenToArrayOffset:function(e,t){return e.set(this.elements,t),e},getPosition:function(){var e=this.elements;return XG.Matrix4.__v1.set(e[12],e[13],e[14])},setPosition:function(e){return this.elements.set(e.data,12),this},setPositionXYZ:function(e,t,a){var r=this.elements;return r[12]=e,r[13]=t,r[14]=a,this},getColumnX:function(){var e=this.elements;return XG.Matrix4.__v1.set(e[0],e[1],e[2])},getColumnY:function(){var e=this.elements;return XG.Matrix4.__v1.set(e[4],e[5],e[6])},getColumnZ:function(){var e=this.elements;return XG.Matrix4.__v1.set(e[8],e[9],e[10])},getInverse:function(e){var t=this.elements,a=e.elements,r=a[0],i=a[4],o=a[8],n=a[12],s=a[1],l=a[5],h=a[9],d=a[13],c=a[2],u=a[6],f=a[10],p=a[14],m=a[3],v=a[7],g=a[11],S=a[15];t[0]=h*p*v-d*f*v+d*u*g-l*p*g-h*u*S+l*f*S,t[4]=n*f*v-o*p*v-n*u*g+i*p*g+o*u*S-i*f*S,t[8]=o*d*v-n*h*v+n*l*g-i*d*g-o*l*S+i*h*S,t[12]=n*h*u-o*d*u-n*l*f+i*d*f+o*l*p-i*h*p,t[1]=d*f*m-h*p*m-d*c*g+s*p*g+h*c*S-s*f*S,t[5]=o*p*m-n*f*m+n*c*g-r*p*g-o*c*S+r*f*S,t[9]=n*h*m-o*d*m-n*s*g+r*d*g+o*s*S-r*h*S,t[13]=o*d*c-n*h*c+n*s*f-r*d*f-o*s*p+r*h*p,t[2]=l*p*m-d*u*m+d*c*v-s*p*v-l*c*S+s*u*S,t[6]=n*u*m-i*p*m-n*c*v+r*p*v+i*c*S-r*u*S,t[10]=i*d*m-n*l*m+n*s*v-r*d*v-i*s*S+r*l*S,t[14]=n*l*c-i*d*c-n*s*u+r*d*u+i*s*p-r*l*p,t[3]=h*u*m-l*f*m-h*c*v+s*f*v+l*c*g-s*u*g,t[7]=i*f*m-o*u*m+o*c*v-r*f*v-i*c*g+r*u*g,t[11]=o*l*m-i*h*m-o*s*v+r*h*v+i*s*g-r*l*g,t[15]=i*h*c-o*l*c+o*s*u-r*h*u-i*s*f+r*l*f;var G=a[0]*t[0]+a[1]*t[4]+a[2]*t[8]+a[3]*t[12];if(0===G){var x="Matrix4.getInverse(): can't invert matrix, determinant is 0";return console.warn(x),this.identity(),this}return this.multiplyScalar(1/G),this},compose:function(e,t,a){var r=this.elements;r[3]=0,r[7]=0,r[11]=0,r[15]=1,this.setRotationFromQuaternion(t);var i=a.data,o=i[0],n=i[1],s=i[2];return r[0]*=o,r[1]*=o,r[2]*=o,r[4]*=n,r[5]*=n,r[6]*=n,r[8]*=s,r[9]*=s,r[10]*=s,r.set(e.data,12),this},decompose:function(e,t,a){var r=this.elements,i=XG.Matrix4.__v1,o=XG.Matrix4.__v2,n=XG.Matrix4.__v3;i.set(r[0],r[1],r[2]),o.set(r[4],r[5],r[6]),n.set(r[8],r[9],r[10]),e=e instanceof XG.Vector3?e:new XG.Vector3,t=t instanceof XG.Quaternion?t:new XG.Quaternion,a=a instanceof XG.Vector3?a:new XG.Vector3;var s=a.data,l=e.data;s[0]=i.length(),s[1]=o.length(),s[2]=n.length(),l[0]=r[12],l[1]=r[13],l[2]=r[14];var h=XG.Matrix4.__m1;return h.copy(this),h.elements[0]/=s[0],h.elements[1]/=s[0],h.elements[2]/=s[0],h.elements[4]/=s[1],h.elements[5]/=s[1],h.elements[6]/=s[1],h.elements[8]/=s[2],h.elements[9]/=s[2],h.elements[10]/=s[2],t.setFromRotationMatrix(h),[e,t,a]},extractPosition:function(e){var t=this.elements,a=e.elements;return t[12]=a[12],t[13]=a[13],t[14]=a[14],this},extractRotation:function(e){var t=this.elements,a=e.elements,r=XG.Matrix4.__v1,i=1/r.set(a[0],a[1],a[2]).length(),o=1/r.set(a[4],a[5],a[6]).length(),n=1/r.set(a[8],a[9],a[10]).length();return t[0]=a[0]*i,t[1]=a[1]*i,t[2]=a[2]*i,t[4]=a[4]*o,t[5]=a[5]*o,t[6]=a[6]*o,t[8]=a[8]*n,t[9]=a[9]*n,t[10]=a[10]*n,this},translate:function(e){var t=this.elements,a=e.data,r=a[0],i=a[1],o=a[2];return t[12]=t[0]*r+t[4]*i+t[8]*o+t[12],t[13]=t[1]*r+t[5]*i+t[9]*o+t[13],t[14]=t[2]*r+t[6]*i+t[10]*o+t[14],t[15]=t[3]*r+t[7]*i+t[11]*o+t[15],this},rotateX:function(e){var t=this.elements,a=t[4],r=t[5],i=t[6],o=t[7],n=t[8],s=t[9],l=t[10],h=t[11],d=Math.cos(e),c=Math.sin(e);return t[4]=d*a+c*n,t[5]=d*r+c*s,t[6]=d*i+c*l,t[7]=d*o+c*h,t[8]=d*n-c*a,t[9]=d*s-c*r,t[10]=d*l-c*i,t[11]=d*h-c*o,this},rotateY:function(e){var t=this.elements,a=t[0],r=t[1],i=t[2],o=t[3],n=t[8],s=t[9],l=t[10],h=t[11],d=Math.cos(e),c=Math.sin(e);return t[0]=d*a-c*n,t[1]=d*r-c*s,t[2]=d*i-c*l,t[3]=d*o-c*h,t[8]=d*n+c*a,t[9]=d*s+c*r,t[10]=d*l+c*i,t[11]=d*h+c*o,this},rotateZ:function(e){var t=this.elements,a=t[0],r=t[1],i=t[2],o=t[3],n=t[4],s=t[5],l=t[6],h=t[7],d=Math.cos(e),c=Math.sin(e);return t[0]=d*a+c*n,t[1]=d*r+c*s,t[2]=d*i+c*l,t[3]=d*o+c*h,t[4]=d*n-c*a,t[5]=d*s-c*r,t[6]=d*l-c*i,t[7]=d*h-c*o,this},rotateByAxis:function(e,t){var a=this.elements,r=e.data,i=r[0],o=r[1],n=r[2];if(1===i&&0===o&&0===n)return this.rotateX(t);if(0===i&&1===o&&0===n)return this.rotateY(t);if(0===i&&0===o&&1===n)return this.rotateZ(t);var s=Math.sqrt(i*i+o*o+n*n);i/=s,o/=s,n/=s;var l=i*i,h=o*o,d=n*n,c=Math.cos(t),u=Math.sin(t),f=1-c,p=i*o*f,m=i*n*f,v=o*n*f,g=i*u,S=o*u,G=n*u,x=l+(1-l)*c,M=p+G,y=m-S,X=p-G,D=h+(1-h)*c,_=v+g,w=m+S,A=v-g,C=d+(1-d)*c,T=a[0],b=a[1],P=a[2],L=a[3],E=a[4],F=a[5],R=a[6],U=a[7],N=a[8],I=a[9],B=a[10],O=a[11];return a[0]=x*T+M*E+y*N,a[1]=x*b+M*F+y*I,a[2]=x*P+M*R+y*B,a[3]=x*L+M*U+y*O,a[4]=X*T+D*E+_*N,a[5]=X*b+D*F+_*I,a[6]=X*P+D*R+_*B,a[7]=X*L+D*U+_*O,a[8]=w*T+A*E+C*N,a[9]=w*b+A*F+C*I,a[10]=w*P+A*R+C*B,a[11]=w*L+A*U+C*O,this},scale:function(e){var t=this.elements,a=e.data,r=a[0],i=a[1],o=a[2];return t[0]*=r,t[4]*=i,t[8]*=o,t[1]*=r,t[5]*=i,t[9]*=o,t[2]*=r,t[6]*=i,t[10]*=o,t[3]*=r,t[7]*=i,t[11]*=o,this},getMaxScaleOnAxis:function(){var e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],a=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,Math.max(a,r)))},makeTranslation:function(e){return this.set(1,0,0,e.data[0],0,1,0,e.data[1],0,0,1,e.data[2],0,0,0,1),this},makeRotationX:function(e){var t=Math.cos(e),a=Math.sin(e);return this.set(1,0,0,0,0,t,-a,0,0,a,t,0,0,0,0,1),this},makeRotationY:function(e){var t=Math.cos(e),a=Math.sin(e);return this.set(t,0,a,0,0,1,0,0,-a,0,t,0,0,0,0,1),this},makeRotationZ:function(e){var t=Math.cos(e),a=Math.sin(e);return this.set(t,-a,0,0,a,t,0,0,0,0,1,0,0,0,0,1),this},makeRotationAxis:function(e,t){var a=e.data,r=Math.cos(t),i=Math.sin(t),o=1-r,n=a[0],s=a[1],l=a[2],h=o*n,d=o*s;return this.set(h*n+r,h*s-i*l,h*l+i*s,0,h*s+i*l,d*s+r,d*l-i*n,0,h*l-i*s,d*l+i*n,o*l*l+r,0,0,0,0,1),this},makeScale:function(e){var t=e.data;return this.set(t[0],0,0,0,0,t[1],0,0,0,0,t[2],0,0,0,0,1),this},makeFrustum:function(e,t,a,r,i,o){var n=this.elements,s=2*i/(t-e),l=2*i/(r-a),h=(t+e)/(t-e),d=(r+a)/(r-a),c=-(o+i)/(o-i),u=-2*o*i/(o-i);return n[0]=s,n[4]=0,n[8]=h,n[12]=0,n[1]=0,n[5]=l,n[9]=d,n[13]=0,n[2]=0,n[6]=0,n[10]=c,n[14]=u,n[3]=0,n[7]=0,n[11]=-1,n[15]=0,this},makePerspective:function(e,t,a,r){var i=a*Math.tan(XG.Math.degToRad(.5*e)),o=-i,n=o*t,s=i*t;return this.makeFrustum(n,s,o,i,a,r)},makeOrthographic:function(e,t,a,r,i,o){var n=this.elements,s=t-e,l=a-r,h=o-i,d=(t+e)/s,c=(a+r)/l,u=(o+i)/h;return n[0]=2/s,n[4]=0,n[8]=0,n[12]=-d,n[1]=0,n[5]=2/l,n[9]=0,n[13]=-c,n[2]=0,n[6]=0,n[10]=-2/h,n[14]=-u,n[3]=0,n[7]=0,n[11]=0,n[15]=1,this},clone:function(){return(new XG.Matrix4).copy(this)}},XG.Matrix4.__v1=new XG.Vector3,XG.Matrix4.__v2=new XG.Vector3,XG.Matrix4.__v3=new XG.Vector3,XG.Matrix4.__m1=new XG.Matrix4,XG.Matrix4.__m2=new XG.Matrix4,XG.Frustum=function(){this.planes=[new XG.Plane,new XG.Plane,new XG.Plane,new XG.Plane,new XG.Plane,new XG.Plane],this.tmpVec=new XG.Vector3},XG.Frustum.prototype.setFromMatrix=function(e){var t=this.planes,a=e.elements,r=a[0],i=a[1],o=a[2],n=a[3],s=a[4],l=a[5],h=a[6],d=a[7],c=a[8],u=a[9],f=a[10],p=a[11],m=a[12],v=a[13],g=a[14],S=a[15];t[0].setComponents(n-r,d-s,p-c,S-m),t[1].setComponents(n+r,d+s,p+c,S+m),t[2].setComponents(n+i,d+l,p+u,S+v),t[3].setComponents(n-i,d-l,p-u,S-v),t[4].setComponents(n-o,d-h,p-f,S-g),t[5].setComponents(n+o,d+h,p+f,S+g);for(var G=0;6>G;G++)t[G].normalize()},XG.Frustum.prototype.contains=function(e,t){for(var a=this.planes,r=e.matrixWorld,i=r.getPosition(),o=-t.boundingSphere.radius*r.getMaxScaleOnAxis(),n=0,s=0;6>s;s++)if(n=a[s].distanceToPoint(i),o>=n)return!1;return!0},XG.Frustum.prototype.containsInstance=function(e,t,a){var r=this.planes,i=e.matrixWorld,o=-t.boundingSphere.radius*i.getMaxScaleOnAxis(),n=t.attributes.offset.array,s=3*a,l=n[s],h=n[s+1],d=n[s+2],c=this.tmpVec;c.set(l,h,d),e.localToWorld(c);for(var u=0,f=0;6>f;f++)if(u=r[f].distanceToPoint(c),o>=u)return!1;return!0},XG.Plane=function(e,t){this.normal=void 0!==e?e.clone():XG.Vector3.xAxis.clone(),this.constant=void 0!==t?t:0},XG.Plane.prototype={constructor:XG.Plane,set:function(e,t){return this.normal.copy(e),this.constant=t,this},setComponents:function(e,t,a,r){return this.normal.set(e,t,a),this.constant=r,this},setFromNormalAndCoplanarPoint:function(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this},setFromCoplanarPoints:function(){var e=new XG.Vector3,t=new XG.Vector3;return function(a,r,i){var o=e.sub(i,r).crossSelf(t.sub(a,r)).normalize();return this.setFromNormalAndCoplanarPoint(o,a),this}}(),intersectLine:function(){var e=new XG.Vector3;return function(t,a,r){var i=r||new XG.Vector3,o=e.sub(a,t),n=this.normal.dot(o);if(0===n)return 0===this.distanceToPoint(t)?i.copy(t):void 0;var s=-(t.dot(this.normal)+this.constant)/n;return i.copy(o).multiplyScalar(s).addSelf(t)}}(),intersectLineSegment:function(){var e=new XG.Vector3;return function(t,a,r){var i=r||new XG.Vector3,o=e.sub(a,t),n=this.normal.dot(o);if(0===n)return 0===this.distanceToPoint(t)?i.copy(t):void 0;var s=-(t.dot(this.normal)+this.constant)/n;return 0>s||s>1?void 0:i.copy(o).multiplyScalar(s).addSelf(t)}}(),copy:function(e){return this.normal.copy(e.normal),this.constant=e.constant,this},normalize:function(){var e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this},distanceToPoint:function(e){return this.normal.dot(e)+this.constant},coplanarPoint:function(e){var t=e||new XG.Vector3;return t.copy(this.normal),t.multiplyScalar(-this.constant),t},applyMatrix4:function(e,t){var a=XG.Plane.__v1,r=XG.Plane.__v2;t=t||XG.Plane.__m1.getNormalMatrix(e);var i=a.copy(this.normal);t.multiplyVector3(i);var o=this.coplanarPoint(r);return e.multiplyVector3(o),this.setFromNormalAndCoplanarPoint(i,o),this},clone:function(){return(new XG.Plane).copy(this)}},XG.Plane.__v1=new XG.Vector3,XG.Plane.__v2=new XG.Vector3,XG.Plane.__m1=new XG.Matrix3,XG.Box3=function(e,t){this.min=void 0!==e?e.clone():new XG.Vector3(1/0,1/0,1/0),this.max=void 0!==t?t.clone():new XG.Vector3(-1/0,-1/0,-1/0)},XG.Box3.prototype={constructor:XG.Box3,set:function(e,t){return this.min.copy(e),this.max.copy(t),this},copy:function(e){return this.min.copy(e.min),this.max.copy(e.max),this},add:function(e){this.min.minSelf(e.min),this.max.maxSelf(e.max)},clone:function(){return(new XG.Box3).copy(this)}},XG.Sphere=function(e,t){this.center=void 0===e?new XG.Vector3:e.clone(),this.radius=void 0===t?0:t},XG.Sphere.prototype={constructor:XG.Sphere,set:function(e,t){return this.center.copy(e),this.radius=t,this},copy:function(e){return this.center.copy(e.center),this.radius=e.radius,this},containsPoint:function(e){return e.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(e){return e.distanceTo(this.center)-this.radius},clone:function(){return(new XG.Sphere).copy(this)}},XG.Clock=function(e){this.autoStart=void 0!==e?e:!0,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1},XG.Clock.prototype.start=function(){this.startTime=Date.now(),this.oldTime=this.startTime,this.running=!0},XG.Clock.prototype.stop=function(){this.getElapsedTime(),this.running=!1},XG.Clock.prototype.getElapsedTime=function(){return this.getDelta(),this.elapsedTime},XG.Clock.prototype.getDelta=function(){var e=0;if(this.autoStart&&!this.running&&this.start(),this.running){var t=Date.now();e=.001*(t-this.oldTime),this.oldTime=t,this.elapsedTime+=e}return e},XG.Animation=function(e,t){this.id=XG.AnimationIdCount++,this.root=e,this.data=t,this.hierarchy=[],this.boneIndexMap={};for(var a=0;a<e.bones.length;a++){var r=e.bones[a];this.hierarchy.push(r),this.boneIndexMap[r.name]=a}this.initData(t),this.currentTime=0,this.timeScale=1,this.weight=1,this.direction=1,this.directionBackwards=!1,this.isPlaying=!1,this.isPaused=!0,this.loop=!0},XG.Animation.prototype.play=function(e,t){if(this.isPlaying===!1){this.isPlaying=!0,this.loop=void 0!==e?e:!0,this.currentTime=void 0!==t?t:0;var a,r,i=this.hierarchy.length;for(a=0;i>a;a++){r=this.hierarchy[a],r.useQuaternion=!0,r.matrixAutoUpdate=!0,void 0===r.animationCache&&(r.animationCache={});var o;void 0===r.animationCache[this.id]?(r.animationCache[this.id]={},o=r.animationCache[this.id],o.prevKey={pos:0,rot:0,scl:0},o.nextKey={pos:0,rot:0,scl:0},o.originalMatrix=r instanceof XG.Bone?r.skinMatrix:r.matrix,o.oldMatrix=new XG.Matrix4):o=r.animationCache[this.id];var n=o.prevKey,s=o.nextKey;n.pos=this.data.hierarchy[a].keys[0],n.rot=this.data.hierarchy[a].keys[0],n.scl=this.data.hierarchy[a].keys[0],this.directionBackwards?(s.pos=this.getPrevKeyWith("pos",a,-1),s.rot=this.getPrevKeyWith("rot",a,-1),s.scl=this.getPrevKeyWith("scl",a,-1)):(s.pos=this.getNextKeyWith("pos",a,1),s.rot=this.getNextKeyWith("rot",a,1),s.scl=this.getNextKeyWith("scl",a,1))}this.update(0)}this.isPaused=!1},XG.Animation.prototype.setWeight=function(e){this.weight=e},XG.Animation.prototype.setDirectionForward=function(){this.direction=1,this.directionBackwards=!1},XG.Animation.prototype.setDirectionBackward=function(){this.direction=-1,this.directionBackwards=!0},XG.Animation.prototype.pause=function(){this.isPaused=!this.isPaused},XG.Animation.prototype.stop=function(){this.isPlaying=!1,this.isPaused=!1},XG.Animation.prototype.update=function(e){if(this.isPlaying!==!1){var t,a,r,i,o,n,s,l,h,d,c,u,f=["pos","rot","scl"],p=this.currentTime+e*this.timeScale*this.direction,m=p%this.data.length;this.directionBackwards&&0>m&&(m+=this.data.length);var v=m;this.currentTime=m;for(var g=0,S=this.hierarchy.length;S>g;g++){l=this.hierarchy[g],h=l.animationCache[this.id],l.matrixAutoUpdate=!1,l.firstAnimationFlag||h.oldMatrix.copy(l.matrix);for(var G=0;3>G;G++){if(t=f[G],n=h.prevKey[t],s=h.nextKey[t],this.directionBackwards){if(s.time>p){if(v>p){if(!this.loop)return void this.stop();var x=this.data.hierarchy[g].keys;for(n=this.data.hierarchy[g].keys[x.length-1],s=this.getPrevKeyWith(t,g,-1);s.time>v;)n=s,s=this.getPrevKeyWith(t,g,s.index-1)}else do n=s,s=this.getPrevKeyWith(t,g,s.index-1);while(s.time>v);h.prevKey[t]=n,h.nextKey[t]=s}a=(n.time-v)/(n.time-s.time)}else{if(s.time<=p){if(p>v){if(!this.loop)return void this.stop();for(n=this.data.hierarchy[g].keys[0],s=this.getNextKeyWith(t,g,1);s.time<v;)n=s,s=this.getNextKeyWith(t,g,s.index+1)}else do n=s,s=this.getNextKeyWith(t,g,s.index+1);while(s.time<v);h.prevKey[t]=n,h.nextKey[t]=s}a=(v-n.time)/(s.time-n.time)}i=n[t],o=s[t],(0>a||a>1)&&(console.log("XG.Animation.update: Warning! Scale out of bounds:"+a+" on bone "+g),a=0>a?0:1),"pos"===t?(r=l.position,d=i[0]+(o[0]-i[0])*a,c=i[1]+(o[1]-i[1])*a,u=i[2]+(o[2]-i[2])*a,r.set(d,c,u)):"rot"===t?XG.Quaternion.slerp(i,o,l.quaternion,a):"scl"===t&&(r=l.scale,d=i[0]+(o[0]-i[0])*a,c=i[1]+(o[1]-i[1])*a,u=i[2]+(o[2]-i[2])*a,r.set(d,c,u))}l.updateMatrix(),l.matrix.multiplyScalar(this.weight),l.firstAnimationFlag||l.matrix.addSelf(h.oldMatrix),l.firstAnimationFlag=!1}}},XG.Animation.prototype.getNextKeyWith=function(e,t,a){var r=this.data.hierarchy[t].keys;for(a%=r.length;a<r.length;a++)if(void 0!==r[a][e])return r[a];return this.data.hierarchy[t].keys[0]},XG.Animation.prototype.getPrevKeyWith=function(e,t,a){var r=this.data.hierarchy[t].keys;for(a=a>=0?a:a+r.length;a>=0;a--)if(void 0!==r[a][e])return r[a];return this.data.hierarchy[t].keys[r.length-1]},XG.Animation.prototype.initData=function(e){if(e.initialized!==!0){for(var t=e.hierarchy,a=0;a<t.length;a++){for(var r=t[a],i=0;i<r.keys.length;i++)if(r.keys[i].time<0&&(r.keys[i].time=0),void 0!==r.keys[i].rot&&!(r.keys[i].rot instanceof XG.Quaternion)){var o=r.keys[i].rot;r.keys[i].rot=new XG.Quaternion(o[0],o[1],o[2],o[3])}for(var i=1;i<r.keys.length;i++)r.keys[i].time===r.keys[i-1].time&&(r.keys.splice(i,1),i--);for(var i=0;i<r.keys.length;i++)r.keys[i].index=i}e.initialized=!0}},XG.Animation.prototype.findRoot=function(){for(var e,t=this.data.hierarchy,a=0,r=t.length;r>a;a++){var i=t[a];if(-1===i.parent){e=i;break}}return e},XG.Animation.prototype.offsetPositionKeysForBone=function(e,t){for(var a=this.boneIndexMap[e],r=this.data.hierarchy[a].keys,i=0,o=r.length;o>i;i++){var n=r[i],s=n.pos;void 0!==s&&(s[0]+=t.x,s[1]+=t.y,s[2]+=t.z)}},XG.Animation.prototype.offsetRotationKeysForBone=function(e,t){for(var a=this.boneIndexMap[e],r=this.data.hierarchy[a].keys,i=0,o=r.length;o>i;i++){var n=r[i],s=n.rot;void 0!==s&&s.multiplySelf(t)}},XG.Animation.prototype.setKeysComponentValue=function(e,t,a,r){for(var i=0,o=e.keys.length;o>i;i++){var n=e.keys[i];n[t]&&(n[t][a]=r)}},XG.Animation.prototype.copyKeysToBoneRange=function(e,t,a){for(var r=this.data.hierarchy,i=e.data.hierarchy,o=t;a>o;o++)for(var n=i[o],s=r[o],l=0,h=n.keys.length;h>l;l++){var d=n.keys[l];s.keys[l]=d}},XG.AnimationIdCount=0,XG.Geometry=function(){this.id=XG.GeometryIdCount++,this.attributes={},this.attributesList=[],this.virtualAttributes={},this.virtualAttributesList=[],this.numPrimitives=0,this.numVertices=0,this.numInstances=0,this.numVisibleInstances=0,this.instanceCulled=!0,this.dynamic=!1,this.offsets=[],this.boundingBox=null,this.boundingSphere=null,this.morphTargets=[],this.morphColors=[]},XG.Geometry.prototype={constructor:XG.Geometry,addIndex:function(e,t,a){var r=new t(this.numPrimitives*a);this.addAttributeArray(e,r,a)},addAttribute:function(e,t,a){var r=new t(this.numVertices*a);this.addAttributeArray(e,r,a)},addInstancedAttribute:function(e,t,a,r){var i=new t(this.numInstances*a);this.addAttributeArray(e,i,a,r)},addVirtualAttribute:function(e){var t={name:e,mapped:null};this.virtualAttributes[e]=t,this.virtualAttributesList.push(t)},addUnattachedAttribute:function(e,t,a){var r=new t(this.numVertices*a),i={name:e,itemSize:a,numItems:r.length,array:r,buffer:null,type:XG.paramTypedArrayToXG(r),typeSize:r.BYTES_PER_ELEMENT,needsUpdate:!0,attached:!1,divisor:0};this.attributes[e]=i,this.attributesList.push(i)},addAttributeArray:function(e,t,a,r){void 0===r&&(r=0);var i={name:e,itemSize:a,numItems:t.length,array:t,buffer:null,type:XG.paramTypedArrayToXG(t),typeSize:t.BYTES_PER_ELEMENT,needsUpdate:!0,attached:!0,divisor:r};this.attributes[e]=i,this.attributesList.push(i)},setAttributeValue:function(e,t,a,r){var i=this.attributes[e];if(i){if(void 0===a&&(a=0),void 0===r&&(r=i.array.length),t instanceof XG.Color||t instanceof XG.Vector2||t instanceof XG.Vector3||t instanceof XG.Vector4||t instanceof XG.Quaternion)for(var o=a;r>o;o+=i.itemSize)t.copyIntoArray(i.array,o);i.needsUpdate=!0}},applyMatrix:function(e){var t,a;if(this.attributes.position&&(t=this.attributes.position.array),this.attributes.normal&&(a=this.attributes.normal.array),void 0!==t&&(e.multiplyVector3Array(t),this.attributes.position.needsUpdate=!0),void 0!==a){var r=new XG.Matrix3;r.getInverse(e).transpose(),r.multiplyVector3Array(a),this.normalizeAttribute("normal"),this.attributes.normal.needsUpdate=!0}},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new XG.Box3);var e=this.attributes.position.array;if(e){var t,a,r,i=this.boundingBox,o=i.min.data,n=i.max.data;e.length>=3&&(o[0]=n[0]=e[0],o[1]=n[1]=e[1],o[2]=n[2]=e[2]);for(var s=3,l=e.length;l>s;s+=3)t=e[s],a=e[s+1],r=e[s+2],t<o[0]?o[0]=t:t>n[0]&&(n[0]=t),a<o[1]?o[1]=a:a>n[1]&&(n[1]=a),r<o[2]?o[2]=r:r>n[2]&&(n[2]=r)}(void 0===e||0===e.length)&&(this.boundingBox.min.set(0,0,0),this.boundingBox.max.set(0,0,0))},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new XG.Sphere);var e=this.attributes.position.array;if(e){for(var t,a,r,i,o=0,n=0,s=e.length;s>n;n+=3)a=e[n],r=e[n+1],i=e[n+2],t=a*a+r*r+i*i,t>o&&(o=t);this.boundingSphere.radius=Math.sqrt(o)}},computeVertexNormals:function(){this.computeNormals("position","normal")},computeNormals:function(e,t){if(this.attributes[e]){var a,r,i,o,n=this.attributes[e].array.length;if(void 0===this.attributes[t])this.addAttributeArray(t,new Float32Array(n),3);else for(a=0,r=this.attributes[t].array.length;r>a;a++)this.attributes[t].array[a]=0;var s,l,h,d,c,u,f=this.attributes[e].array,p=this.attributes[t].array,m=new XG.Vector3,v=new XG.Vector3,g=new XG.Vector3,S=new XG.Vector3,G=new XG.Vector3,x=S.data;if(this.attributes.index){var M=this.attributes.index.array,y=this.offsets;for(i=0,o=y.length;o>i;++i){var X=y[i].start,D=y[i].count,_=y[i].index;for(a=X,r=X+D;r>a;a+=3)s=_+M[a],l=_+M[a+1],h=_+M[a+2],d=f[3*s],c=f[3*s+1],u=f[3*s+2],m.set(d,c,u),d=f[3*l],c=f[3*l+1],u=f[3*l+2],v.set(d,c,u),d=f[3*h],c=f[3*h+1],u=f[3*h+2],g.set(d,c,u),S.sub(g,v),G.sub(m,v),S.crossSelf(G),p[3*s]+=x[0],p[3*s+1]+=x[1],p[3*s+2]+=x[2],p[3*l]+=x[0],p[3*l+1]+=x[1],p[3*l+2]+=x[2],p[3*h]+=x[0],p[3*h+1]+=x[1],p[3*h+2]+=x[2]}}else for(a=0,r=f.length;r>a;a+=9)d=f[a],c=f[a+1],u=f[a+2],m.set(d,c,u),d=f[a+3],c=f[a+4],u=f[a+5],v.set(d,c,u),d=f[a+6],c=f[a+7],u=f[a+8],g.set(d,c,u),S.sub(g,v),G.sub(m,v),S.crossSelf(G),p[a]=x[0],p[a+1]=x[1],p[a+2]=x[2],p[a+3]=x[0],p[a+4]=x[1],p[a+5]=x[2],p[a+6]=x[0],p[a+7]=x[1],p[a+8]=x[2];this.normalizeAttribute(t),this.attributes[t].needsUpdate=!0}},normalizeAttribute:function(e,t,a){var r=this.attributes[e];if(r){var i=r.array;void 0===t&&(t=0),void 0===a&&(a=i.length);for(var o,n,s,l,h=t;a>h;h+=3)o=i[h],n=i[h+1],s=i[h+2],l=1/Math.sqrt(o*o+n*n+s*s),i[h]*=l,i[h+1]*=l,i[h+2]*=l}},scaleAttribute:function(e,t,a,r,i,o){var n=this.attributes[e];if(n){var s=n.array,l=n.itemSize;void 0===i&&(i=0),void 0===o&&(o=s.length);for(var h=i;o>h;h+=l)s[h]*=t,l>1&&void 0!==a&&(s[h+1]*=a),l>2&&void 0!==r&&(s[h+2]*=r)}},computeMorphNormals:function(){for(var e=0,t=this.morphTargets.length;t>e;e++){var a="mp_"+e,r="mn_"+e;this.computeNormals(a,r)}},computeTangents:function(){function e(e,t,a){c=r[3*e],u=r[3*e+1],f=r[3*e+2],p=r[3*t],m=r[3*t+1],v=r[3*t+2],g=r[3*a],S=r[3*a+1],G=r[3*a+2],x=o[2*e],M=o[2*e+1],y=o[2*t],X=o[2*t+1],D=o[2*a],_=o[2*a+1],w=p-c,A=g-c,C=m-u,T=S-u,b=v-f,P=G-f,L=y-x,E=D-x,F=X-M,R=_-M,U=1/(L*R-E*F),z.set((R*w-F*A)*U,(R*C-F*T)*U,(R*b-F*P)*U),W.set((L*A-E*w)*U,(L*T-E*C)*U,(L*P-E*b)*U),l[e].addSelf(z),l[t].addSelf(z),l[a].addSelf(z),h[e].addSelf(W),h[t].addSelf(W),h[a].addSelf(W)}function t(e){rt[0]=i[3*e],rt[1]=i[3*e+1],rt[2]=i[3*e+2],at.copy(tt),Q=l[e],$.copy(Q),$.subSelf(tt.multiplyScalar(tt.dot(Q))).normalize(),et.cross(at,Q),J=et.dot(h[e]),Y=0>J?-1:1,s[4*e]=it[0],s[4*e+1]=it[1],s[4*e+2]=it[2],s[4*e+3]=Y}if(void 0===this.attributes.index||void 0===this.attributes.position||void 0===this.attributes.normal||void 0===this.attributes.uv)return void console.warn("Missing required attributes (index, position, normal or uv) in Geometry.computeTangents()");var a=this.attributes.index.array,r=this.attributes.position.array,i=this.attributes.normal.array,o=this.attributes.uv.array,n=r.length/3;void 0===this.attributes.tangent&&this.addAttributeArray("tangent",new Float32Array(4*n),4);for(var s=this.attributes.tangent.array,l=[],h=[],d=0;n>d;d++)l[d]=new XG.Vector3,h[d]=new XG.Vector3;var c,u,f,p,m,v,g,S,G,x,M,y,X,D,_,w,A,C,T,b,P,L,E,F,R,U,N,I,B,O,k,V,H,z=new XG.Vector3,W=new XG.Vector3,j=this.offsets;for(B=0,O=j.length;O>B;++B){var q=j[B].start,K=j[B].count,Z=j[B].index;for(N=q,I=q+K;I>N;N+=3)k=Z+a[N],V=Z+a[N+1],H=Z+a[N+2],e(k,V,H)}var Y,Q,J,$=new XG.Vector3,et=new XG.Vector3,tt=new XG.Vector3,at=new XG.Vector3,rt=tt.data,it=$.data;for(B=0,O=j.length;O>B;++B){var q=j[B].start,K=j[B].count,Z=j[B].index;for(N=q,I=q+K;I>N;N+=3)k=Z+a[N],V=Z+a[N+1],H=Z+a[N+2],t(k),t(V),t(H)}this.attributes.tangent.needsUpdate=!0},mergeBatch:function(e,t){e.length!==t.length&&console.warn("XG.Geometry.mergeBatch: geometries and transforms arrays don't have the same sizes");var a=Math.min(e.length,t.length),r=e.slice(0),i=t.slice(0);0!==this.attributesList.length&&(r.unshift(this),i.unshift(new XG.Matrix4));for(var o={},n=0,s=0,l=0;a>l;l++){for(var h=r[l],d=0,c=h.attributesList.length;c>d;d++){var u=h.attributesList[d],f=u.name,p=u.type,m=u.array,v=u.itemSize;void 0===o[f]&&(o[f]={size:0,type:p,array:null,offset:0,itemSize:v}),o[f].size+=m.length}n+=h.numVertices,s+=h.numPrimitives}for(var f in o){var u=o[f],g=XG.paramXGToTypedArray(u.type);"index"===f&&n>65535&&(XG.elementIndexUintAvailable?g=Uint32Array:console.warn("XG.Geometry.mergeBatch: too many vertices for new merged indexed geometry")),u.array=new g(u.size)}for(var S=0,l=0;a>l;l++){for(var h=r[l],G=i[l],d=0,c=h.attributesList.length;c>d;d++){var u=h.attributesList[d],f=u.name,p=u.type,m=u.array,x=o[f],M=x.array,y=x.offset;if("index"===f&&x.type===XG.UnsignedIntType&&p===XG.UnsignedShortType)for(var X=0,D=m.length;D>X;X++)M[y+X]=m[X];else M.set(m,y);var _=y,w=y+m.length;if("position"===f&&G.multiplyVector3Array(M,_,w),"normal"===f){var A=new XG.Matrix3;A.getInverse(G).transpose(),A.multiplyVector3Array(_,w),this.normalizeAttribute("normal",_,w)}if("index"===f)for(var X=_;w>X;X++)M[X]+=S;x.offset+=m.length}S+=h.attributes.position.array.length/3}if(0===this.attributesList.length){for(var f in o){var u=o[f];this.addAttributeArray(f,u.array,u.itemSize)}this.offsets[0]={start:0,index:0,count:3*s}}else{for(var d=0,c=this.attributesList.length;c>d;d++){var C=this.attributesList[d],f=C.name,u=o[f];C.array=u.array,C.numItems=u.array.length,C.needsUpdate=!0}this.offsets[0].count=3*s}this.numVertices=n,this.numPrimitives=s},merge:function(e,t){if(this.numVertices+=e.numVertices,this.numPrimitives+=e.numPrimitives,0===this.attributesList.length){this.attributes={};for(var a=0,r=e.attributesList.length;r>a;a++){var i=e.attributesList[a],o=i.name,n=i.array,s=i.itemSize,l=i.type,h=XG.paramXGToTypedArray(i.type),d=new h(n);this.addAttributeArray(o,d,s)}this.offsets=[];var c=e.offsets;for(a=0,r=c.length;r>a;a++){var u=c[a].start,f=c[a].index,p=c[a].count;this.offsets[a]={start:u,index:f,count:p}}return void this.applyMatrix(t)}var m=this.attributes.position.array.length/3,v=e.attributes.position.array.length/3,g=Uint16Array;m+v>65535&&this.attributes.index&&(XG.elementIndexUintAvailable?g=Uint32Array:console.warn("XG.Geometry.merge: too many vertices for new merged indexed geometry"));for(var S=this.attributes.position?m:0,G=0,a=0,r=this.attributesList.length;r>a;a++){var x=this.attributesList[a],o=x.name,n=x.array,l=x.type,s=x.itemSize,M=e.attributes[o],y=M.array;if(void 0!==M)if(M.itemSize===s&&M.type===l||"index"===o&&M.itemSize===s){var X=n.length,D=n.length+y.length,h=XG.paramXGToTypedArray(l);if("index"===o&&h!==g){for(var _=new g(D),w=0;X>w;w++)_[w]=n[w];for(w=X;D>w;w++)_[w]=y[w-X];x.type=XG.paramTypedArrayToXG(_),x.typeSize=_.BYTES_PER_ELEMENT}else{var _=new h(D);_.set(n,0),_.set(y,X)}if("index"===o){G=y.length/3;for(var w=X;D>w;w++)_[w]+=S}if(t&&("position"===o&&t.multiplyVector3Array(_,X),"normal"===o)){var A=new XG.Matrix3;A.getInverse(t).transpose(),A.multiplyVector3Array(_,X),this.normalizeAttribute("normal",X)}x.array=_,x.numItems=D,x.needsUpdate=!0}else console.warn("XG.Geometry.merge: incompatible attribute ["+o+"]");else console.warn("XG.Geometry.merge: missing attribute ["+o+"]")}this.offsets.length>0&&(this.offsets[0].count+=3*G)}},XG.Geometry.prototype.clone=function(){for(var e=new XG.Geometry,t=this.attributesList,a=e.attributesList,r=e.attributes,i=0,o=t.length;o>i;++i){var n=t[i],s={name:n.name,itemSize:n.itemSize,numItems:n.numItems,array:n.array.slice(0),buffer:null,type:n.type,typeSize:n.typeSize,needsUpdate:!0,attached:n.attached,divisor:n.divisor};a[i]=s,r[s.name]=s}for(var l=this.virtualAttributesList,h=e.virtualAttributesList,d=e.virtualAttributes,i=0,o=l.length;o>i;++i){var n=l[i],s={name:n.name,mapped:n.mapped};h[i]=s,d[s.name]=s}e.numPrimitives=this.numPrimitives,e.numVertices=this.numVertices,e.numInstances=this.numInstances,e.numVisibleInstances=this.numVisibleInstances,e.instanceCulled=this.instanceCulled,e.dynamic=this.dynamic;for(var c=this.offsets,u=e.offsets,i=0,o=c.length;o>i;++i){var f=c[i].start,p=c[i].count,m=c[i].index;u.push({start:f,count:p,index:m})}this.boundingBox&&(e.boundingBox=this.boundingBox.clone()),this.boundingSphere&&(e.boundingSphere=this.boundingSphere.clone());for(var v=this.morphTargets,g=e.morphTargets,i=0,o=v.length;o>i;++i){var S=v[i],G={name:S.name,index:S.index};g[i]=G}for(var x=this.morphColors,M=e.morphColors,i=0,o=x.length;o>i;++i){var y=x[i],X={name:y.name,index:y.index,faceColors:y.faceColors};M[i]=X}return d.color.mapped&&(d.color.mapped=a[M[0].index]),e},XG.GeometryIdCount=0,XG.PlaneGeometry=function(e,t){XG.Geometry.call(this),this.width=e,this.height=t,this.numPrimitives=2,this.numVertices=4,this.addIndex("index",Uint16Array,3),this.addAttribute("position",Float32Array,3),this.addAttribute("normal",Float32Array,3),this.addAttribute("uv",Float32Array,2);var a=this.attributes.index.array,r=this.attributes.position.array,i=this.attributes.normal.array,o=this.attributes.uv.array,n=.5*this.width,s=.5*this.height;r[0]=-n,r[1]=-s,r[2]=0,r[3]=n,r[4]=-s,r[5]=0,r[6]=n,r[7]=s,r[8]=0,r[9]=-n,r[10]=s,r[11]=0,i[0]=0,i[1]=0,i[2]=1,i[3]=0,i[4]=0,i[5]=1,i[6]=0,i[7]=0,i[8]=1,i[9]=0,i[10]=0,i[11]=1,o[0]=0,o[1]=0,o[2]=1,o[3]=0,o[4]=1,o[5]=1,o[6]=0,o[7]=1,a[0]=0,a[1]=1,a[2]=3,a[3]=1,a[4]=2,a[5]=3,this.offsets.push({start:0,index:0,count:a.length})
  },XG.PlaneGeometry.prototype=Object.create(XG.Geometry.prototype),XG.TriangleGeometry=function(e,t){XG.Geometry.call(this),this.numPrimitives=1,this.numVertices=3,this.addAttribute("position",Float32Array,3),this.addAttribute("uv",Float32Array,2);var a=this.attributes.position.array,r=this.attributes.uv.array;a[0]=e[0][0],a[1]=e[0][1],a[2]=e[0][2],a[3]=e[1][0],a[4]=e[1][1],a[5]=e[1][2],a[6]=e[2][0],a[7]=e[2][1],a[8]=e[2][2],r[0]=t[0][0],r[1]=t[0][1],r[2]=t[1][0],r[3]=t[1][1],r[4]=t[2][0],r[5]=t[2][1]},XG.TriangleGeometry.prototype=Object.create(XG.Geometry.prototype),XG.HeightfieldGeometry=function(e,t,a,r,i){XG.Geometry.call(this),this.width=e,this.length=t,this.widthSegments=a||1,this.lengthSegments=r||1,this.numPrimitives=this.widthSegments*this.lengthSegments*2,this.numVertices=(this.widthSegments+1)*(this.lengthSegments+1);var o=Uint16Array;this.numVertices>65536&&(XG.elementIndexUintAvailable?o=Uint32Array:console.warn("XG.HeightfieldGeometry: too many vertices for 16 bit indices")),this.addIndex("index",o,3),this.addAttribute("position",Float32Array,3),this.addAttribute("normal",Float32Array,3),this.addAttribute("uv",Float32Array,2);for(var n=this.attributes.index.array,s=this.attributes.position.array,l=(this.attributes.normal.array,this.attributes.uv.array),h=.5*this.width,d=.5*this.length,c=this.width/this.widthSegments,u=this.length/this.lengthSegments,f=0,p=0,m=0,v=0;v<this.lengthSegments+1;v++)for(var g=0;g<this.widthSegments+1;g++){var S=g*c-h,G=v*u-d,x=0;void 0!==i&&(x=i[m],m+=1),s[f]=S,s[f+1]=x,s[f+2]=G,f+=3;var M=g/this.widthSegments,y=v/this.lengthSegments;l[p]=M,l[p+1]=y,p+=2}for(var X=0,D=this.widthSegments+1,v=0;v<this.lengthSegments;v++)for(var g=0;g<this.widthSegments;g++){var _=g+D*v,w=g+D*(v+1),A=g+1+D*(v+1),C=g+1+D*v;n[X]=_,n[X+1]=w,n[X+2]=C,n[X+3]=w,n[X+4]=A,n[X+5]=C,X+=6}this.offsets.push({start:0,index:0,count:n.length}),this.computeVertexNormals()},XG.HeightfieldGeometry.prototype=Object.create(XG.Geometry.prototype),XG.BoxGeometry=function(e,t,a){XG.Geometry.call(this),this.width=e,this.height=t,this.depth=a,this.numPrimitives=12,this.numVertices=24,this.addIndex("index",Uint16Array,3),this.addAttribute("position",Float32Array,3),this.addAttribute("normal",Float32Array,3),this.addAttribute("uv",Float32Array,2);var r=this.attributes.index.array,i=this.attributes.position.array,o=this.attributes.normal.array,n=this.attributes.uv.array,s=this.width/2,l=this.height/2,h=this.depth/2,d=0,c=0,u=0,f=0,p=function(e,t,a,s,l,h,p,m,v,g,S,G,x,M,y){i[d]=s,i[d+1]=l,i[d+2]=h,i[d+3]=p,i[d+4]=m,i[d+5]=v,i[d+6]=g,i[d+7]=S,i[d+8]=G,i[d+9]=x,i[d+10]=M,i[d+11]=y,o[d]=e,o[d+1]=t,o[d+2]=a,o[d+3]=e,o[d+4]=t,o[d+5]=a,o[d+6]=e,o[d+7]=t,o[d+8]=a,o[d+9]=e,o[d+10]=t,o[d+11]=a,n[c]=0,n[c+1]=0,n[c+2]=1,n[c+3]=0,n[c+4]=1,n[c+5]=1,n[c+6]=0,n[c+7]=1,r[u]=f,r[u+1]=f+1,r[u+2]=f+3,r[u+3]=f+1,r[u+4]=f+2,r[u+5]=f+3,d+=12,c+=8,u+=6,f+=4};p(1,0,0,s,-l,h,s,-l,-h,s,l,-h,s,l,h),p(-1,0,0,-s,-l,-h,-s,-l,h,-s,l,h,-s,l,-h),p(0,1,0,-s,l,h,s,l,h,s,l,-h,-s,l,-h),p(0,-1,0,s,-l,h,-s,-l,h,-s,-l,-h,s,-l,-h),p(0,0,1,-s,-l,h,s,-l,h,s,l,h,-s,l,h),p(0,0,-1,s,-l,-h,-s,-l,-h,-s,l,-h,s,l,-h),this.offsets.push({start:0,index:0,count:r.length})},XG.BoxGeometry.prototype=Object.create(XG.Geometry.prototype),XG.SphereGeometry=function(e,t,a,r,i,o,n){XG.Geometry.call(this),this.radius=e||50,this.widthSegments=Math.max(3,Math.floor(t)||8),this.heightSegments=Math.max(2,Math.floor(a)||6),r=void 0!==r?r:0,i=void 0!==i?i:2*Math.PI,o=void 0!==o?o:0,n=void 0!==n?n:Math.PI,this.numPrimitives=this.heightSegments*this.widthSegments*2,this.numVertices=(this.heightSegments+1)*(this.widthSegments+1);var s=Uint16Array;this.numVertices>65536&&(XG.elementIndexUintAvailable?s=Uint32Array:console.warn("XG.SphereGeometry: too many vertices for 16 bit indices")),this.addIndex("index",s,3),this.addAttribute("position",Float32Array,3),this.addAttribute("normal",Float32Array,3),this.addAttribute("uv",Float32Array,2);var l,h,d=this.attributes.index.array,c=this.attributes.position.array,u=this.attributes.normal.array,f=this.attributes.uv.array,p=0,m=0,v=new XG.Vector3;for(h=0;h<=this.heightSegments;h++)for(l=0;l<=this.widthSegments;l++){var g=l/this.widthSegments,S=h/this.heightSegments,G=-this.radius*Math.cos(r+g*i)*Math.sin(o+S*n),x=this.radius*Math.cos(o+S*n),M=this.radius*Math.sin(r+g*i)*Math.sin(o+S*n);c[p]=G,c[p+1]=x,c[p+2]=M,v.set(G,x,M).normalize(),u[p]=v.data[0],u[p+1]=v.data[1],u[p+2]=v.data[2],p+=3,f[m]=g,f[m+1]=1-S,m+=2}for(p=0,h=0;h<this.heightSegments;h++)for(l=0;l<this.widthSegments;l++){var y=h*(this.widthSegments+1)+(l+1),X=h*(this.widthSegments+1)+l,D=(h+1)*(this.widthSegments+1)+l,_=(h+1)*(this.widthSegments+1)+(l+1);d[p]=y,d[p+1]=X,d[p+2]=_,d[p+3]=X,d[p+4]=D,d[p+5]=_,p+=6}this.offsets.push({start:0,index:0,count:d.length}),this.boundingSphere=new XG.Sphere(new XG.Vector3,e)},XG.SphereGeometry.prototype=Object.create(XG.Geometry.prototype),XG.CylinderGeometry=function(e,t,a,r,i,o){XG.Geometry.call(this),e=void 0!==e?e:20,t=void 0!==t?t:20,a=void 0!==a?a:100;var n=a/2,s=r||8,l=i||1,h=e>0&&!o,d=t>0&&!o;this.numPrimitives=l*s*2+s*(1*h+1*d),this.numVertices=(l+1)*(s+1)+(2*s+1)*(1*h+1*d),this.addIndex("index",Uint16Array,3),this.addAttribute("position",Float32Array,3),this.addAttribute("normal",Float32Array,3),this.addAttribute("uv",Float32Array,2);var c,u,f=this.attributes.index.array,p=this.attributes.position.array,m=this.attributes.normal.array,v=this.attributes.uv.array,g=0,S=0,G=0;for(u=0;l>=u;u++){var x=u/l,M=x*(t-e)+e;for(c=0;s>=c;c++){var y=c/s,X=M*Math.sin(y*Math.PI*2),D=-x*a+n,_=M*Math.cos(y*Math.PI*2);p[g]=X,p[g+1]=D,p[g+2]=_,g+=3,v[G]=y,v[G+1]=1-x,G+=2}}var w,A,C,T,b,P,L,E,F=(t-e)/a,R=new XG.Vector3,U=new XG.Vector3;for(S=0,c=0;s>c;c++)for(0!==e?(L=c,E=c+1):(L=s+1+c,E=s+1+(c+1)),L*=3,E*=3,w=p[L],A=p[L+1],C=p[L+2],T=p[E],b=p[E+1],P=p[E+2],R.set(w,A,C),U.set(T,b,P),R.setY(Math.sqrt(R.data[0]*R.data[0]+R.data[2]*R.data[2])*F).normalize(),U.setY(Math.sqrt(U.data[0]*U.data[0]+U.data[2]*U.data[2])*F).normalize(),u=0;l>u;u++){var N=u*(s+1)+c,I=(u+1)*(s+1)+c,B=(u+1)*(s+1)+(c+1),O=u*(s+1)+(c+1);f[S]=N,f[S+1]=I,f[S+2]=O,f[S+3]=I,f[S+4]=B,f[S+5]=O,S+=6,m[3*N]=R.data[0],m[3*N+1]=R.data[1],m[3*N+2]=R.data[2],m[3*I]=R.data[0],m[3*I+1]=R.data[1],m[3*I+2]=R.data[2],m[3*B]=U.data[0],m[3*B+1]=U.data[1],m[3*B+2]=U.data[2],m[3*O]=U.data[0],m[3*O+1]=U.data[1],m[3*O+2]=U.data[2]}if(!o&&e>0){var B=g/3;for(p[g]=0,p[g+1]=n,p[g+2]=0,m[g]=0,m[g+1]=1,m[g+2]=0,g+=3,v[G]=.5,v[G+1]=.5,G+=2,c=0;s>c;c++){var N=g/3,I=N+1;w=3*c,T=3*(c+1),p[g]=p[w],p[g+1]=p[w+1],p[g+2]=p[w+2],p[g+3]=p[T],p[g+4]=p[T+1],p[g+5]=p[T+2],m[g]=0,m[g+1]=1,m[g+2]=0,m[g+3]=0,m[g+4]=1,m[g+5]=0,g+=6,f[S]=N,f[S+1]=I,f[S+2]=B,S+=3;var k=c/s,V=(c+1)/s;v[G]=k,v[G+1]=1,v[G+2]=V,v[G+3]=1,G+=4}}if(!o&&t>0){var B=g/3;for(p[g]=0,p[g+1]=-n,p[g+2]=0,m[g]=0,m[g+1]=-1,m[g+2]=0,g+=3,v[G]=.5,v[G+1]=.5,G+=2,c=0;s>c;c++){var N=g/3,I=N+1;w=3*(c+1+u*(s+1)),T=3*(c+u*(s+1)),p[g]=p[w],p[g+1]=p[w+1],p[g+2]=p[w+2],p[g+3]=p[T],p[g+4]=p[T+1],p[g+5]=p[T+2],m[g]=0,m[g+1]=-1,m[g+2]=0,m[g+3]=0,m[g+4]=-1,m[g+5]=0,g+=6,f[S]=N,f[S+1]=I,f[S+2]=B,S+=3;var k=c/s,V=(c+1)/s;v[G]=k,v[G+1]=0,v[G+2]=V,v[G+3]=0,G+=4}}this.offsets.push({start:0,index:0,count:f.length})},XG.CylinderGeometry.prototype=Object.create(XG.Geometry.prototype),XG.CapsuleGeometry=function(e,t,a){XG.Geometry.call(this);var r=new XG.CylinderGeometry(e,e,t,a,1,!0),i=new XG.SphereGeometry(e,a,.5*a,0,2*Math.PI,0,.5*Math.PI),o=new XG.Vector3(0,.5*t,0),n=new XG.Vector3(0,.5*-t,0),s=new XG.Matrix4;s.makeTranslation(o);var l=new XG.Matrix4;l.makeRotationX(Math.PI);var h=new XG.Matrix4;h.makeTranslation(n),h.multiplySelf(l),r.merge(i,s),r.merge(i,h),r.computeBoundingSphere(),this.attributes=r.attributes,this.attributesList=r.attributesList,this.virtualAttributes=r.virtualAttributes,this.virtualAttributesList=r.virtualAttributesList,this.numPrimitives=r.numPrimitives,this.numVertices=r.numVertices,this.offsets=r.offsets,this.boundingBox=r.boundingBox,this.boundingSphere=r.boundingSphere},XG.CapsuleGeometry.prototype=Object.create(XG.Geometry.prototype),XG.RandomGeometry=function(e){XG.Geometry.call(this),void 0===e&&(e={}),this.shape=void 0!==e.shape?e.shape:"sphere",this.customCallback=void 0!==e.callback?e.callback:function(){},this.radius=void 0!==e.radius?e.radius:1,this.width=void 0!==e.width?e.width:1,this.height=void 0!==e.height?e.height:1,this.depth=void 0!==e.depth?e.depth:1,this.useSeed=void 0!==e.useSeed?e.useSeed:!1,this.seed=void 0!==e.seed?e.seed:Math.random(),this.numPrimitives=0,this.numVertices=void 0!==e.vertices?e.vertices:1e3,this.addAttribute("position",Float32Array,3),this.refresh(this.seed)},XG.RandomGeometry.prototype=Object.create(XG.Geometry.prototype),XG.RandomGeometry.prototype.refresh=function(e){this.seed=e;var t=this.attributes.position.array,a=this.radius,r=this.width,i=this.height,o=this.depth;if(this.useSeed){Math.seedrandom(this.seed);var n=Math.srandom}else var n=Math.random;var s,l=function(e){var t=2*n()-1,r=n()*Math.PI*2,i=Math.sqrt(1-t*t);e.x=a*i*Math.cos(r),e.y=a*i*Math.sin(r),e.z=a*t},h=function(e){for(var t=0,r=.5,i=u;i;r*=.5,i>>=1)1&i&&(t+=r);t=2*t-1;var o=(u+.5)/f,n=2*o*Math.PI,s=Math.sqrt(1-t*t);e.x=a*s*Math.cos(n),e.y=a*s*Math.sin(n),e.z=a*t,u+=1},d=function(e){var t=(n()-.5)*a,r=(n()-.5)*a,i=(n()-.5)*a,o=n()*a,s=1/Math.sqrt(t*t+r*r+i*i);e.x=o*t*s,e.y=o*r*s,e.z=o*i*s},c=function(e){e.x=(n()-.5)*r,e.y=(n()-.5)*i,e.z=(n()-.5)*o};"sphereSurface"===this.shape?s=l:"sphereHammersley"===this.shape?s=h:"sphere"===this.shape?s=d:"box"===this.shape?s=c:"custom"===this.shape&&(s=this.customCallback);for(var u=0,f=this.numVertices,p=0,m={x:0,y:0,z:0},v=0,g=this.numVertices;g>v;v++)s(m),t[p]=m.x,t[p+1]=m.y,t[p+2]=m.z,p+=3;this.attributes.position.needsUpdate=!0},XG.SpriteGeometry=function(e){XG.Geometry.call(this),this.numSprites=e,this.numPrimitives=2*e,this.numVertices=4*e;var t=Uint16Array;this.numVertices>65536&&(t=XG.elementIndexUintAvailable?Uint32Array:null),null===t&&console.error("XG.SpriteGeometry: 32 bit indices not supported (geometry has",e,"sprites)"),this.addIndex("index",t,3),this.addAttribute("position",Float32Array,3),this.addAttribute("offset",Float32Array,3),this.addAttribute("color",Float32Array,3),this.addAttribute("uv",Float32Array,2),this.addAttribute("scale",Float32Array,2);for(var a=this.attributes.index.array,r=this.attributes.position.array,i=this.attributes.offset.array,o=this.attributes.color.array,n=this.attributes.uv.array,s=this.attributes.scale.array,l=0,h=0,d=0,c=0,u=function(){var e=0,t=0,u=0,f=1,p=1,m=1,v=1,g=1,S=0,G=0,x=1,M=0,y=1,X=1,D=0,_=1;r[l]=-.5,r[l+1]=-.5,r[l+2]=0,r[l+3]=.5,r[l+4]=-.5,r[l+5]=0,r[l+6]=.5,r[l+7]=.5,r[l+8]=0,r[l+9]=-.5,r[l+10]=.5,r[l+11]=0,i[l]=e,i[l+1]=t,i[l+2]=u,i[l+3]=e,i[l+4]=t,i[l+5]=u,i[l+6]=e,i[l+7]=t,i[l+8]=u,i[l+9]=e,i[l+10]=t,i[l+11]=u,o[l]=f,o[l+1]=p,o[l+2]=m,o[l+3]=f,o[l+4]=p,o[l+5]=m,o[l+6]=f,o[l+7]=p,o[l+8]=m,o[l+9]=f,o[l+10]=p,o[l+11]=m,s[c]=v,s[c+1]=g,s[c+2]=v,s[c+3]=g,s[c+4]=v,s[c+5]=g,s[c+6]=v,s[c+7]=g,n[c]=S,n[c+1]=G,n[c+2]=x,n[c+3]=M,n[c+4]=y,n[c+5]=X,n[c+6]=D,n[c+7]=_,a[d]=h,a[d+1]=h+1,a[d+2]=h+2,a[d+3]=h,a[d+4]=h+2,a[d+5]=h+3,l+=12,c+=8,d+=6,h+=4},f=0;f<this.numSprites;f++)u();this.offsets.push({start:0,index:0,count:a.length})},XG.SpriteGeometry.prototype=Object.create(XG.Geometry.prototype),XG.SpriteGeometry.prototype.setSpritePosition=function(e,t,a,r){var i=this.attributes.offset.array,o=12*e;i[o]=t,i[o+1]=a,i[o+2]=r,i[o+3]=t,i[o+4]=a,i[o+5]=r,i[o+6]=t,i[o+7]=a,i[o+8]=r,i[o+9]=t,i[o+10]=a,i[o+11]=r},XG.SpriteGeometry.prototype.setSpriteColor=function(e,t,a,r){var i=this.attributes.color.array,o=12*e;i[o]=t,i[o+1]=a,i[o+2]=r,i[o+3]=t,i[o+4]=a,i[o+5]=r,i[o+6]=t,i[o+7]=a,i[o+8]=r,i[o+9]=t,i[o+10]=a,i[o+11]=r},XG.SpriteGeometry.prototype.setSpriteScale=function(e,t,a){var r=this.attributes.scale.array,i=8*e;r[i]=t,r[i+1]=a,r[i+2]=t,r[i+3]=a,r[i+4]=t,r[i+5]=a,r[i+6]=t,r[i+7]=a},XG.SpriteGeometry.prototype.setSpriteUV=function(e,t,a,r,i,o,n,s,l){var h=this.attributes.uv.array,d=8*e;h[d]=t,h[d+1]=a,h[d+2]=o,h[d+3]=n,h[d+4]=s,h[d+5]=l,h[d+6]=r,h[d+7]=i},XG.SpriteGeometry.prototype.computeBoundingSphere=function(){null===this.boundingSphere&&(this.boundingSphere=new XG.Sphere);var e=this.attributes.position.array,t=this.attributes.offset.array,a=this.attributes.scale.array;if(e){for(var r,i,o,n,s,l,h,d,c,u,f,p,m=0,v=0,g=0,S=e.length;S>v;v+=3,g+=2)s=e[v],l=e[v+1],h=e[v+2],d=t[v],c=t[v+1],u=t[v+2],f=a[g],p=a[g+1],i=s*f+d,o=l*p+c,n=h+u,r=i*i+o*o+n*n,r>m&&(m=r);this.boundingSphere.radius=Math.sqrt(m)}},XG.SpriteGeometry.prototype.setSpriteTexture=function(e,t,a){var r=a.width,i=a.height,o=(a.base,t.width),n=t.height,s=t.x,l=t.y,h=s/r,d=(i-l)/i,c=(s+o)/r,u=(i-(l+n))/i,f=(s+o)/r,p=(i-l)/i,m=s/r,v=(i-(l+n))/i,g=o,S=n,G=this.attributes.scale.array,x=8*e,M=G[x],y=G[x+1];M=g*M,y=S*y,this.setSpriteUV(e,m,v,h,d,c,u,f,p),this.setSpriteScale(e,M,y)},XG.SpriteGeometry.prototype.setText=function(e,t,a,r,i,o){void 0===i&&(i={});for(var n=void 0!==i.wordWrap?i.wordWrap:!0,s=void 0!==i.charWrap?i.charWrap:!1,l=i.font,h=i.lineLength,d=i.lineHeight,c=i.fontSize,u=Math.min(e.length,this.numSprites),f=d*l.base*c,p={width:l.width,height:l.height,base:l.base},m=function(e){return" "===e||"	"===e||"\n"===e||"\r"===e||"\f"===e||""===e||null===e},v=function(t,a){for(var r=a,i=t,o=e[i],n=e[i+1];u>i&&!m(o);){var s=o.charCodeAt(0),h=l.chars[s],d=m(n)||void 0===n;if(void 0===h)r+=g;else{var f=h.xadvance*c,p=h.xoffset*c;if(d){var v=h.width*c;r+=p+v}else r+=p+f}i+=1,o=e[i],n=e[i+1]}return r},g=l.base,S=0,G=0,x=!0,M=null,y=1/0,X=1/0,D=-1/0,_=-1/0,w=0;u>w;w++){var A=e[w];if("\n"!==A){var C=A.charCodeAt(0),T=l.chars[C];if(void 0!==T){if(n&&(x=m(M)&&!m(A))){var b=v(w,S);b>h&&(G-=f,S=0)}var P=T.width*c,L=T.height*c,E=T.xadvance*c,F=T.xoffset*c,R=T.yoffset*c;if(s){var U=S+F+P;U>h&&(G-=f,S=0)}var N=t+.5*P+S+F,I=a+.5*L+G+R-L,B=r;this.setSpriteScale(w,c,c),this.setSpritePosition(w,N,I,B),this.setSpriteTexture(w,T,p);var O=S+F,k=O+P,V=G+R,H=V-L;y>O&&(y=O),k>D&&(D=k),X>V&&(X=V),H>_&&(_=H),S+=E,M=A}else S+=g*c,M=A,this.setSpriteScale(w,0,0)}else G-=f,S=0,M=A,this.setSpriteScale(w,0,0)}return void 0===o&&(o={width:0,height:0,minx:1/0,maxx:-1/0,miny:1/0,maxy:-1/0}),o.width=D-y,o.height=_-X,o.minx=y,o.miny=X,o.maxx=D,o.maxy=_,o},XG.GeometryUtils={center:function(e){for(var t=new XG.Box3,a=0,r=e.length;r>a;a++){var i=e[a];i.computeBoundingBox(),t.add(i.boundingBox)}var o=t.min.clone();o.addSelf(t.max),o.multiplyScalar(-.5);var n=new XG.Matrix4;n.makeTranslation(o);for(var a=0,r=e.length;r>a;a++){var i=e[a];i.applyMatrix(n)}},generateTerrainHeights:function(e,t,a,r){if(void 0!==r){Math.seedrandom(r);var i=Math.srandom}else var i=Math.random;for(var o=function(t,a,r){var i=a*s+t;e[i]=r},n=function(t,a){var r=a*s+t;return e[r]},s=t+1,l=t;l>=2;l/=2){var h=l/2;a/=2;for(var d=0;t>d;d+=l)for(var c=0;t>c;c+=l){var u=n(d,c)+n(d+l,c)+n(d,c+l)+n(d+l,c+l);u/=4,u+=2*a*i()-a,o(d+h,c+h,u)}for(var d=0;t>d;d+=h)for(var c=(d+h)%l;t>c;c+=l){var u=n((d-h+s)%s,c)+n((d+h)%s,c)+n(d,(c+h)%s)+n(d,(c-h+s)%s);u/=4,u+=2*a*i()-a,o(d,c,u),0===d&&o(t,c,u),0===c&&o(d,t,u)}}},getTerrainHeightsRange:function(e){for(var t=1/0,a=-1/0,r=0,i=e.length;i>r;r++){var o=e[r];t>o&&(t=o),o>a&&(a=o)}return{min:t,max:a}},offsetTerrainHeights:function(e,t){for(var a=0,r=e.length;r>a;a++)e[a]+=t},centerTerrainHeights:function(e){var t=XG.GeometryUtils.getTerrainHeightsRange(e),a=(t.min+t.max)*-.5;XG.GeometryUtils.offsetTerrainHeights(e,a)},floorTerrainHeights:function(e){var t=XG.GeometryUtils.getTerrainHeightsRange(e),a=-t.min;XG.GeometryUtils.offsetTerrainHeights(e,a)},blendTerrainHeights:function(e,t,a,r){for(var i=0,o=e.length;o>i;i++){var n=e[i],s=t[i],l=Math.floor(i/a),h=i%a,d=r(h,l);e[i]=d*n+(1-d)*s}},addParticleAttributes:function(e){e.addAttribute("velocitySpinStart",Float32Array,4),e.addAttribute("accelerationSpinSpeed",Float32Array,4),e.addAttribute("startSizeEndSizeStartTimeLifeTime",Float32Array,4)},setParticleAttributes:function(e,t){var a=e.attributes.velocitySpinStart.array,r=e.attributes.accelerationSpinSpeed.array,i=e.attributes.startSizeEndSizeStartTimeLifeTime.array,o={x:0,y:0,z:0},n={x:0,y:0,z:0},s={start:0,speed:0},l={start:0,end:0},h={start:0,life:0},d={velocity:o,acceleration:n,spin:s,size:l,time:h};(a.length!==r.length||a.length!==i.length||i.length!==r.length)&&console.error("XG.GeometryUtils.setParticleAttributes: attributes lengths mismatch");for(var c=0,u=a.length;u>c;c+=4)t(d),a[c]=o.x,a[c+1]=o.y,a[c+2]=o.z,a[c+3]=s.start,r[c]=n.x,r[c+1]=n.y,r[c+2]=n.z,r[c+3]=s.speed,i[c]=l.start,i[c+1]=l.end,i[c+2]=h.start,i[c+3]=h.life}},XG.Node=function(){this.id=XG.NodeIdCount++,this.name="",this.properties={},this.parent=void 0,this.children=[],this.transformChildren=!0,this.position=new XG.Vector3,this.rotation=new XG.Vector3,this.scale=new XG.Vector3(1,1,1),this.up=new XG.Vector3(0,1,0),this.eulerOrder=XG.Node.defaultEulerOrder,this.renderDepth=null,this.rotationAutoUpdate=!0,this.matrix=new XG.Matrix4,this.matrixWorld=new XG.Matrix4,this.matrixAutoUpdate=!0,this.matrixWorldNeedsUpdate=!0,this.quaternion=new XG.Quaternion,this.useQuaternion=!1,this.visible=!0,this.enabled=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0},XG.Node.prototype={constructor:XG.Node,applyMatrix:function(e){this.matrix.multiply(e,this.matrix),this.scale.getScaleFromMatrix(this.matrix);var t=(new XG.Matrix4).extractRotation(this.matrix);this.rotation.setEulerFromRotationMatrix(t,this.eulerOrder),this.position.getPositionFromMatrix(this.matrix)},translate:function(e,t){this.matrix.rotateAxis(t),this.position.addSelf(t.multiplyScalar(e))},translateX:function(e){this.translate(e,XG.Vector3.xAxis.clone())},translateY:function(e){this.translate(e,XG.Vector3.yAxis.clone())},translateZ:function(e){this.translate(e,XG.Vector3.zAxis.clone())},localToWorld:function(e){return this.matrixWorld.multiplyVector3(e)},worldToLocal:function(e){return XG.Node.__m1.getInverse(this.matrixWorld).multiplyVector3(e)},lookAt:function(e){this.matrix.lookAt(e,this.position,this.up),this.rotationAutoUpdate&&(this.useQuaternion===!1?this.rotation.setEulerFromRotationMatrix(this.matrix,this.eulerOrder):this.quaternion.copy(this.matrix.decompose()[1]))},add:function(e){if(e===this)return void console.warn("XG.Node.add: A node can't be added as a child of itself.");if(e instanceof XG.Node){void 0!==e.parent&&e.parent.remove(e),e.parent=this,this.children.push(e);var t=this.getTopParent();void 0!==t&&t instanceof XG.Scene&&t.__addNode(e)}},remove:function(e){var t=this.children.indexOf(e);if(-1!==t){e.parent=void 0,this.children.splice(t,1);var a=this.getTopParent();void 0!==a&&a instanceof XG.Scene&&a.__removeNode(e)}},traverse:function(e){e(this);for(var t=this.children,a=0,r=t.length;r>a;a++)t[a].traverse(e)},getChildByName:function(e,t){for(var a=0,r=this.children.length;r>a;a++){var i=this.children[a];if(i.name===e)return i;if(t===!0&&(i=i.getChildByName(e,t),void 0!==i))return i}return void 0},getDescendants:function(e){void 0===e&&(e=[]),Array.prototype.push.apply(e,this.children);for(var t=0,a=this.children.length;a>t;t++)this.children[t].getDescendants(e);return e},getTopParent:function(){for(var e=this;void 0!==e.parent;)e=e.parent;return e},updateMatrix:function(){this.useQuaternion===!1&&this.quaternion.setFromEuler(this.rotation,this.eulerOrder),this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0},updateMatrixWorld:function(e){this.matrixAutoUpdate===!0&&this.updateMatrix(),(this.matrixWorldNeedsUpdate===!0||e===!0)&&(this.parent&&this.parent.transformChildren?this.matrixWorld.multiply(this.parent.matrixWorld,this.matrix):this.matrixWorld.copy(this.matrix),this.matrixWorldNeedsUpdate=!1,e=!0);for(var t=this.children,a=0,r=t.length;r>a;a++)t[a].updateMatrixWorld(e)},clone:function(e){void 0===e&&(e=new XG.Node),e.name=this.name,e.up.copy(this.up),e.position.copy(this.position),e.rotation instanceof XG.Vector3&&e.rotation.copy(this.rotation),e.eulerOrder=this.eulerOrder,e.scale.copy(this.scale),e.renderDepth=this.renderDepth,e.rotationAutoUpdate=this.rotationAutoUpdate,e.matrix.copy(this.matrix),e.matrixWorld.copy(this.matrixWorld),e.matrixAutoUpdate=this.matrixAutoUpdate,e.matrixWorldNeedsUpdate=this.matrixWorldNeedsUpdate,e.quaternion.copy(this.quaternion),e.useQuaternion=this.useQuaternion,e.visible=this.visible,e.castShadow=this.castShadow,e.receiveShadow=this.receiveShadow,e.frustumCulled=this.frustumCulled;for(var t=0;t<this.children.length;t++){var a=this.children[t];e.add(a.clone())}return e}},XG.Node.__m1=new XG.Matrix4,XG.Node.defaultEulerOrder=XG.xyzOrder,XG.NodeIdCount=0,XG.Bone=function(e){XG.Node.call(this),this.skin=e,this.skinMatrix=new XG.Matrix4},XG.Bone.prototype=Object.create(XG.Node.prototype),XG.Bone.prototype.update=function(e,t){this.matrixAutoUpdate&&(t|=this.updateMatrix()),(t||this.matrixWorldNeedsUpdate)&&(e?this.skinMatrix.multiply(e,this.matrix):this.skinMatrix.copy(this.matrix),this.matrixWorldNeedsUpdate=!1,t=!0);for(var a=0,r=this.children.length;r>a;a++)this.children[a].update(this.skinMatrix,t)},XG.Scene=function(){XG.Node.call(this),this.fog=null,this.heightFog=null,this.matrixAutoUpdate=!1,this.transformChildren=!1,this.__objects=[],this.__lights=[],this.__objectsAdded=[],this.__objectsRemoved=[]},XG.Scene.prototype=Object.create(XG.Node.prototype),XG.Scene.prototype.__addNode=function(e){if(e instanceof XG.Light)-1===this.__lights.indexOf(e)&&this.__lights.push(e),e.target&&void 0===e.target.parent&&this.add(e.target);else if(!(e instanceof XG.Camera||e instanceof XG.Bone)&&-1===this.__objects.indexOf(e)){this.__objects.push(e),this.__objectsAdded.push(e);var t=this.__objectsRemoved.indexOf(e);-1!==t&&this.__objectsRemoved.splice(t,1)}for(var a=0;a<e.children.length;a++)this.__addNode(e.children[a])},XG.Scene.prototype.__removeNode=function(e){if(e instanceof XG.Light){var t=this.__lights.indexOf(e);-1!==t&&this.__lights.splice(t,1)}else if(!(e instanceof XG.Camera)){var t=this.__objects.indexOf(e);if(-1!==t){this.__objects.splice(t,1),this.__objectsRemoved.push(e);var a=this.__objectsAdded.indexOf(e);-1!==a&&this.__objectsAdded.splice(a,1)}}for(var r=0;r<e.children.length;r++)this.__removeNode(e.children[r])},XG.Gyroscope=function(){XG.Node.call(this)},XG.Gyroscope.prototype=Object.create(XG.Node.prototype),XG.Gyroscope.prototype.updateMatrixWorld=function(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.parent?(this.matrixWorld.multiply(this.parent.matrixWorld,this.matrix),this.matrixWorld.decompose(this.translationWorld,this.rotationWorld,this.scaleWorld),this.matrix.decompose(this.translationObject,this.rotationObject,this.scaleObject),this.matrixWorld.compose(this.translationWorld,this.rotationObject,this.scaleWorld)):this.matrixWorld.copy(this.matrix),this.matrixWorldNeedsUpdate=!1,e=!0);for(var t=0,a=this.children.length;a>t;t++)this.children[t].updateMatrixWorld(e)},XG.Gyroscope.prototype.translationWorld=new XG.Vector3,XG.Gyroscope.prototype.translationObject=new XG.Vector3,XG.Gyroscope.prototype.rotationWorld=new XG.Quaternion,XG.Gyroscope.prototype.rotationObject=new XG.Quaternion,XG.Gyroscope.prototype.scaleWorld=new XG.Vector3,XG.Gyroscope.prototype.scaleObject=new XG.Vector3,XG.Mesh=function(e,t){XG.Node.call(this),this.geometries=e instanceof Array?e:e instanceof XG.Geometry?[e]:[],this.materials=t instanceof Array?t:t instanceof XG.Material?[t]:[];for(var a=0,r=this.geometries.length;r>a;a++){var i=this.geometries[a];null===i.boundingSphere&&i.computeBoundingSphere()}},XG.Mesh.prototype=Object.create(XG.Node.prototype),XG.Mesh.prototype.clone=function(e){return void 0===e&&(e=new XG.Mesh(this.geometries,this.materials)),XG.Node.prototype.clone.call(this,e),e},XG.MorphMesh=function(e,t){XG.Mesh.call(this,e,t),this.animationsMap={},this.animationsList=[];var a=this.geometries[0],r=a.morphTargets.length,i="__default",o=0,n=r-1,s=r/1;this.createAnimation(i,o,n,s),this.setAnimationWeight(i,1),this.morphTargetInfluences=new Float32Array(a.morphTargets.length)},XG.MorphMesh.prototype=Object.create(XG.Mesh.prototype),XG.MorphMesh.prototype.createAnimation=function(e,t,a,r){var i={startFrame:t,endFrame:a,length:a-t+1,fps:r,duration:(a-t)/r,lastFrame:0,currentFrame:0,active:!1,time:0,direction:1,weight:1,directionBackwards:!1,mirroredLoop:!1};this.animationsMap[e]=i,this.animationsList.push(i)},XG.MorphMesh.prototype.autoCreateAnimations=function(e){for(var t,a=/([a-z]+)(\d+)/,r={},i=this.geometries[0],o=0,n=i.morphTargets.length;n>o;o++){var s=i.morphTargets[o],l=s.name.match(a);if(l&&l.length>1){{var h=l[1];l[2]}r[h]||(r[h]={start:1/0,end:-1/0});var d=r[h];o<d.start&&(d.start=o),o>d.end&&(d.end=o),t||(t=h)}}for(var h in r){var d=r[h];this.createAnimation(h,d.start,d.end,e)}this.firstAnimation=t},XG.MorphMesh.prototype.setAnimationDirectionForward=function(e){var t=this.animationsMap[e];t&&(t.direction=1,t.directionBackwards=!1)},XG.MorphMesh.prototype.setAnimationDirectionBackward=function(e){var t=this.animationsMap[e];t&&(t.direction=-1,t.directionBackwards=!0)},XG.MorphMesh.prototype.setAnimationFPS=function(e,t){var a=this.animationsMap[e];a&&(a.fps=t,a.duration=(a.end-a.start)/a.fps)},XG.MorphMesh.prototype.setAnimationDuration=function(e,t){var a=this.animationsMap[e];a&&(a.duration=t,a.fps=(a.end-a.start)/a.duration)},XG.MorphMesh.prototype.setAnimationWeight=function(e,t){var a=this.animationsMap[e];a&&(a.weight=t)},XG.MorphMesh.prototype.setAnimationTime=function(e,t){var a=this.animationsMap[e];a&&(a.time=t)},XG.MorphMesh.prototype.getAnimationTime=function(e){var t=0,a=this.animationsMap[e];return a&&(t=a.time),t},XG.MorphMesh.prototype.getAnimationDuration=function(e){var t=-1,a=this.animationsMap[e];return a&&(t=a.duration),t},XG.MorphMesh.prototype.playAnimation=function(e){var t=this.animationsMap[e];t?(t.time=0,t.active=!0):console.warn("animation["+e+"] undefined")},XG.MorphMesh.prototype.stopAnimation=function(e){var t=this.animationsMap[e];t&&(t.active=!1)},XG.MorphMesh.prototype.update=function(e){for(var t=0,a=this.animationsList.length;a>t;t++){var r=this.animationsList[t];if(r.active){var i=r.duration/r.length;r.time+=r.direction*e,r.mirroredLoop?(r.time>r.duration||r.time<0)&&(r.direction*=-1,r.time>r.duration&&(r.time=r.duration,r.directionBackwards=!0),r.time<0&&(r.time=0,r.directionBackwards=!1)):(r.time=r.time%r.duration,r.time<0&&(r.time+=r.duration));var o=r.startFrame+XG.Math.clamp(Math.floor(r.time/i),0,r.length-1),n=r.weight;o!==r.currentFrame&&(this.morphTargetInfluences[r.lastFrame]=0,this.morphTargetInfluences[r.currentFrame]=1*n,this.morphTargetInfluences[o]=0,r.lastFrame=r.currentFrame,r.currentFrame=o);var s=r.time%i/i;r.directionBackwards&&(s=1-s),this.morphTargetInfluences[r.currentFrame]=s*n,this.morphTargetInfluences[r.lastFrame]=(1-s)*n}}},XG.MD2Character=function(){function e(e,t){for(var r=[],i=0;i<t.length;i++)r[i]=XG.ImageUtils.loadTexture(e+t[i],a),r[i].name=t[i];return r}function t(e,t){var a=(XG.ImageUtils.generateDataTexture(1,1,new XG.Color(16777215)),new XG.PhongMaterial({color:16777215,specular:1118481,shininess:50,map:t,morphTargets:!0,morphNormals:!0,metal:!0}));a.wrapAround=!0;for(var r=[],o=0,n=e.length;n>o;o++)r[o]=a;var s=new XG.MorphMesh(e,r);return s.rotation.setY(-Math.PI/2),s.autoCreateAnimations(i.animationFPS),s}function a(){i.loadCounter-=1,0===i.loadCounter&&i.onLoadComplete()}function r(e){return 1===e?1:-Math.pow(2,-10*e)+1}var i=this;this.scale=1,this.animationFPS=6,this.transitionFrames=15,this.maxSpeed=275,this.maxReverseSpeed=-275,this.frontAcceleration=600,this.backAcceleration=600,this.frontDecceleration=600,this.angularSpeed=2.5,this.root=new XG.Node,this.meshBody=null,this.meshWeapon=null,this.controls=null,this.skinsBody=[],this.skinsWeapon=[],this.weapons=[],this.currentSkin=void 0,this.onLoadComplete=function(){},this.meshes=[],this.animations={},this.loadCounter=0,this.speed=0,this.bodyOrientation=0,this.walkSpeed=this.maxSpeed,this.crouchSpeed=.5*this.maxSpeed,this.activeAnimation=null,this.oldAnimation=null,this.enableShadows=function(e){for(var t=0;t<this.meshes.length;t++)this.meshes[t].castShadow=e,this.meshes[t].receiveShadow=e},this.setVisible=function(e){for(var t=0;t<this.meshes.length;t++)this.meshes[t].visible=e,this.meshes[t].visible=e},this.shareParts=function(e){this.animations=e.animations,this.walkSpeed=e.walkSpeed,this.crouchSpeed=e.crouchSpeed,this.skinsBody=e.skinsBody,this.skinsWeapon=e.skinsWeapon;var a=t(e.meshBody.geometries,this.skinsBody[0]);a.scale.set(this.scale,this.scale,this.scale),this.root.position.data[1]=e.root.position.data[1],this.root.add(a),this.meshBody=a,this.meshes.push(a);for(var r=0;r<e.weapons.length;r++){var i=t(e.weapons[r].geometries,this.skinsWeapon[r]);i.scale.set(this.scale,this.scale,this.scale),i.visible=!1,i.name=e.weapons[r].name,this.root.add(i),this.weapons[r]=i,this.meshWeapon=i,this.meshes.push(i)}},this.loadParts=function(r){this.animations=r.animations,this.walkSpeed=r.walkSpeed,this.crouchSpeed=r.crouchSpeed,this.loadCounter=2*r.weapons.length+r.skins.length+1;for(var o=[],n=0;n<r.weapons.length;n++)o[n]=r.weapons[n][1];this.skinsBody=e(r.baseUrl+"skins/",r.skins),this.skinsWeapon=e(r.baseUrl+"skins/",o);var s=new XG.JSONLoader;s.load(r.baseUrl+r.body,function(e){for(var r=0,o=e.length;o>r;r++){var n=e[r];n.computeBoundingBox()}i.root.position.data[1]=-i.scale*n.boundingBox.min.data[1];var s=t(n,i.skinsBody[0]);s.scale.multiplyScalar(i.scale),i.root.add(s),i.meshBody=s,i.meshes.push(s),a()});for(var l=function(e,r){return function(o){var n=t(o,i.skinsWeapon[e]);n.scale.set(i.scale,i.scale,i.scale),n.visible=!1,n.name=r,i.root.add(n),i.weapons[e]=n,i.meshWeapon=n,i.meshes.push(n),a()}},n=0;n<r.weapons.length;n++)s.load(r.baseUrl+r.weapons[n][0],l(n,r.weapons[n][0]))},this.setPlaybackRate=function(e){this.meshBody&&(this.meshBody.duration=this.meshBody.baseDuration/e),this.meshWeapon&&(this.meshWeapon.duration=this.meshWeapon.baseDuration/e)},this.setSkin=function(e){if(this.meshBody){for(var t=0,a=this.meshBody.materials.length;a>t;t++){var r=this.meshBody.materials[t];r.map=this.skinsBody[e]}this.currentSkin=e}},this.setWeapon=function(e){for(var t=0;t<this.weapons.length;t++)this.weapons[t].visible=!1;var a=this.weapons[e];a&&(a.visible=!0,this.meshWeapon=a,this.activeAnimation&&(a.playAnimation(this.activeAnimation),this.meshWeapon.setAnimationTime(this.activeAnimation,this.meshBody.getAnimationTime(this.activeAnimation))))},this.setAnimation=function(e){e!==this.activeAnimation&&e&&(this.meshBody&&(this.meshBody.setAnimationWeight(e,0),this.meshBody.playAnimation(e),this.oldAnimation=this.activeAnimation,this.activeAnimation=e,this.blendCounter=this.transitionFrames),this.meshWeapon&&(this.meshWeapon.setAnimationWeight(e,0),this.meshWeapon.playAnimation(e)))},this.update=function(e){this.controls&&this.updateMovementModel(e),this.animations&&(this.updateBehaviors(e),this.updateAnimations(e))},this.updateAnimations=function(e){var t=1;this.blendCounter>0&&(t=(this.transitionFrames-this.blendCounter)/this.transitionFrames,this.blendCounter-=1),this.meshBody&&(this.meshBody.update(e),this.meshBody.setAnimationWeight(this.activeAnimation,t),this.meshBody.setAnimationWeight(this.oldAnimation,1-t)),this.meshWeapon&&(this.meshWeapon.update(e),this.meshWeapon.setAnimationWeight(this.activeAnimation,t),this.meshWeapon.setAnimationWeight(this.oldAnimation,1-t))},this.updateBehaviors=function(){var e,t,a=this.controls,r=this.animations;a.crouch?(e=r.crouchMove,t=r.crouchIdle):(e=r.move,t=r.idle),a.jump&&(e=r.jump,t=r.jump),a.attack&&(a.crouch?(e=r.crouchAttack,t=r.crouchAttack):(e=r.attack,t=r.attack)),(a.moveForward||a.moveBackward||a.moveLeft||a.moveRight)&&this.activeAnimation!==e&&this.setAnimation(e),Math.abs(this.speed)<.2*this.maxSpeed&&!(a.moveLeft||a.moveRight||a.moveForward||a.moveBackward)&&this.activeAnimation!==t&&this.setAnimation(t),a.moveForward&&(this.meshBody&&(this.meshBody.setAnimationDirectionForward(this.activeAnimation),this.meshBody.setAnimationDirectionForward(this.oldAnimation)),this.meshWeapon&&(this.meshWeapon.setAnimationDirectionForward(this.activeAnimation),this.meshWeapon.setAnimationDirectionForward(this.oldAnimation))),a.moveBackward&&(this.meshBody&&(this.meshBody.setAnimationDirectionBackward(this.activeAnimation),this.meshBody.setAnimationDirectionBackward(this.oldAnimation)),this.meshWeapon&&(this.meshWeapon.setAnimationDirectionBackward(this.activeAnimation),this.meshWeapon.setAnimationDirectionBackward(this.oldAnimation)))
  },this.updateMovementModel=function(e){var t=this.controls;this.maxSpeed=t.crouch?this.crouchSpeed:this.walkSpeed,this.maxReverseSpeed=-this.maxSpeed,t.moveForward&&(this.speed=XG.Math.clamp(this.speed+e*this.frontAcceleration,this.maxReverseSpeed,this.maxSpeed)),t.moveBackward&&(this.speed=XG.Math.clamp(this.speed-e*this.backAcceleration,this.maxReverseSpeed,this.maxSpeed));var a=1;if(t.moveLeft&&(this.bodyOrientation+=e*this.angularSpeed,this.speed=XG.Math.clamp(this.speed+a*e*this.frontAcceleration,this.maxReverseSpeed,this.maxSpeed)),t.moveRight&&(this.bodyOrientation-=e*this.angularSpeed,this.speed=XG.Math.clamp(this.speed+a*e*this.frontAcceleration,this.maxReverseSpeed,this.maxSpeed)),!t.moveForward&&!t.moveBackward)if(this.speed>0){var i=r(this.speed/this.maxSpeed);this.speed=XG.Math.clamp(this.speed-i*e*this.frontDecceleration,0,this.maxSpeed)}else{var i=r(this.speed/this.maxReverseSpeed);this.speed=XG.Math.clamp(this.speed+i*e*this.backAcceleration,this.maxReverseSpeed,0)}var o=this.speed*e;this.root.position.data[0]+=Math.sin(this.bodyOrientation)*o,this.root.position.data[2]+=Math.cos(this.bodyOrientation)*o,this.root.rotation.data[1]=this.bodyOrientation}},XG.SkinnedCharacter=function(e){function t(e){return 1===e?1:-Math.pow(2,-10*e)+1}this.config=e,this.transitionFrames=15,this.controls=null,this.root=new XG.Node,this.meshes=[],this.animations={},this.speed=0,this.bodyOrientation=0,this.activeAnimation=null,this.oldAnimation=null,this.animations=e.animations,this.walkSpeed=void 0!==e.walkSpeed?e.walkSpeed:275,this.crouchSpeed=void 0!==e.crouchSpeed?e.crouchSpeed:137.5,this.angularSpeed=void 0!==e.angularSpeed?e.angularSpeed:2.5,this.frontAcceleration=void 0!==e.frontAcceleration?e.frontAcceleration:600,this.frontDecceleration=void 0!==e.frontDecceleration?e.frontDecceleration:600,this.backAcceleration=void 0!==e.backAcceleration?e.backAcceleration:600,this.maxSpeed=this.walkSpeed,this.maxReverseSpeed=-this.maxSpeed,this.addMesh=function(e){this.root.add(e),this.meshes.push(e)},this.enableShadows=function(e){for(var t=0;t<this.meshes.length;t++){var a=this.meshes[t];a.castShadow=e,a.receiveShadow=e}},this.setVisible=function(e){for(var t=0;t<this.meshes.length;t++){var a=this.meshes[t];a.visible=e,a.visible=e}},this.setAnimation=function(e){if(e!==this.activeAnimation&&e)for(var t=0,a=this.meshes.length;a>t;t++){var r=this.meshes[t];r.setAnimationWeight(e,0),r.playAnimation(e),this.oldAnimation=this.activeAnimation,this.activeAnimation=e,this.blendCounter=this.transitionFrames}},this.update=function(e){this.controls&&this.updateMovementModel(e),this.animations&&(this.updateBehaviors(e),this.updateAnimations(e))},this.updateAnimations=function(e){var t=1;this.blendCounter>0&&(t=(this.transitionFrames-this.blendCounter)/this.transitionFrames,this.blendCounter-=1);for(var a=0,r=this.meshes.length;r>a;a++){var i=this.meshes[a];i.setAnimationWeight(this.activeAnimation,t),i.setAnimationWeight(this.oldAnimation,1-t),i.update(e)}},this.updateBehaviors=function(){var e,t,a=this.controls,r=this.animations;if(a.crouch?(e=r.crouchMove,t=r.crouchIdle):(e=r.move,t=r.idle),a.jump&&(e=r.jump,t=r.jump),a.attack&&(a.crouch?(e=r.crouchAttack,t=r.crouchAttack):(e=r.attack,t=r.attack)),(a.moveForward||a.moveBackward||a.moveLeft||a.moveRight)&&this.activeAnimation!==e&&this.setAnimation(e),Math.abs(this.speed)<.2*this.maxSpeed&&!(a.moveLeft||a.moveRight||a.moveForward||a.moveBackward)&&this.activeAnimation!==t&&this.setAnimation(t),a.moveForward)for(var i=0,o=this.meshes.length;o>i;i++){var n=this.meshes[i];n.setAnimationDirectionForward(this.activeAnimation),n.setAnimationDirectionForward(this.oldAnimation)}if(a.moveBackward)for(var i=0,o=this.meshes.length;o>i;i++){var n=this.meshes[i];n.setAnimationDirectionBackward(this.activeAnimation),n.setAnimationDirectionBackward(this.oldAnimation)}},this.updateMovementModel=function(e){var a=this.controls;this.maxSpeed=a.crouch?this.crouchSpeed:this.walkSpeed,this.maxReverseSpeed=-this.maxSpeed,a.moveForward&&(this.speed=XG.Math.clamp(this.speed+e*this.frontAcceleration,this.maxReverseSpeed,this.maxSpeed)),a.moveBackward&&(this.speed=XG.Math.clamp(this.speed-e*this.backAcceleration,this.maxReverseSpeed,this.maxSpeed));var r=1;if(a.moveLeft&&(this.bodyOrientation+=e*this.angularSpeed,this.speed=XG.Math.clamp(this.speed+r*e*this.frontAcceleration,this.maxReverseSpeed,this.maxSpeed)),a.moveRight&&(this.bodyOrientation-=e*this.angularSpeed,this.speed=XG.Math.clamp(this.speed+r*e*this.frontAcceleration,this.maxReverseSpeed,this.maxSpeed)),!a.moveForward&&!a.moveBackward)if(this.speed>0){var i=t(this.speed/this.maxSpeed);this.speed=XG.Math.clamp(this.speed-i*e*this.frontDecceleration,0,this.maxSpeed)}else{var i=t(this.speed/this.maxReverseSpeed);this.speed=XG.Math.clamp(this.speed+i*e*this.backAcceleration,this.maxReverseSpeed,0)}var o=this.speed*e;this.root.position.data[0]+=Math.sin(this.bodyOrientation)*o,this.root.position.data[2]+=Math.cos(this.bodyOrientation)*o,this.root.rotation.data[1]=this.bodyOrientation}},XG.SkinnedMesh=function(e,t,a){XG.Mesh.call(this,e,t),this.useVertexTexture=void 0!==a?a:!0,this.animations={},this.animationsList=[],this.identityMatrix=new XG.Matrix4,this.bones=[],this.boneMatrices=[];var r=this.geometries[0];if(r){var i=r.bones,o=r.animations;if(i){var n,s,l,h,d,c;for(n=0;n<i.length;n++)l=i[n],h=l.pos,d=l.rotq,c=l.scl,s=this.addBone(),s.name=l.name,s.position.set(h[0],h[1],h[2]),s.quaternion.set(d[0],d[1],d[2],d[3]),s.useQuaternion=!0,void 0!==c?s.scale.set(c[0],c[1],c[2]):s.scale.set(1,1,1);for(n=0;n<this.bones.length;n++)l=i[n],s=this.bones[n],-1===l.parent?this.add(s):this.bones[l.parent].add(s);var u=this.bones.length;if(this.useVertexTexture){var f;f=u>256?64:u>64?32:u>16?16:8,this.boneTextureWidth=f,this.boneTextureHeight=f,this.boneMatrices=new Float32Array(this.boneTextureWidth*this.boneTextureHeight*4),this.boneTexture=new XG.DataTexture(this.boneMatrices,this.boneTextureWidth,this.boneTextureHeight,XG.RGBAFormat,XG.FloatType),this.boneTexture.minFilter=XG.NearestFilter,this.boneTexture.magFilter=XG.NearestFilter,this.boneTexture.generateMipmaps=!1,this.boneTexture.flipY=!1}else this.boneMatrices=new Float32Array(16*u);this.pose()}if(o)for(var p=0,m=o.length;m>p;p++){var v=o[p],g=new XG.Animation(this,v);this.animations[v.name]=g,this.animationsList.push(g)}}},XG.SkinnedMesh.prototype=Object.create(XG.Mesh.prototype),XG.SkinnedMesh.prototype.playAnimation=function(e){void 0!==this.animations[e]&&this.animations[e].play()},XG.SkinnedMesh.prototype.setAnimationWeight=function(e,t){void 0!==this.animations[e]&&this.animations[e].setWeight(t)},XG.SkinnedMesh.prototype.setAnimationDirectionForward=function(e){void 0!==this.animations[e]&&this.animations[e].setDirectionForward()},XG.SkinnedMesh.prototype.setAnimationDirectionBackward=function(e){void 0!==this.animations[e]&&this.animations[e].setDirectionBackward()},XG.SkinnedMesh.prototype.update=function(e){for(var t=this.bones,a=0,r=t.length;r>a;a++){var i=t[a];i.firstAnimationFlag=!0}for(var a=0,r=this.animationsList.length;r>a;a++){var o=this.animationsList[a];o.update(e)}},XG.SkinnedMesh.prototype.addBone=function(e){return void 0===e&&(e=new XG.Bone(this)),this.bones.push(e),e},XG.SkinnedMesh.prototype.updateMatrixWorld=function(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.parent?this.matrixWorld.multiply(this.parent.matrixWorld,this.matrix):this.matrixWorld.copy(this.matrix),this.matrixWorldNeedsUpdate=!1,e=!0);for(var t=0,a=this.children.length;a>t;t++){var r=this.children[t];r instanceof XG.Bone?r.update(this.identityMatrix,!1):r.updateMatrixWorld(!0)}if(void 0==this.boneInverses){this.boneInverses=[];for(var i=0,o=this.bones.length;o>i;i++){var n=new XG.Matrix4;n.getInverse(this.bones[i].skinMatrix),this.boneInverses.push(n)}}for(var i=0,o=this.bones.length;o>i;i++)XG.SkinnedMesh.offsetMatrix.multiply(this.bones[i].skinMatrix,this.boneInverses[i]),XG.SkinnedMesh.offsetMatrix.flattenToArrayOffset(this.boneMatrices,16*i);this.useVertexTexture&&(this.boneTexture.needsUpdate=!0)},XG.SkinnedMesh.prototype.pose=function(){this.updateMatrixWorld(!0);for(var e,t,a,r,i,o=0,n=this.geometries.length;n>o;o++)for(var s=this.geometries[o],l=s.attributes.skinWeight.array,h=0,d=l.length;d>h;h+=4)e=l[h],t=l[h+1],a=l[h+2],r=l[h+3],i=1/(Math.abs(e)+Math.abs(t)+Math.abs(a)+Math.abs(r)),1/0!==i?(l[h]*=i,l[h+1]*=i,l[h+2]*=i,l[h+3]*=i):l[h]=1},XG.SkinnedMesh.prototype.clone=function(e){return void 0===e&&(e=new XG.SkinnedMesh(this.geometries,this.materials,this.useVertexTexture)),XG.Mesh.prototype.clone.call(this,e),e},XG.SkinnedMesh.offsetMatrix=new XG.Matrix4,XG.TriangleStrip=function(e,t){XG.Mesh.call(this,e,t)},XG.TriangleStrip.prototype=Object.create(XG.Mesh.prototype),XG.TriangleStrip.prototype.clone=function(e){return void 0===e&&(e=new XG.TriangleStrip(this.geometries,this.materials)),XG.Mesh.prototype.clone.call(this,e),e},XG.Particles=function(e,t){XG.Node.call(this),this.geometries=e instanceof Array?e:e instanceof XG.Geometry?[e]:[],this.materials=t instanceof Array?t:t instanceof XG.Material?[t]:[];for(var a=0,r=this.geometries.length;r>a;a++){var i=this.geometries[a];null===i.boundingSphere&&i.computeBoundingSphere()}this.sortParticles=!1,this.frustumCulled=!1},XG.Particles.prototype=Object.create(XG.Node.prototype),XG.Particles.prototype.clone=function(e){return void 0===e&&(e=new XG.Particles(this.geometries,this.materials)),e.sortParticles=this.sortParticles,e.frustumCulled=this.frustumCulled,XG.Node.prototype.clone.call(this,e),e},XG.ImmediateRenderObject=function(){XG.Node.call(this),this.boundingSphere=new XG.Sphere,this.render=function(){}},XG.ImmediateRenderObject.prototype=Object.create(XG.Node.prototype),XG.MarchingCubes=function(e,t,a,r){XG.ImmediateRenderObject.call(this),this.materials=[t],this.boundingSphere.radius=1,this.enableUvs=void 0!==a?a:!1,this.enableColors=void 0!==r?r:!1,this.init=function(e){this.resolution=e,this.isolation=80,this.size=e,this.size2=this.size*this.size,this.size3=this.size2*this.size,this.halfsize=this.size/2,this.delta=2/this.size,this.yd=this.size,this.zd=this.size2,this.field=new Float32Array(this.size3),this.normal_cache=new Float32Array(3*this.size3),this.vlist=new Float32Array(36),this.nlist=new Float32Array(36),this.firstDraw=!0,this.maxCount=4096,this.count=0,this.hasPositions=!1,this.hasNormals=!1,this.hasColors=!1,this.hasUvs=!1,this.positionArray=new Float32Array(3*this.maxCount),this.normalArray=new Float32Array(3*this.maxCount),this.enableUvs&&(this.uvArray=new Float32Array(2*this.maxCount)),this.enableColors&&(this.colorArray=new Float32Array(3*this.maxCount))},this.lerp=function(e,t,a){return e+(t-e)*a},this.VIntX=function(e,t,a,r,i,o,n,s,l,h){var d=(i-l)/(h-l),c=this.normal_cache;t[r]=o+d*this.delta,t[r+1]=n,t[r+2]=s,a[r]=this.lerp(c[e],c[e+3],d),a[r+1]=this.lerp(c[e+1],c[e+4],d),a[r+2]=this.lerp(c[e+2],c[e+5],d)},this.VIntY=function(e,t,a,r,i,o,n,s,l,h){var d=(i-l)/(h-l),c=this.normal_cache;t[r]=o,t[r+1]=n+d*this.delta,t[r+2]=s;var u=e+3*this.yd;a[r]=this.lerp(c[e],c[u],d),a[r+1]=this.lerp(c[e+1],c[u+1],d),a[r+2]=this.lerp(c[e+2],c[u+2],d)},this.VIntZ=function(e,t,a,r,i,o,n,s,l,h){var d=(i-l)/(h-l),c=this.normal_cache;t[r]=o,t[r+1]=n,t[r+2]=s+d*this.delta;var u=e+3*this.zd;a[r]=this.lerp(c[e],c[u],d),a[r+1]=this.lerp(c[e+1],c[u+1],d),a[r+2]=this.lerp(c[e+2],c[u+2],d)},this.compNorm=function(e){var t=3*e;0===this.normal_cache[t]&&(this.normal_cache[t]=this.field[e-1]-this.field[e+1],this.normal_cache[t+1]=this.field[e-this.yd]-this.field[e+this.yd],this.normal_cache[t+2]=this.field[e-this.zd]-this.field[e+this.zd])},this.polygonize=function(e,t,a,r,i,o){var n=r+1,s=r+this.yd,l=r+this.zd,h=n+this.yd,d=n+this.zd,c=r+this.yd+this.zd,u=n+this.yd+this.zd,f=0,p=this.field[r],m=this.field[n],v=this.field[s],g=this.field[h],S=this.field[l],G=this.field[d],x=this.field[c],M=this.field[u];i>p&&(f|=1),i>m&&(f|=2),i>v&&(f|=8),i>g&&(f|=4),i>S&&(f|=16),i>G&&(f|=32),i>x&&(f|=128),i>M&&(f|=64);var y=XG.edgeTable[f];if(0===y)return 0;var X=this.delta,D=e+X,_=t+X,w=a+X;1&y&&(this.compNorm(r),this.compNorm(n),this.VIntX(3*r,this.vlist,this.nlist,0,i,e,t,a,p,m)),2&y&&(this.compNorm(n),this.compNorm(h),this.VIntY(3*n,this.vlist,this.nlist,3,i,D,t,a,m,g)),4&y&&(this.compNorm(s),this.compNorm(h),this.VIntX(3*s,this.vlist,this.nlist,6,i,e,_,a,v,g)),8&y&&(this.compNorm(r),this.compNorm(s),this.VIntY(3*r,this.vlist,this.nlist,9,i,e,t,a,p,v)),16&y&&(this.compNorm(l),this.compNorm(d),this.VIntX(3*l,this.vlist,this.nlist,12,i,e,t,w,S,G)),32&y&&(this.compNorm(d),this.compNorm(u),this.VIntY(3*d,this.vlist,this.nlist,15,i,D,t,w,G,M)),64&y&&(this.compNorm(c),this.compNorm(u),this.VIntX(3*c,this.vlist,this.nlist,18,i,e,_,w,x,M)),128&y&&(this.compNorm(l),this.compNorm(c),this.VIntY(3*l,this.vlist,this.nlist,21,i,e,t,w,S,x)),256&y&&(this.compNorm(r),this.compNorm(l),this.VIntZ(3*r,this.vlist,this.nlist,24,i,e,t,a,p,S)),512&y&&(this.compNorm(n),this.compNorm(d),this.VIntZ(3*n,this.vlist,this.nlist,27,i,D,t,a,m,G)),1024&y&&(this.compNorm(h),this.compNorm(u),this.VIntZ(3*h,this.vlist,this.nlist,30,i,D,_,a,g,M)),2048&y&&(this.compNorm(s),this.compNorm(c),this.VIntZ(3*s,this.vlist,this.nlist,33,i,e,_,a,v,x)),f<<=4;for(var A,C,T,b=0,P=0;-1!=XG.triTable[f+P];)A=f+P,C=A+1,T=A+2,this.posnormtriv(this.vlist,this.nlist,3*XG.triTable[A],3*XG.triTable[C],3*XG.triTable[T],o),P+=3,b++;return b},this.posnormtriv=function(e,t,a,r,i,o){var n=3*this.count;if(this.positionArray[n]=e[a],this.positionArray[n+1]=e[a+1],this.positionArray[n+2]=e[a+2],this.positionArray[n+3]=e[r],this.positionArray[n+4]=e[r+1],this.positionArray[n+5]=e[r+2],this.positionArray[n+6]=e[i],this.positionArray[n+7]=e[i+1],this.positionArray[n+8]=e[i+2],this.normalArray[n]=t[a],this.normalArray[n+1]=t[a+1],this.normalArray[n+2]=t[a+2],this.normalArray[n+3]=t[r],this.normalArray[n+4]=t[r+1],this.normalArray[n+5]=t[r+2],this.normalArray[n+6]=t[i],this.normalArray[n+7]=t[i+1],this.normalArray[n+8]=t[i+2],this.enableUvs){var s=2*this.count;this.uvArray[s]=e[a],this.uvArray[s+1]=e[a+2],this.uvArray[s+2]=e[r],this.uvArray[s+3]=e[r+2],this.uvArray[s+4]=e[i],this.uvArray[s+5]=e[i+2]}this.enableColors&&(this.colorArray[n]=e[a],this.colorArray[n+1]=e[a+1],this.colorArray[n+2]=e[a+2],this.colorArray[n+3]=e[r],this.colorArray[n+4]=e[r+1],this.colorArray[n+5]=e[r+2],this.colorArray[n+6]=e[i],this.colorArray[n+7]=e[i+1],this.colorArray[n+8]=e[i+2]),this.count+=3,this.count>=this.maxCount-3&&(this.hasPositions=!0,this.hasNormals=!0,this.enableUvs&&(this.hasUvs=!0),this.enableColors&&(this.hasColors=!0),o(this))},this.begin=function(){this.count=0,this.hasPositions=!1,this.hasNormals=!1,this.hasUvs=!1,this.hasColors=!1},this.end=function(e){if(0!==this.count){for(var t=3*this.count;t<this.positionArray.length;t++)this.positionArray[t]=0;this.hasPositions=!0,this.hasNormals=!0,this.enableUvs&&(this.hasUvs=!0),this.enableColors&&(this.hasColors=!0),e(this)}},this.addBall=function(e,t,a,r,i){var o=this.size*Math.sqrt(r/i),n=a*this.size,s=t*this.size,l=e*this.size,h=Math.floor(n-o);1>h&&(h=1);var d=Math.floor(n+o);d>this.size-1&&(d=this.size-1);var c=Math.floor(s-o);1>c&&(c=1);var u=Math.floor(s+o);u>this.size-1&&(u=this.size-1);var f=Math.floor(l-o);1>f&&(f=1);var p=Math.floor(l+o);p>this.size-1&&(p=this.size-1);var m,v,g,S,G,x,M,y,X,D,_;for(g=h;d>g;g++)for(G=this.size2*g,y=g/this.size-a,X=y*y,v=c;u>v;v++)for(S=G+this.size*v,M=v/this.size-t,D=M*M,m=f;p>m;m++)x=m/this.size-e,_=r/(1e-6+x*x+D+X)-i,_>0&&(this.field[S+m]+=_)},this.addPlaneX=function(e,t){var a,r,i,o,n,s,l,h=this.size,d=this.yd,c=this.zd,u=this.field,f=h*Math.sqrt(e/t);for(f>h&&(f=h),a=0;f>a;a++)if(s=a/h,o=s*s,n=e/(1e-4+o)-t,n>0)for(r=0;h>r;r++)for(l=a+r*d,i=0;h>i;i++)u[c*i+l]+=n},this.addPlaneY=function(e,t){var a,r,i,o,n,s,l,h,d=this.size,c=this.yd,u=this.zd,f=this.field,p=d*Math.sqrt(e/t);for(p>d&&(p=d),r=0;p>r;r++)if(s=r/d,o=s*s,n=e/(1e-4+o)-t,n>0)for(l=r*c,a=0;d>a;a++)for(h=l+a,i=0;d>i;i++)f[u*i+h]+=n},this.addPlaneZ=function(e,t){var a,r,i,o,n,s,l,h,d=this.size,c=this.yd,u=this.zd,f=this.field,p=d*Math.sqrt(e/t);for(p>d&&(p=d),i=0;p>i;i++)if(s=i/d,o=s*s,n=e/(1e-4+o)-t,n>0)for(l=u*i,r=0;d>r;r++)for(h=l+r*c,a=0;d>a;a++)f[h+a]+=n},this.reset=function(){var e;for(e=0;e<this.size3;e++)this.normal_cache[3*e]=0,this.field[e]=0},this.render=function(e){this.begin();var t,a,r,i,o,n,s,l,h,d=this.size-2;for(i=1;d>i;i++)for(h=this.size2*i,s=(i-this.halfsize)/this.halfsize,r=1;d>r;r++)for(l=h+this.size*r,n=(r-this.halfsize)/this.halfsize,a=1;d>a;a++)o=(a-this.halfsize)/this.halfsize,t=l+a,this.polygonize(o,n,s,t,this.isolation,e);this.end(e)},this.init(e)},XG.MarchingCubes.prototype=Object.create(XG.ImmediateRenderObject.prototype),XG.edgeTable=new Int32Array([0,265,515,778,1030,1295,1541,1804,2060,2309,2575,2822,3082,3331,3593,3840,400,153,915,666,1430,1183,1941,1692,2460,2197,2975,2710,3482,3219,3993,3728,560,825,51,314,1590,1855,1077,1340,2620,2869,2111,2358,3642,3891,3129,3376,928,681,419,170,1958,1711,1445,1196,2988,2725,2479,2214,4010,3747,3497,3232,1120,1385,1635,1898,102,367,613,876,3180,3429,3695,3942,2154,2403,2665,2912,1520,1273,2035,1786,502,255,1013,764,3580,3317,4095,3830,2554,2291,3065,2800,1616,1881,1107,1370,598,863,85,348,3676,3925,3167,3414,2650,2899,2137,2384,1984,1737,1475,1226,966,719,453,204,4044,3781,3535,3270,3018,2755,2505,2240,2240,2505,2755,3018,3270,3535,3781,4044,204,453,719,966,1226,1475,1737,1984,2384,2137,2899,2650,3414,3167,3925,3676,348,85,863,598,1370,1107,1881,1616,2800,3065,2291,2554,3830,4095,3317,3580,764,1013,255,502,1786,2035,1273,1520,2912,2665,2403,2154,3942,3695,3429,3180,876,613,367,102,1898,1635,1385,1120,3232,3497,3747,4010,2214,2479,2725,2988,1196,1445,1711,1958,170,419,681,928,3376,3129,3891,3642,2358,2111,2869,2620,1340,1077,1855,1590,314,51,825,560,3728,3993,3219,3482,2710,2975,2197,2460,1692,1941,1183,1430,666,915,153,400,3840,3593,3331,3082,2822,2575,2309,2060,1804,1541,1295,1030,778,515,265,0]),XG.triTable=new Int32Array([-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,8,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,8,3,9,8,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,2,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,8,3,1,2,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,2,10,0,2,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,8,3,2,10,8,10,9,8,-1,-1,-1,-1,-1,-1,-1,3,11,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,11,2,8,11,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,9,0,2,3,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,11,2,1,9,11,9,8,11,-1,-1,-1,-1,-1,-1,-1,3,10,1,11,10,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,10,1,0,8,10,8,11,10,-1,-1,-1,-1,-1,-1,-1,3,9,0,3,11,9,11,10,9,-1,-1,-1,-1,-1,-1,-1,9,8,10,10,8,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,7,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,3,0,7,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,9,8,4,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,1,9,4,7,1,7,3,1,-1,-1,-1,-1,-1,-1,-1,1,2,10,8,4,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3,4,7,3,0,4,1,2,10,-1,-1,-1,-1,-1,-1,-1,9,2,10,9,0,2,8,4,7,-1,-1,-1,-1,-1,-1,-1,2,10,9,2,9,7,2,7,3,7,9,4,-1,-1,-1,-1,8,4,7,3,11,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,4,7,11,2,4,2,0,4,-1,-1,-1,-1,-1,-1,-1,9,0,1,8,4,7,2,3,11,-1,-1,-1,-1,-1,-1,-1,4,7,11,9,4,11,9,11,2,9,2,1,-1,-1,-1,-1,3,10,1,3,11,10,7,8,4,-1,-1,-1,-1,-1,-1,-1,1,11,10,1,4,11,1,0,4,7,11,4,-1,-1,-1,-1,4,7,8,9,0,11,9,11,10,11,0,3,-1,-1,-1,-1,4,7,11,4,11,9,9,11,10,-1,-1,-1,-1,-1,-1,-1,9,5,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,5,4,0,8,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,5,4,1,5,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,5,4,8,3,5,3,1,5,-1,-1,-1,-1,-1,-1,-1,1,2,10,9,5,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3,0,8,1,2,10,4,9,5,-1,-1,-1,-1,-1,-1,-1,5,2,10,5,4,2,4,0,2,-1,-1,-1,-1,-1,-1,-1,2,10,5,3,2,5,3,5,4,3,4,8,-1,-1,-1,-1,9,5,4,2,3,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,11,2,0,8,11,4,9,5,-1,-1,-1,-1,-1,-1,-1,0,5,4,0,1,5,2,3,11,-1,-1,-1,-1,-1,-1,-1,2,1,5,2,5,8,2,8,11,4,8,5,-1,-1,-1,-1,10,3,11,10,1,3,9,5,4,-1,-1,-1,-1,-1,-1,-1,4,9,5,0,8,1,8,10,1,8,11,10,-1,-1,-1,-1,5,4,0,5,0,11,5,11,10,11,0,3,-1,-1,-1,-1,5,4,8,5,8,10,10,8,11,-1,-1,-1,-1,-1,-1,-1,9,7,8,5,7,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,3,0,9,5,3,5,7,3,-1,-1,-1,-1,-1,-1,-1,0,7,8,0,1,7,1,5,7,-1,-1,-1,-1,-1,-1,-1,1,5,3,3,5,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,7,8,9,5,7,10,1,2,-1,-1,-1,-1,-1,-1,-1,10,1,2,9,5,0,5,3,0,5,7,3,-1,-1,-1,-1,8,0,2,8,2,5,8,5,7,10,5,2,-1,-1,-1,-1,2,10,5,2,5,3,3,5,7,-1,-1,-1,-1,-1,-1,-1,7,9,5,7,8,9,3,11,2,-1,-1,-1,-1,-1,-1,-1,9,5,7,9,7,2,9,2,0,2,7,11,-1,-1,-1,-1,2,3,11,0,1,8,1,7,8,1,5,7,-1,-1,-1,-1,11,2,1,11,1,7,7,1,5,-1,-1,-1,-1,-1,-1,-1,9,5,8,8,5,7,10,1,3,10,3,11,-1,-1,-1,-1,5,7,0,5,0,9,7,11,0,1,0,10,11,10,0,-1,11,10,0,11,0,3,10,5,0,8,0,7,5,7,0,-1,11,10,5,7,11,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,6,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,8,3,5,10,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,0,1,5,10,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,8,3,1,9,8,5,10,6,-1,-1,-1,-1,-1,-1,-1,1,6,5,2,6,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,6,5,1,2,6,3,0,8,-1,-1,-1,-1,-1,-1,-1,9,6,5,9,0,6,0,2,6,-1,-1,-1,-1,-1,-1,-1,5,9,8,5,8,2,5,2,6,3,2,8,-1,-1,-1,-1,2,3,11,10,6,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,0,8,11,2,0,10,6,5,-1,-1,-1,-1,-1,-1,-1,0,1,9,2,3,11,5,10,6,-1,-1,-1,-1,-1,-1,-1,5,10,6,1,9,2,9,11,2,9,8,11,-1,-1,-1,-1,6,3,11,6,5,3,5,1,3,-1,-1,-1,-1,-1,-1,-1,0,8,11,0,11,5,0,5,1,5,11,6,-1,-1,-1,-1,3,11,6,0,3,6,0,6,5,0,5,9,-1,-1,-1,-1,6,5,9,6,9,11,11,9,8,-1,-1,-1,-1,-1,-1,-1,5,10,6,4,7,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,3,0,4,7,3,6,5,10,-1,-1,-1,-1,-1,-1,-1,1,9,0,5,10,6,8,4,7,-1,-1,-1,-1,-1,-1,-1,10,6,5,1,9,7,1,7,3,7,9,4,-1,-1,-1,-1,6,1,2,6,5,1,4,7,8,-1,-1,-1,-1,-1,-1,-1,1,2,5,5,2,6,3,0,4,3,4,7,-1,-1,-1,-1,8,4,7,9,0,5,0,6,5,0,2,6,-1,-1,-1,-1,7,3,9,7,9,4,3,2,9,5,9,6,2,6,9,-1,3,11,2,7,8,4,10,6,5,-1,-1,-1,-1,-1,-1,-1,5,10,6,4,7,2,4,2,0,2,7,11,-1,-1,-1,-1,0,1,9,4,7,8,2,3,11,5,10,6,-1,-1,-1,-1,9,2,1,9,11,2,9,4,11,7,11,4,5,10,6,-1,8,4,7,3,11,5,3,5,1,5,11,6,-1,-1,-1,-1,5,1,11,5,11,6,1,0,11,7,11,4,0,4,11,-1,0,5,9,0,6,5,0,3,6,11,6,3,8,4,7,-1,6,5,9,6,9,11,4,7,9,7,11,9,-1,-1,-1,-1,10,4,9,6,4,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,10,6,4,9,10,0,8,3,-1,-1,-1,-1,-1,-1,-1,10,0,1,10,6,0,6,4,0,-1,-1,-1,-1,-1,-1,-1,8,3,1,8,1,6,8,6,4,6,1,10,-1,-1,-1,-1,1,4,9,1,2,4,2,6,4,-1,-1,-1,-1,-1,-1,-1,3,0,8,1,2,9,2,4,9,2,6,4,-1,-1,-1,-1,0,2,4,4,2,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,3,2,8,2,4,4,2,6,-1,-1,-1,-1,-1,-1,-1,10,4,9,10,6,4,11,2,3,-1,-1,-1,-1,-1,-1,-1,0,8,2,2,8,11,4,9,10,4,10,6,-1,-1,-1,-1,3,11,2,0,1,6,0,6,4,6,1,10,-1,-1,-1,-1,6,4,1,6,1,10,4,8,1,2,1,11,8,11,1,-1,9,6,4,9,3,6,9,1,3,11,6,3,-1,-1,-1,-1,8,11,1,8,1,0,11,6,1,9,1,4,6,4,1,-1,3,11,6,3,6,0,0,6,4,-1,-1,-1,-1,-1,-1,-1,6,4,8,11,6,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7,10,6,7,8,10,8,9,10,-1,-1,-1,-1,-1,-1,-1,0,7,3,0,10,7,0,9,10,6,7,10,-1,-1,-1,-1,10,6,7,1,10,7,1,7,8,1,8,0,-1,-1,-1,-1,10,6,7,10,7,1,1,7,3,-1,-1,-1,-1,-1,-1,-1,1,2,6,1,6,8,1,8,9,8,6,7,-1,-1,-1,-1,2,6,9,2,9,1,6,7,9,0,9,3,7,3,9,-1,7,8,0,7,0,6,6,0,2,-1,-1,-1,-1,-1,-1,-1,7,3,2,6,7,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,3,11,10,6,8,10,8,9,8,6,7,-1,-1,-1,-1,2,0,7,2,7,11,0,9,7,6,7,10,9,10,7,-1,1,8,0,1,7,8,1,10,7,6,7,10,2,3,11,-1,11,2,1,11,1,7,10,6,1,6,7,1,-1,-1,-1,-1,8,9,6,8,6,7,9,1,6,11,6,3,1,3,6,-1,0,9,1,11,6,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7,8,0,7,0,6,3,11,0,11,6,0,-1,-1,-1,-1,7,11,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7,6,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3,0,8,11,7,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,9,11,7,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,1,9,8,3,1,11,7,6,-1,-1,-1,-1,-1,-1,-1,10,1,2,6,11,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,2,10,3,0,8,6,11,7,-1,-1,-1,-1,-1,-1,-1,2,9,0,2,10,9,6,11,7,-1,-1,-1,-1,-1,-1,-1,6,11,7,2,10,3,10,8,3,10,9,8,-1,-1,-1,-1,7,2,3,6,2,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7,0,8,7,6,0,6,2,0,-1,-1,-1,-1,-1,-1,-1,2,7,6,2,3,7,0,1,9,-1,-1,-1,-1,-1,-1,-1,1,6,2,1,8,6,1,9,8,8,7,6,-1,-1,-1,-1,10,7,6,10,1,7,1,3,7,-1,-1,-1,-1,-1,-1,-1,10,7,6,1,7,10,1,8,7,1,0,8,-1,-1,-1,-1,0,3,7,0,7,10,0,10,9,6,10,7,-1,-1,-1,-1,7,6,10,7,10,8,8,10,9,-1,-1,-1,-1,-1,-1,-1,6,8,4,11,8,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3,6,11,3,0,6,0,4,6,-1,-1,-1,-1,-1,-1,-1,8,6,11,8,4,6,9,0,1,-1,-1,-1,-1,-1,-1,-1,9,4,6,9,6,3,9,3,1,11,3,6,-1,-1,-1,-1,6,8,4,6,11,8,2,10,1,-1,-1,-1,-1,-1,-1,-1,1,2,10,3,0,11,0,6,11,0,4,6,-1,-1,-1,-1,4,11,8,4,6,11,0,2,9,2,10,9,-1,-1,-1,-1,10,9,3,10,3,2,9,4,3,11,3,6,4,6,3,-1,8,2,3,8,4,2,4,6,2,-1,-1,-1,-1,-1,-1,-1,0,4,2,4,6,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,9,0,2,3,4,2,4,6,4,3,8,-1,-1,-1,-1,1,9,4,1,4,2,2,4,6,-1,-1,-1,-1,-1,-1,-1,8,1,3,8,6,1,8,4,6,6,10,1,-1,-1,-1,-1,10,1,0,10,0,6,6,0,4,-1,-1,-1,-1,-1,-1,-1,4,6,3,4,3,8,6,10,3,0,3,9,10,9,3,-1,10,9,4,6,10,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,9,5,7,6,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,8,3,4,9,5,11,7,6,-1,-1,-1,-1,-1,-1,-1,5,0,1,5,4,0,7,6,11,-1,-1,-1,-1,-1,-1,-1,11,7,6,8,3,4,3,5,4,3,1,5,-1,-1,-1,-1,9,5,4,10,1,2,7,6,11,-1,-1,-1,-1,-1,-1,-1,6,11,7,1,2,10,0,8,3,4,9,5,-1,-1,-1,-1,7,6,11,5,4,10,4,2,10,4,0,2,-1,-1,-1,-1,3,4,8,3,5,4,3,2,5,10,5,2,11,7,6,-1,7,2,3,7,6,2,5,4,9,-1,-1,-1,-1,-1,-1,-1,9,5,4,0,8,6,0,6,2,6,8,7,-1,-1,-1,-1,3,6,2,3,7,6,1,5,0,5,4,0,-1,-1,-1,-1,6,2,8,6,8,7,2,1,8,4,8,5,1,5,8,-1,9,5,4,10,1,6,1,7,6,1,3,7,-1,-1,-1,-1,1,6,10,1,7,6,1,0,7,8,7,0,9,5,4,-1,4,0,10,4,10,5,0,3,10,6,10,7,3,7,10,-1,7,6,10,7,10,8,5,4,10,4,8,10,-1,-1,-1,-1,6,9,5,6,11,9,11,8,9,-1,-1,-1,-1,-1,-1,-1,3,6,11,0,6,3,0,5,6,0,9,5,-1,-1,-1,-1,0,11,8,0,5,11,0,1,5,5,6,11,-1,-1,-1,-1,6,11,3,6,3,5,5,3,1,-1,-1,-1,-1,-1,-1,-1,1,2,10,9,5,11,9,11,8,11,5,6,-1,-1,-1,-1,0,11,3,0,6,11,0,9,6,5,6,9,1,2,10,-1,11,8,5,11,5,6,8,0,5,10,5,2,0,2,5,-1,6,11,3,6,3,5,2,10,3,10,5,3,-1,-1,-1,-1,5,8,9,5,2,8,5,6,2,3,8,2,-1,-1,-1,-1,9,5,6,9,6,0,0,6,2,-1,-1,-1,-1,-1,-1,-1,1,5,8,1,8,0,5,6,8,3,8,2,6,2,8,-1,1,5,6,2,1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,3,6,1,6,10,3,8,6,5,6,9,8,9,6,-1,10,1,0,10,0,6,9,5,0,5,6,0,-1,-1,-1,-1,0,3,8,5,6,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,5,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,5,10,7,5,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,5,10,11,7,5,8,3,0,-1,-1,-1,-1,-1,-1,-1,5,11,7,5,10,11,1,9,0,-1,-1,-1,-1,-1,-1,-1,10,7,5,10,11,7,9,8,1,8,3,1,-1,-1,-1,-1,11,1,2,11,7,1,7,5,1,-1,-1,-1,-1,-1,-1,-1,0,8,3,1,2,7,1,7,5,7,2,11,-1,-1,-1,-1,9,7,5,9,2,7,9,0,2,2,11,7,-1,-1,-1,-1,7,5,2,7,2,11,5,9,2,3,2,8,9,8,2,-1,2,5,10,2,3,5,3,7,5,-1,-1,-1,-1,-1,-1,-1,8,2,0,8,5,2,8,7,5,10,2,5,-1,-1,-1,-1,9,0,1,5,10,3,5,3,7,3,10,2,-1,-1,-1,-1,9,8,2,9,2,1,8,7,2,10,2,5,7,5,2,-1,1,3,5,3,7,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,8,7,0,7,1,1,7,5,-1,-1,-1,-1,-1,-1,-1,9,0,3,9,3,5,5,3,7,-1,-1,-1,-1,-1,-1,-1,9,8,7,5,9,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,8,4,5,10,8,10,11,8,-1,-1,-1,-1,-1,-1,-1,5,0,4,5,11,0,5,10,11,11,3,0,-1,-1,-1,-1,0,1,9,8,4,10,8,10,11,10,4,5,-1,-1,-1,-1,10,11,4,10,4,5,11,3,4,9,4,1,3,1,4,-1,2,5,1,2,8,5,2,11,8,4,5,8,-1,-1,-1,-1,0,4,11,0,11,3,4,5,11,2,11,1,5,1,11,-1,0,2,5,0,5,9,2,11,5,4,5,8,11,8,5,-1,9,4,5,2,11,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,5,10,3,5,2,3,4,5,3,8,4,-1,-1,-1,-1,5,10,2,5,2,4,4,2,0,-1,-1,-1,-1,-1,-1,-1,3,10,2,3,5,10,3,8,5,4,5,8,0,1,9,-1,5,10,2,5,2,4,1,9,2,9,4,2,-1,-1,-1,-1,8,4,5,8,5,3,3,5,1,-1,-1,-1,-1,-1,-1,-1,0,4,5,1,0,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,4,5,8,5,3,9,0,5,0,3,5,-1,-1,-1,-1,9,4,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,11,7,4,9,11,9,10,11,-1,-1,-1,-1,-1,-1,-1,0,8,3,4,9,7,9,11,7,9,10,11,-1,-1,-1,-1,1,10,11,1,11,4,1,4,0,7,4,11,-1,-1,-1,-1,3,1,4,3,4,8,1,10,4,7,4,11,10,11,4,-1,4,11,7,9,11,4,9,2,11,9,1,2,-1,-1,-1,-1,9,7,4,9,11,7,9,1,11,2,11,1,0,8,3,-1,11,7,4,11,4,2,2,4,0,-1,-1,-1,-1,-1,-1,-1,11,7,4,11,4,2,8,3,4,3,2,4,-1,-1,-1,-1,2,9,10,2,7,9,2,3,7,7,4,9,-1,-1,-1,-1,9,10,7,9,7,4,10,2,7,8,7,0,2,0,7,-1,3,7,10,3,10,2,7,4,10,1,10,0,4,0,10,-1,1,10,2,8,7,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,9,1,4,1,7,7,1,3,-1,-1,-1,-1,-1,-1,-1,4,9,1,4,1,7,0,8,1,8,7,1,-1,-1,-1,-1,4,0,3,7,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,8,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,10,8,10,11,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3,0,9,3,9,11,11,9,10,-1,-1,-1,-1,-1,-1,-1,0,1,10,0,10,8,8,10,11,-1,-1,-1,-1,-1,-1,-1,3,1,10,11,3,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,2,11,1,11,9,9,11,8,-1,-1,-1,-1,-1,-1,-1,3,0,9,3,9,11,1,2,9,2,11,9,-1,-1,-1,-1,0,2,11,8,0,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3,2,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,3,8,2,8,10,10,8,9,-1,-1,-1,-1,-1,-1,-1,9,10,2,0,9,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,3,8,2,8,10,0,1,8,1,10,8,-1,-1,-1,-1,1,10,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,3,8,9,1,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,9,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,3,8,-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,-1,-1]),XG.Camera=function(){XG.Node.call(this),this.matrixWorldInverse=new XG.Matrix4,this.projectionMatrix=new XG.Matrix4,this.projectionMatrixInverse=new XG.Matrix4},XG.Camera.prototype=Object.create(XG.Node.prototype),XG.Camera.prototype.lookAt=function(e){this.matrix.lookAt(this.position,e,this.up),this.rotationAutoUpdate===!0&&(this.useQuaternion===!1?this.rotation.setEulerFromRotationMatrix(this.matrix,this.eulerOrder):this.quaternion.copy(this.matrix.decompose()[1]))},XG.Camera.prototype.clone=function(e){return void 0===e&&(e=new XG.Camera),XG.Node.prototype.clone.call(this,e),e.matrixWorldInverse.copy(this.matrixWorldInverse),e.projectionMatrix.copy(this.projectionMatrix),e.projectionMatrixInverse.copy(this.projectionMatrixInverse),e},XG.OrthographicCamera=function(e,t,a,r,i,o){XG.Camera.call(this),this.left=e,this.right=t,this.top=a,this.bottom=r,this.near=void 0!==i?i:.1,this.far=void 0!==o?o:2e3,this.updateProjectionMatrix()},XG.OrthographicCamera.prototype=Object.create(XG.Camera.prototype),XG.OrthographicCamera.prototype.updateProjectionMatrix=function(){this.projectionMatrix.makeOrthographic(this.left,this.right,this.top,this.bottom,this.near,this.far)},XG.OrthographicCamera.prototype.clone=function(e){return void 0===e&&(e=new XG.OrthographicCamera),XG.Camera.prototype.clone.call(this,e),e.left=this.left,e.right=this.right,e.top=this.top,e.bottom=this.bottom,e.near=this.near,e.far=this.far,e},XG.PerspectiveCamera=function(e,t,a,r){XG.Camera.call(this),this.fov=void 0!==e?e:50,this.aspect=void 0!==t?t:1,this.near=void 0!==a?a:.1,this.far=void 0!==r?r:2e3,this.updateProjectionMatrix()},XG.PerspectiveCamera.prototype=Object.create(XG.Camera.prototype),XG.PerspectiveCamera.prototype.updateProjectionMatrix=function(){this.projectionMatrix.makePerspective(this.fov,this.aspect,this.near,this.far)},XG.PerspectiveCamera.prototype.clone=function(e){return void 0===e&&(e=new XG.PerspectiveCamera),XG.Camera.prototype.clone.call(this,e),e.fov=this.fov,e.aspect=this.aspect,e.near=this.near,e.far=this.far,e},XG.CubeCamera=function(e,t){XG.Node.call(this);var a=90,r=1,i=new XG.PerspectiveCamera(a,r,e,t);i.up.set(0,-1,0),i.lookAt(new XG.Vector3(1,0,0)),this.add(i);var o=new XG.PerspectiveCamera(a,r,e,t);o.up.set(0,-1,0),o.lookAt(new XG.Vector3(-1,0,0)),this.add(o);var n=new XG.PerspectiveCamera(a,r,e,t);n.up.set(0,0,1),n.lookAt(new XG.Vector3(0,1,0)),this.add(n);var s=new XG.PerspectiveCamera(a,r,e,t);s.up.set(0,0,-1),s.lookAt(new XG.Vector3(0,-1,0)),this.add(s);var l=new XG.PerspectiveCamera(a,r,e,t);l.up.set(0,-1,0),l.lookAt(new XG.Vector3(0,0,1)),this.add(l);var h=new XG.PerspectiveCamera(a,r,e,t);h.up.set(0,-1,0),h.lookAt(new XG.Vector3(0,0,-1)),this.add(h),this.px=i,this.nx=o,this.py=n,this.ny=s,this.pz=l,this.nz=h},XG.CubeCamera.prototype=Object.create(XG.Node.prototype),XG.Light=function(e){XG.Node.call(this),this.color=new XG.Color(e)},XG.Light.prototype=Object.create(XG.Node.prototype),XG.AreaLight=function(e,t){XG.Light.call(this,e),this.normal=new XG.Vector3(0,-1,0),this.right=new XG.Vector3(1,0,0),this.intensity=void 0!==t?t:1,this.width=1,this.height=1,this.constantAttenuation=1.5,this.linearAttenuation=.5,this.quadraticAttenuation=.1,this.texture=null,this.castShadow=!1,this.onlyShadow=!1,this.shadowCameraNear=50,this.shadowCameraFar=5e3,this.shadowCameraFov=90,this.shadowCameraLeft=-500,this.shadowCameraRight=500,this.shadowCameraTop=500,this.shadowCameraBottom=-500,this.shadowCameraOrtho=!1,this.shadowCameraVisible=!1,this.shadowBias=0,this.shadowDarkness=.5,this.shadowMapWidth=512,this.shadowMapHeight=512},XG.AreaLight.prototype=Object.create(XG.Light.prototype),XG.DayLight=function(e,t,a,r,i){XG.Light.call(this,e),this.skyColor=new XG.Color(t),this.groundColor=new XG.Color(a),this.position=new XG.Vector3(0,100,0),this.hemiPosition=new XG.Vector3(0,100,0),this.target=new XG.Node,this.sunIntensity=void 0!==r?r:1,this.hemiIntensity=void 0!==i?i:1,this.distance=0,this.castShadow=!1,this.shadowCameraNear=50,this.shadowCameraFar=5e3,this.shadowCameraLeft=-500,this.shadowCameraRight=500,this.shadowCameraTop=500,this.shadowCameraBottom=-500,this.shadowCameraVisible=!1,this.shadowBias=0,this.shadowDarkness=.5,this.shadowMapWidth=512,this.shadowMapHeight=512,this.shadowCascade=!1,this.shadowCascadeOffset=new XG.Vector3(0,0,-1e3),this.shadowCascadeCount=2,this.shadowCascadeBias=[0,0,0,0],this.shadowCascadeWidth=[512,512,512,512],this.shadowCascadeHeight=[512,512,512,512],this.shadowCascadeNearZ=[-1,.99,.998],this.shadowCascadeFarZ=[.99,.998,1],this.shadowCascadeArray=[],this.texture=null,this.textureCameraLeft=-500,this.textureCameraRight=500,this.textureCameraTop=500,this.textureCameraBottom=-500,this.textureCameraNear=1,this.textureCameraFar=5e3,this.textureWidth=512,this.textureHeight=512,this.textureBias=-4,this.castTransparentShadow=!1
  },XG.DayLight.prototype=Object.create(XG.Light.prototype),XG.DayLightCube=function(e,t){XG.Light.call(this,e),this.position=new XG.Vector3(0,100,0),this.target=new XG.Node,this.intensity=void 0!==t?t:1,this.distance=0,this.textureSpecular=null,this.textureDiffuse=null,this.ambientIntensity=1,this.castShadow=!1,this.shadowCameraNear=50,this.shadowCameraFar=5e3,this.shadowCameraLeft=-500,this.shadowCameraRight=500,this.shadowCameraTop=500,this.shadowCameraBottom=-500,this.shadowCameraVisible=!1,this.shadowBias=0,this.shadowDarkness=.5,this.shadowMapWidth=512,this.shadowMapHeight=512,this.shadowCascade=!1,this.shadowCascadeOffset=new XG.Vector3(0,0,-1e3),this.shadowCascadeCount=2,this.shadowCascadeBias=[0,0,0,0],this.shadowCascadeWidth=[512,512,512,512],this.shadowCascadeHeight=[512,512,512,512],this.shadowCascadeNearZ=[-1,.99,.998],this.shadowCascadeFarZ=[.99,.998,1],this.shadowCascadeArray=[],this.texture=null,this.textureCameraLeft=-500,this.textureCameraRight=500,this.textureCameraTop=500,this.textureCameraBottom=-500,this.textureCameraNear=1,this.textureCameraFar=5e3,this.textureWidth=512,this.textureHeight=512,this.textureBias=-4,this.castTransparentShadow=!1},XG.DayLightCube.prototype=Object.create(XG.Light.prototype),XG.DirectionalLight=function(e,t){XG.Light.call(this,e),this.position=new XG.Vector3(0,1,0),this.target=new XG.Node,this.intensity=void 0!==t?t:1,this.distance=0,this.castShadow=!1,this.onlyShadow=!1,this.shadowCameraNear=50,this.shadowCameraFar=5e3,this.shadowCameraLeft=-500,this.shadowCameraRight=500,this.shadowCameraTop=500,this.shadowCameraBottom=-500,this.shadowCameraVisible=!1,this.shadowBias=0,this.shadowDarkness=.5,this.shadowMapWidth=512,this.shadowMapHeight=512,this.shadowCascade=!1,this.shadowCascadeOffset=new XG.Vector3(0,0,-1e3),this.shadowCascadeCount=2,this.shadowCascadeBias=[0,0,0,0],this.shadowCascadeWidth=[512,512,512,512],this.shadowCascadeHeight=[512,512,512,512],this.shadowCascadeNearZ=[-1,.99,.998],this.shadowCascadeFarZ=[.99,.998,1],this.shadowCascadeArray=[],this.texture=null,this.textureCameraLeft=-500,this.textureCameraRight=500,this.textureCameraTop=500,this.textureCameraBottom=-500,this.textureCameraNear=1,this.textureCameraFar=5e3,this.textureWidth=512,this.textureHeight=512,this.textureBias=-4,this.castTransparentShadow=!1},XG.DirectionalLight.prototype=Object.create(XG.Light.prototype),XG.HemisphereLight=function(e,t,a){XG.Light.call(this,e),this.groundColor=new XG.Color(t),this.position=new XG.Vector3(0,100,0),this.intensity=void 0!==a?a:1},XG.HemisphereLight.prototype=Object.create(XG.Light.prototype),XG.PointLight=function(e,t,a){XG.Light.call(this,e),this.position=new XG.Vector3(0,0,0),this.intensity=void 0!==t?t:1,this.distance=void 0!==a?a:0,this.castShadow=!1,this.onlyShadow=!1,this.shadowCameraNear=50,this.shadowCameraFar=5e3,this.shadowCameraVisible=!1,this.shadowBias=0,this.shadowDarkness=.5,this.shadowMapWidth=512,this.shadowMapHeight=512},XG.PointLight.prototype=Object.create(XG.Light.prototype),XG.SphereLight=function(e,t,a,r){XG.Light.call(this,e),this.position=new XG.Vector3(0,0,0),this.intensity=void 0!==t?t:1,this.distance=void 0!==a?a:0,this.radius=void 0!==r?r:1,this.castShadow=!1,this.onlyShadow=!1,this.shadowCameraNear=50,this.shadowCameraFar=5e3,this.shadowCameraVisible=!1,this.shadowBias=0,this.shadowDarkness=.5,this.shadowMapWidth=512,this.shadowMapHeight=512,this.forwardShadowSide=0},XG.SphereLight.prototype=Object.create(XG.Light.prototype),XG.TubeLight=function(e,t,a,r,i){XG.Light.call(this,e),this.position=new XG.Vector3(0,0,0),this.intensity=void 0!==t?t:1,this.distance=void 0!==a?a:0,this.radius=void 0!==r?r:.1,this.length=void 0!==i?r:5,this.occlusionEnabled=!1,this.castShadow=!1,this.onlyShadow=!1,this.endPoint0=new XG.Node,this.endPoint1=new XG.Node,this.endPoint0.position.y=.5*-i,this.endPoint1.position.y=.5*i,this.add(this.endPoint0),this.add(this.endPoint1)},XG.TubeLight.prototype=Object.create(XG.Light.prototype),XG.SpotLight=function(e,t,a,r,i){XG.Light.call(this,e),this.position=new XG.Vector3(0,1,0),this.target=new XG.Node,this.intensity=void 0!==t?t:1,this.distance=void 0!==a?a:0,this.angle=void 0!==r?r:Math.PI/2,this.exponent=void 0!==i?i:10,this.castShadow=!1,this.onlyShadow=!1,this.shadowCameraNear=50,this.shadowCameraFar=5e3,this.shadowCameraFov=50,this.shadowCameraVisible=!1,this.shadowBias=0,this.shadowDarkness=.5,this.shadowMapWidth=512,this.shadowMapHeight=512,this.texture=null,this.textureCameraNear=1,this.textureCameraFar=5e3,this.textureCameraFov=50,this.textureCameraAspectScale=1,this.textureWidth=512,this.textureHeight=512,this.textureBias=-4,this.castTransparentShadow=!1},XG.SpotLight.prototype=Object.create(XG.Light.prototype),XG.ImageLight=function(e,t,a){XG.Light.call(this,16777215),this.textureSpecular=e,this.textureDiffuse=t,this.textureMip=e,this.intensity=void 0!==a?a:1,this.local=!1,this.size=new XG.Vector3(1,1,1)},XG.ImageLight.prototype=Object.create(XG.Light.prototype),XG.LightProxy=function(e,t){this.light=e,this.renderer=t},XG.LightProxy.prototype=Object.create(XG.Mesh.prototype),XG.LightProxy.prototype.update=function(e){var t=this.materials[0].uniforms;t.matProj&&(t.matProj.value=e.projectionMatrix),t.matProjInverse&&(t.matProjInverse.value=e.projectionMatrixInverse),t.matView&&(t.matView.value=e.matrixWorldInverse),t.matViewInverse&&(t.matViewInverse.value=e.matrixWorld),this.light&&(this.visible=this.light.visible)},XG.LightProxy.prototype.resize=function(e,t){var a=this.materials[0],r=a.uniforms;r.viewSize&&r.viewSize.value.set(e,t)},XG.LightProxy.prototype.setSamplers=function(e){var t=this.renderer,a=e.uniforms,r=t.getUseMultipleRenderTargets();if(r){var i=t.getCombinedTarget();a.viewSize.value.set(i.width,i.height),a.samplerDiffuseRGB&&(a.samplerDiffuseRGB.value=i.colorTexture[0]),a.samplerSpecularRGB&&(a.samplerSpecularRGB.value=i.colorTexture[1]),a.samplerWrapRGB&&(a.samplerWrapRGB.value=i.colorTexture[2]),a.samplerNormal&&(a.samplerNormal.value=i.colorTexture[3]),a.samplerDepth&&(a.samplerDepth.value=t.useDepthTexture?i.depthTexture:i.colorTexture[4])}else{var o=t.getColorTarget(),n=t.getNormalDepthTarget();a.viewSize.value.set(o.width,o.height),a.samplerColor&&(a.samplerColor.value=o),a.samplerNormalDepth&&(a.samplerNormalDepth.value=n)}var s=t.getSSAOTarget();a.samplerSSAO&&(a.samplerSSAO.value=s)},XG.LightProxy.prototype.generateDefines=function(){var e=this.light,t=this.renderer,a="webgl2"===t.renderer.getRenderingBackend(),r=t.shadowMapUseDepthTextures&&t.renderer.supportsDepthTextures(),i={};if(t.shadowMapEnabled&&e&&e.castShadow){i.USE_SHADOWMAP=!0;var o=void 0!==e.shadowMapType?e.shadowMapType:t.shadowMapType;switch(o){case XG.BasicShadowMap:i.SHADOWMAP_TYPE_BASIC=!0;break;case XG.PCFSoftShadowMap:i.SHADOWMAP_TYPE_PCF_SOFT=!0;break;case XG.PCFSoftHQShadowMap:i.SHADOWMAP_TYPE_PCF_SOFT_HQ=!0}i.SLOPE_DEPTH_BIAS=t.shadowMapSlopeDepthBias,i.SHADOWMAP_DEBUG=t.shadowMapDebug,i.DEPTH_TEXTURES=t.shadowMapUseDepthTextures&&t.renderer.supportsDepthTextures(),i.USE_SHADOWSAMPLER=a&&r}return t.ssaoEnabled&&e&&(i.USE_SSAO=!0),t.skinHighQuality&&(i.SKIN_HQ=!0),i.USE_MRT=t.getUseMultipleRenderTargets(),i.TEXTURE_DEPTH=t.useDepthTexture,i.PROJECTED_TEXTURE=!!e.texture||!!e.castTransparentShadow,i.PROJECTED_SHADOW=!!e.castTransparentShadow,i},XG.LightProxy.prototype.getShadowMapParameters=function(){var e,t=this.renderer,a=t.renderer,r=!a.supportsDepthOnlyRenderTarget(),i="webgl2"===a.getRenderingBackend(),o=a.supportsLuminanceFloatRenderTarget()?XG.LuminanceFormat:a.supportsRGBFloatRenderTarget()?XG.RGBFormat:XG.RGBAFormat;if(i)switch(o){case XG.LuminanceFormat:e=XG.R32F,o=XG.RED;break;case XG.RGBFormat:e=XG.RGB32F;break;case XG.RGBAFormat:e=XG.RGBA32F}else e=o;var n={minFilter:XG.NearestFilter,magFilter:XG.NearestFilter,stencilBuffer:!1,format:o,internalFormat:e,type:XG.FloatType};if(i)var s={minFilter:XG.LinearFilter,magFilter:XG.LinearFilter,useColorTexture:r,stencilBuffer:!1,format:o,useDepthTexture:!0,depthTextureType:t.shadowMapDepthTextureType};else var s={minFilter:XG.NearestFilter,magFilter:XG.NearestFilter,useColorTexture:r,stencilBuffer:!1,format:o,useDepthTexture:!0,depthTextureType:t.shadowMapDepthTextureType};var l=t.shadowMapUseDepthTextures&&a.supportsDepthTextures(),h=l?s:n;return h},XG.LightProxy.prototype.setupDirectionalShadowmap=function(e){var t=this.light,a=t.properties,r=this.getShadowMapParameters();a.shadowMap=[],a.shadowMatrixDeferred=[],a.shadowMatrixForward=[],a.shadowCamera=[],a.pointsWorld=[],a.pointsFrustum=[];for(var i=0;e>i;i++){var o=new XG.RenderTarget(t.shadowMapWidth,t.shadowMapHeight,r);o.generateMipmaps=!1,a.shadowMap[i]=o;var n=new XG.OrthographicCamera(t.shadowCameraLeft,t.shadowCameraRight,t.shadowCameraTop,t.shadowCameraBottom,t.shadowCameraNear,t.shadowCameraFar);if(a.shadowCamera[i]=n,a.shadowMatrixDeferred[i]=new XG.Matrix4,a.shadowMatrixForward[i]=new XG.Matrix4,t.shadowCascade){a.pointsWorld[i]=[],a.pointsFrustum[i]=[];for(var s=a.pointsWorld[i],l=a.pointsFrustum[i],h=0;8>h;h++)s[h]=new XG.Vector3,l[h]=new XG.Vector3;var d=t.shadowCascadeNearZ[i],c=t.shadowCascadeFarZ[i];l[0].set(-1,-1,d),l[1].set(1,-1,d),l[2].set(-1,1,d),l[3].set(1,1,d),l[4].set(-1,-1,c),l[5].set(1,-1,c),l[6].set(-1,1,c),l[7].set(1,1,c)}a.shadowMapPars=new XG.Vector4(t.shadowMapWidth,t.shadowMapHeight,t.shadowDarkness,t.shadowBias)}t.properties.cascadeCount=e},XG.LightProxy.prototype.updateDirectionalShadowmap=function(e){var t=this.light,a=this.materials[0].uniforms,r=t.properties;if(t.shadowCascade&&!r.gyro){var i=new XG.Gyroscope;i.position=t.shadowCascadeOffset,i.add(t),i.add(t.target),e.add(i),r.gyro=i;var o=e.getTopParent();if(void 0!==o&&o instanceof XG.Scene){var n=new XG.Node,s=new XG.Node;o.add(n),o.add(s),n.position=t.position,s.position=t.target.position,t.properties.nonGyroLight=n,t.properties.nonGyroTarget=s}else console.error("XG.LightProxy.updateDirectionalShadowmap: can't find parent scene node")}for(var l=0;l<r.cascadeCount;l++){var h=r.shadowMatrixDeferred[l],d=r.shadowMatrixForward[l],c=r.shadowCamera[l],u=r.shadowMap[l];h.multiply(c.projectionMatrix,c.matrixWorldInverse),d.multiply(XG.LightProxy.biasMatrix,h),h.multiplySelf(e.matrixWorld),a.matShadow.value[l]=h,a.samplerShadowMap.value[l]=u.useDepthTexture?u.depthTexture:u}a.shadowDarkness.value=Math.sqrt(t.shadowDarkness),a.shadowBias.value=t.shadowBias,a.shadowMapSize.value.set(t.shadowMapWidth,t.shadowMapHeight)},XG.LightProxy.prototype.setupProjectedTexture=function(){var e=this.light,t=e.properties,a=new XG.OrthographicCamera(e.textureCameraLeft,e.textureCameraRight,e.textureCameraTop,e.textureCameraBottom,e.textureCameraNear,e.textureCameraFar);if(t.textureCamera=a,t.textureMatrixDeferred=new XG.Matrix4,e.castTransparentShadow){var r={minFilter:XG.LinearMipMapLinearFilter,magFilter:XG.LinearFilter,stencilBuffer:!1,format:XG.RGBAFormat,type:XG.UnsignedByteType},i=new XG.RenderTarget(e.textureWidth,e.textureHeight,r);e.shadowCascade||e.textureWidth!==e.shadowMapWidth||e.textureHeight!==e.shadowMapHeight||(i.shareDepthFrom=t.shadowMap[0]),e.texture=i}},XG.LightProxy.prototype.updateProjectedTexture=function(e){var t=this.light,a=this.materials[0].uniforms,r=(t.properties,t.properties.textureMatrixDeferred),i=t.properties.textureCamera;if(i.left=t.textureCameraLeft,i.right=t.textureCameraRight,i.top=t.textureCameraTop,i.bottom=t.textureCameraBottom,i.near=t.textureCameraNear,i.far=t.textureCameraFar,i.updateProjectionMatrix(),t.properties.gyro)var o=t.properties.nonGyroLight,n=t.properties.nonGyroTarget;else var o=t,n=t.target;i.position.copy(o.matrixWorld.getPosition()),t.target&&i.lookAt(n.matrixWorld.getPosition()),i.updateMatrixWorld(),i.matrixWorldInverse.getInverse(i.matrixWorld),r.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),r.multiplySelf(i.projectionMatrix),r.multiplySelf(i.matrixWorldInverse),r.multiplySelf(e.matrixWorld),a.matTexture.value=r,a.samplerTexture.value=t.texture,a.textureBias.value=t.textureBias},XG.LightProxy.geometryLightSphere=new XG.SphereGeometry(1,16,8),XG.LightProxy.geometryLightPlane=new XG.PlaneGeometry(2,2),XG.LightProxy.geometryLightBox=new XG.BoxGeometry(1,1,1),XG.LightProxy.positionVS=new XG.Vector3,XG.LightProxy.directionVS=new XG.Vector3,XG.LightProxy.rightVS=new XG.Vector3,XG.LightProxy.normalVS=new XG.Vector3,XG.LightProxy.upVS=new XG.Vector3,XG.LightProxy.biasMatrix=new XG.Matrix4(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),XG.SpotLightProxy=function(e,t){XG.LightProxy.call(this,e,t);var a=XG.DeferredShaders.spotLight,r=XG.UniformsUtils.clone(a.uniforms),i=this.generateDefines(),o={};t.skinHighQuality&&(o.OES_standard_derivatives=!0);var n=new XG.ShaderMaterial({uniforms:r,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,defines:i,extensions:o,blending:XG.AdditiveBlending,depthWrite:!1,depthTest:!1,transparent:!0});this.setSamplers(n);var s=XG.LightProxy.geometryLightPlane;XG.Mesh.call(this,s,n);var l=e.properties;if(e.castShadow&&this.setupShadowmap(),e.texture||e.castTransparentShadow){var h=e.textureCameraAspectScale;if(e.texture){var d=e.texture.image;h*=d.width/d.height}var c=new XG.PerspectiveCamera(e.textureCameraFov,h,e.textureCameraNear,e.textureCameraFar);if(l.textureCamera=c,l.textureMatrixDeferred=new XG.Matrix4,e.castTransparentShadow){var u={minFilter:XG.LinearMipMapLinearFilter,magFilter:XG.LinearFilter,stencilBuffer:!1,format:XG.RGBAFormat,type:XG.UnsignedByteType},f=new XG.RenderTarget(e.textureWidth,e.textureHeight,u);e.shadowCascade||e.textureWidth!==e.shadowMapWidth||e.textureHeight!==e.shadowMapHeight||(f.shareDepthFrom=l.shadowMap),e.texture=f}}},XG.SpotLightProxy.prototype=Object.create(XG.LightProxy.prototype),XG.SpotLightProxy.prototype.setupShadowmap=function(){var e=this.light,t=e.properties,a=this.getShadowMapParameters(),r=new XG.RenderTarget(e.shadowMapWidth,e.shadowMapHeight,a);r.wrapS=XG.MirroredRepeatWrapping,r.wrapT=XG.MirroredRepeatWrapping,r.generateMipmaps=!1,t.shadowMap=r;var i=e.shadowMapWidth/e.shadowMapHeight,o=new XG.PerspectiveCamera(e.shadowCameraFov,i,e.shadowCameraNear,e.shadowCameraFar);t.shadowCamera=o,t.shadowMatrixDeferred=new XG.Matrix4,t.shadowMatrixForward=new XG.Matrix4,t.shadowMapPars=new XG.Vector4(e.shadowMapWidth,e.shadowMapHeight,e.shadowDarkness,e.shadowBias)},XG.SpotLightProxy.prototype.update=function(e){XG.LightProxy.prototype.update.call(this,e);var t=this.light,a=this.materials[0].uniforms,r=e.matrixWorldInverse,i=t.matrixWorld,o=XG.LightProxy.positionVS,n=XG.LightProxy.directionVS;o.copy(i.getPosition()),r.multiplyVector3(o),n.copy(i.getPosition()),n.subSelf(t.target.matrixWorld.getPosition()),n.normalize(),r.rotateAxis(n),a.lightPositionVS.value.copy(o),a.lightDirectionVS.value.copy(n),a.lightAngleCos.value=Math.cos(.5*t.angle),a.lightDistance.value=t.distance;var s=t.intensity*t.intensity;if(a.lightIntensity.value=s,a.lightColor.value.copyGammaToLinear(t.color),t.castShadow){var l=t.properties.shadowMatrixDeferred,h=t.properties.shadowMatrixForward,d=t.properties.shadowCamera,c=t.properties.shadowMap;l.multiply(d.projectionMatrix,d.matrixWorldInverse),h.multiply(XG.LightProxy.biasMatrix,l),l.multiplySelf(e.matrixWorld),a.matShadow.value=l,a.samplerShadowMap.value=c.useDepthTexture?c.depthTexture:c,a.shadowDarkness.value=Math.sqrt(t.shadowDarkness),a.shadowBias.value=t.shadowBias,a.shadowMapSize.value.set(t.shadowMapWidth,t.shadowMapHeight)}if(t.texture){var u=t.properties.textureMatrixDeferred,f=t.properties.textureCamera,p=t.texture.image?t.texture.image:t.texture,m=p.width/p.height;f.fov=t.textureCameraFov,f.near=t.textureCameraNear,f.far=t.textureCameraFar,f.aspect=m*t.textureCameraAspectScale,f.updateProjectionMatrix(),f.position.copy(t.matrixWorld.getPosition()),t.target&&f.lookAt(t.target.matrixWorld.getPosition()),f.updateMatrixWorld(),f.matrixWorldInverse.getInverse(f.matrixWorld),u.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),u.multiplySelf(f.projectionMatrix),u.multiplySelf(f.matrixWorldInverse),u.multiplySelf(e.matrixWorld),a.matTexture.value=u,a.samplerTexture.value=t.texture,a.textureBias.value=t.textureBias}},XG.AreaLightProxy=function(e,t){XG.LightProxy.call(this,e,t);var a=XG.DeferredShaders.areaLight,r=XG.UniformsUtils.clone(a.uniforms),i=this.generateDefines();i.AREA_TEXTURE=!!e.texture;var o={};t.skinHighQuality&&(o.OES_standard_derivatives=!0);var n=new XG.ShaderMaterial({uniforms:r,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,defines:i,extensions:o,blending:XG.AdditiveBlending,depthWrite:!1,depthTest:!1,transparent:!0});this.setSamplers(n);var s=XG.LightProxy.geometryLightPlane;XG.Mesh.call(this,s,n),e.castShadow&&this.setupShadowmap()},XG.AreaLightProxy.prototype=Object.create(XG.LightProxy.prototype),XG.AreaLightProxy.prototype.setupShadowmap=function(){var e=this.light,t=e.properties,a=this.getShadowMapParameters(),r=new XG.RenderTarget(e.shadowMapWidth,e.shadowMapHeight,a);if(r.generateMipmaps=!1,t.shadowMap=r,e.shadowCameraOrtho)var i=new XG.OrthographicCamera(e.shadowCameraLeft,e.shadowCameraRight,e.shadowCameraTop,e.shadowCameraBottom,e.shadowCameraNear,e.shadowCameraFar);else var o=e.shadowMapWidth/e.shadowMapHeight,i=new XG.PerspectiveCamera(e.shadowCameraFov,o,e.shadowCameraNear,e.shadowCameraFar);t.shadowCamera=i,t.shadowMatrixDeferred=new XG.Matrix4,t.shadowMatrixForward=new XG.Matrix4,t.shadowMapPars=new XG.Vector4(e.shadowMapWidth,e.shadowMapHeight,e.shadowDarkness,e.shadowBias)},XG.AreaLightProxy.prototype.update=function(e){XG.LightProxy.prototype.update.call(this,e);var t=this.light,a=this.materials[0].uniforms,r=t.matrixWorld,i=e.matrixWorldInverse,o=XG.LightProxy.positionVS,n=XG.LightProxy.rightVS,s=XG.LightProxy.normalVS,l=XG.LightProxy.upVS;o.copy(r.getPosition()),i.multiplyVector3(o),a.lightPositionVS.value.copy(o),n.copy(t.right),s.copy(t.normal),r.rotateAxis(n),r.rotateAxis(s),i.rotateAxis(n),i.rotateAxis(s),l.cross(n,s),l.normalize(),a.lightRightVS.value.copy(n),a.lightNormalVS.value.copy(s),a.lightUpVS.value.copy(l),a.lightWidth.value=t.width,a.lightHeight.value=t.height,a.constantAttenuation.value=t.constantAttenuation,a.linearAttenuation.value=t.linearAttenuation,a.quadraticAttenuation.value=t.quadraticAttenuation,a.samplerTexture.value=t.texture;var h=t.intensity*t.intensity;if(a.lightIntensity.value=h,a.lightColor.value.copyGammaToLinear(t.color),t.castShadow){var d=t.properties.shadowMatrixDeferred,c=t.properties.shadowMatrixForward,u=t.properties.shadowCamera,f=t.properties.shadowMap;d.multiply(u.projectionMatrix,u.matrixWorldInverse),c.multiply(XG.LightProxy.biasMatrix,d),d.multiplySelf(e.matrixWorld),a.matShadow.value=d,a.samplerShadowMap.value=f.useDepthTexture?f.depthTexture:f,a.shadowDarkness.value=Math.sqrt(t.shadowDarkness),a.shadowBias.value=t.shadowBias,a.shadowMapSize.value.set(t.shadowMapWidth,t.shadowMapHeight)}},XG.DayLightProxy=function(e,t){XG.LightProxy.call(this,e,t);var a=XG.DeferredShaders.dayLight,r=XG.UniformsUtils.clone(a.uniforms),i=this.generateDefines(e),o=e.shadowCascade?e.shadowCascadeCount:1;i.SHADOWMAP_COUNT=o;var n={};t.skinHighQuality&&(n.OES_standard_derivatives=!0);var s=new XG.ShaderMaterial({uniforms:r,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,defines:i,extensions:n,blending:XG.AdditiveBlending,depthWrite:!1,depthTest:!1,transparent:!0});this.setSamplers(s);var l=XG.LightProxy.geometryLightPlane;XG.Mesh.call(this,l,s),e.castShadow&&this.setupDirectionalShadowmap(o),(e.texture||e.castTransparentShadow)&&this.setupProjectedTexture()},XG.DayLightProxy.prototype=Object.create(XG.LightProxy.prototype),XG.DayLightProxy.prototype.update=function(e){XG.LightProxy.prototype.update.call(this,e);var t=this.light,a=this.materials[0].uniforms,r=XG.LightProxy.directionVS;r.copy(t.matrixWorld.getPosition()),r.subSelf(t.target.matrixWorld.getPosition()),r.normalize(),e.matrixWorldInverse.rotateAxis(r),a.lightDirectionVSSun.value.copy(r),r.copy(t.hemiPosition),r.normalize(),e.matrixWorldInverse.rotateAxis(r),a.lightDirectionVSHemi.value.copy(r);var i=t.sunIntensity*t.sunIntensity,o=t.hemiIntensity*t.hemiIntensity;a.lightIntensitySun.value=i,a.lightIntensityHemi.value=o,a.lightColorSun.value.copyGammaToLinear(t.color),a.lightColorSky.value.copyGammaToLinear(t.skyColor),a.lightColorGround.value.copyGammaToLinear(t.groundColor),t.castShadow&&this.updateDirectionalShadowmap(e),t.texture&&this.updateProjectedTexture(e)},XG.DayLightCubeProxy=function(e,t){XG.LightProxy.call(this,e,t);var a=XG.DeferredShaders.dayLightCube,r=XG.UniformsUtils.clone(a.uniforms),i=this.generateDefines(e),o={},n=e.shadowCascade?e.shadowCascadeCount:1;i.SHADOWMAP_COUNT=n,t.specularMipFix&&(i.SPECULAR_MIP_FIX=!0),(t.skinHighQuality||t.specularMipFix)&&(o.OES_standard_derivatives=!0),t.renderer.supportsShaderTextureLod()&&(o.EXT_shader_texture_lod=!0);var s=new XG.ShaderMaterial({uniforms:r,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,defines:i,extensions:o,blending:XG.AdditiveBlending,depthWrite:!1,depthTest:!1,transparent:!0});this.setSamplers(s);var l=XG.LightProxy.geometryLightPlane;XG.Mesh.call(this,l,s),e.castShadow&&this.setupDirectionalShadowmap(n),(e.texture||e.castTransparentShadow)&&this.setupProjectedTexture()},XG.DayLightCubeProxy.prototype=Object.create(XG.LightProxy.prototype),XG.DayLightCubeProxy.prototype.update=function(e){XG.LightProxy.prototype.update.call(this,e);var t=this.light,a=this.materials[0].uniforms,r=XG.LightProxy.directionVS;r.copy(t.matrixWorld.getPosition()),r.subSelf(t.target.matrixWorld.getPosition()),r.normalize(),e.matrixWorldInverse.rotateAxis(r),a.lightDirectionVSSun.value.copy(r),a.samplerSpecular.value=t.textureSpecular,a.samplerDiffuse.value=t.textureDiffuse,a.maxMipSpecular.value=t.textureSpecular.mipmapCount;var i=t.intensity*t.intensity,o=t.ambientIntensity*t.ambientIntensity;a.lightIntensitySun.value=i,a.lightIntensityAmbient.value=o,a.lightColorSun.value.copyGammaToLinear(t.color),t.castShadow&&this.updateDirectionalShadowmap(e),t.texture&&this.updateProjectedTexture(e)},XG.DirectionalLightProxy=function(e,t){XG.LightProxy.call(this,e,t);var a=XG.DeferredShaders.directionalLight,r=XG.UniformsUtils.clone(a.uniforms),i=this.generateDefines(e),o={};t.skinHighQuality&&(o.OES_standard_derivatives=!0);var n=e.shadowCascade?e.shadowCascadeCount:1;i.SHADOWMAP_COUNT=n;var s=new XG.ShaderMaterial({uniforms:r,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,defines:i,extensions:o,blending:XG.AdditiveBlending,depthWrite:!1,depthTest:!1,transparent:!0});this.setSamplers(s);var l=XG.LightProxy.geometryLightPlane;XG.Mesh.call(this,l,s),e.castShadow&&this.setupDirectionalShadowmap(n),(e.texture||e.castTransparentShadow)&&this.setupProjectedTexture()},XG.DirectionalLightProxy.prototype=Object.create(XG.LightProxy.prototype),XG.DirectionalLightProxy.prototype.update=function(e){XG.LightProxy.prototype.update.call(this,e);var t=this.light,a=this.materials[0].uniforms,r=XG.LightProxy.directionVS;r.copy(t.matrixWorld.getPosition()),r.subSelf(t.target.matrixWorld.getPosition()),r.normalize(),e.matrixWorldInverse.rotateAxis(r),a.lightDirectionVS.value.copy(r);var i=t.intensity*t.intensity;a.lightIntensity.value=i,a.lightColor.value.copyGammaToLinear(t.color),t.castShadow&&this.updateDirectionalShadowmap(e),t.texture&&this.updateProjectedTexture(e)},XG.HemisphereLightProxy=function(e,t){XG.LightProxy.call(this,e,t);var a=XG.DeferredShaders.hemisphereLight,r=XG.UniformsUtils.clone(a.uniforms),i=this.generateDefines(e),o={};t.skinHighQuality&&(o.OES_standard_derivatives=!0);var n=new XG.ShaderMaterial({uniforms:r,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,defines:i,extensions:o,blending:XG.AdditiveBlending,depthWrite:!1,depthTest:!1,transparent:!0});this.setSamplers(n);var s=XG.LightProxy.geometryLightPlane;XG.Mesh.call(this,s,n)},XG.HemisphereLightProxy.prototype=Object.create(XG.LightProxy.prototype),XG.HemisphereLightProxy.prototype.update=function(e){XG.LightProxy.prototype.update.call(this,e);var t=this.light,a=this.materials[0].uniforms,r=XG.LightProxy.directionVS;r.copy(t.matrixWorld.getPosition()),r.normalize(),e.matrixWorldInverse.rotateAxis(r),a.lightDirectionVS.value.copy(r);var i=t.intensity*t.intensity;a.lightIntensity.value=i,a.lightColorSky.value.copyGammaToLinear(t.color),a.lightColorGround.value.copyGammaToLinear(t.groundColor)},XG.PointLightProxy=function(e,t){XG.LightProxy.call(this,e,t);var a=XG.DeferredShaders.pointLight,r=XG.UniformsUtils.clone(a.uniforms),i=this.generateDefines();i.SHADOWMAP_COUNT=6;var o={};t.skinHighQuality&&(o.OES_standard_derivatives=!0);var n,s=new XG.ShaderMaterial({uniforms:r,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,defines:i,extensions:o,blending:XG.AdditiveBlending,depthWrite:!1,transparent:!0});e.distance>0?(n=XG.LightProxy.geometryLightSphere,s.depthTest=!0,s.side=XG.BackSide):(n=XG.LightProxy.geometryLightPlane,s.depthTest=!1,s.side=XG.FrontSide),this.setSamplers(s),XG.Mesh.call(this,n,s),e.castShadow&&this.setupShadowmap()},XG.PointLightProxy.prototype=Object.create(XG.LightProxy.prototype),XG.PointLightProxy.prototype.setupShadowmap=function(){var e=this.light,t=e.properties,a=this.getShadowMapParameters();t.shadowMap=[],t.shadowCamera=[],t.shadowMatrixDeferred=[],t.shadowMatrixForward=[];for(var r=[new XG.Vector3(0,-1,0),new XG.Vector3(0,-1,0),new XG.Vector3(0,0,1),new XG.Vector3(0,0,-1),new XG.Vector3(0,-1,0),new XG.Vector3(0,-1,0)],i=[new XG.Vector3(1,0,0),new XG.Vector3(-1,0,0),new XG.Vector3(0,1,0),new XG.Vector3(0,-1,0),new XG.Vector3(0,0,1),new XG.Vector3(0,0,-1)],o=0;6>o;o++){var n=new XG.RenderTarget(e.shadowMapWidth,e.shadowMapHeight,a);n.generateMipmaps=!1,t.shadowMap[o]=n;var s=e.shadowMapWidth/e.shadowMapHeight,l=new XG.PerspectiveCamera(90,s,e.shadowCameraNear,e.shadowCameraFar);l.up.copy(r[o]),l.lookAt(i[o]),t.shadowCamera[o]=l,t.shadowMatrixDeferred[o]=new XG.Matrix4,t.shadowMatrixForward[o]=new XG.Matrix4}},XG.PointLightProxy.prototype.update=function(e){XG.LightProxy.prototype.update.call(this,e);var t=this.light,a=this.materials[0].uniforms,r=t.properties,i=t.distance;if(i>0){var o=XG.LightProxy.positionVS;this.scale.set(1,1,1).multiplyScalar(i),a.lightDistance.value=i,o.copy(t.matrixWorld.getPosition()),e.matrixWorldInverse.multiplyVector3(o),a.lightPositionVS.value.copy(o),this.position.copy(t.matrixWorld.getPosition())}else a.lightDistance.value=1/0;var n=t.intensity*t.intensity;if(a.lightIntensity.value=n,a.lightColor.value.copyGammaToLinear(t.color),t.castShadow){for(var s=0;6>s;s++){var l=r.shadowMatrixDeferred[s],h=r.shadowMatrixForward[s],d=r.shadowCamera[s],c=r.shadowMap[s];l.multiply(d.projectionMatrix,d.matrixWorldInverse),h.multiply(XG.LightProxy.biasMatrix,l),l.multiplySelf(e.matrixWorld),a.matShadow.value[s]=l,a.samplerShadowMap.value[s]=c.useDepthTexture?c.depthTexture:c}a.shadowDarkness.value=Math.sqrt(t.shadowDarkness),a.shadowBias.value=t.shadowBias,a.shadowMapSize.value.set(t.shadowMapWidth,t.shadowMapHeight)}},XG.SphereLightProxy=function(e,t){XG.LightProxy.call(this,e,t);var a=XG.DeferredShaders.sphereLight,r=XG.UniformsUtils.clone(a.uniforms),i=this.generateDefines();i.SHADOWMAP_COUNT=6;var o={};t.skinHighQuality&&(o.OES_standard_derivatives=!0);var n,s=new XG.ShaderMaterial({uniforms:r,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,defines:i,extensions:o,blending:XG.AdditiveBlending,depthWrite:!1,transparent:!0});e.distance>0?(n=XG.LightProxy.geometryLightSphere,s.depthTest=!0,s.side=XG.BackSide):(n=XG.LightProxy.geometryLightPlane,s.depthTest=!1,s.side=XG.FrontSide),this.setSamplers(s),XG.Mesh.call(this,n,s),e.castShadow&&this.setupShadowmap()},XG.SphereLightProxy.prototype=Object.create(XG.LightProxy.prototype),XG.SphereLightProxy.prototype.setupShadowmap=function(){var e=this.light,t=e.properties,a=this.getShadowMapParameters();t.shadowMap=[],t.shadowCamera=[],t.shadowMatrixDeferred=[],t.shadowMatrixForward=[];for(var r=[new XG.Vector3(0,-1,0),new XG.Vector3(0,-1,0),new XG.Vector3(0,0,1),new XG.Vector3(0,0,-1),new XG.Vector3(0,-1,0),new XG.Vector3(0,-1,0)],i=[new XG.Vector3(1,0,0),new XG.Vector3(-1,0,0),new XG.Vector3(0,1,0),new XG.Vector3(0,-1,0),new XG.Vector3(0,0,1),new XG.Vector3(0,0,-1)],o=0;6>o;o++){var n=new XG.RenderTarget(e.shadowMapWidth,e.shadowMapHeight,a);n.generateMipmaps=!1,t.shadowMap[o]=n;var s=e.shadowMapWidth/e.shadowMapHeight,l=new XG.PerspectiveCamera(90,s,e.shadowCameraNear,e.shadowCameraFar);l.up.copy(r[o]),l.lookAt(i[o]),t.shadowCamera[o]=l,t.shadowMatrixDeferred[o]=new XG.Matrix4,t.shadowMatrixForward[o]=new XG.Matrix4}t.shadowMapPars=new XG.Vector4(e.shadowMapWidth,e.shadowMapHeight,e.shadowDarkness,e.shadowBias)},XG.SphereLightProxy.prototype.update=function(e){XG.LightProxy.prototype.update.call(this,e);var t=this.light,a=this.materials[0].uniforms,r=t.properties,i=t.distance;if(i>0){var o=XG.LightProxy.positionVS;this.scale.set(1,1,1).multiplyScalar(i),a.lightDistance.value=i,o.copy(t.matrixWorld.getPosition()),e.matrixWorldInverse.multiplyVector3(o),a.lightPositionVS.value.copy(o),this.position.copy(t.matrixWorld.getPosition())}else a.lightDistance.value=1/0;a.lightRadius.value=t.radius;var n=t.intensity*t.intensity;if(a.lightIntensity.value=n,a.lightColor.value.copyGammaToLinear(t.color),t.castShadow){for(var s=0;6>s;s++){var l=r.shadowMatrixDeferred[s],h=r.shadowMatrixForward[s],d=r.shadowCamera[s],c=r.shadowMap[s];l.multiply(d.projectionMatrix,d.matrixWorldInverse),h.multiply(XG.LightProxy.biasMatrix,l),l.multiplySelf(e.matrixWorld),a.matShadow.value[s]=l,a.samplerShadowMap.value[s]=c.useDepthTexture?c.depthTexture:c}a.shadowDarkness.value=Math.sqrt(t.shadowDarkness),a.shadowBias.value=t.shadowBias,a.shadowMapSize.value.set(t.shadowMapWidth,t.shadowMapHeight)}},XG.TubeLightProxy=function(e,t){XG.LightProxy.call(this,e,t);var a=XG.DeferredShaders.tubeLight,r=XG.UniformsUtils.clone(a.uniforms),i=this.generateDefines();e.occlusionEnabled&&(i.OCCLUSION_ENABLED=!0);var o=new XG.ShaderMaterial({uniforms:r,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,defines:i,blending:XG.AdditiveBlending,depthWrite:!1,depthTest:!1,transparent:!0,side:XG.FrontSide}),n=XG.LightProxy.geometryLightPlane;this.setSamplers(o),XG.Mesh.call(this,n,o)},XG.TubeLightProxy.prototype=Object.create(XG.LightProxy.prototype),XG.TubeLightProxy.prototype.update=function(e){XG.LightProxy.prototype.update.call(this,e);var t=this.light,a=this.materials[0].uniforms,r=XG.LightProxy.positionVS;r.copy(t.endPoint0.matrixWorld.getPosition()),e.matrixWorldInverse.multiplyVector3(r),a.lightPosition0VS.value.copy(r),r.copy(t.endPoint1.matrixWorld.getPosition()),e.matrixWorldInverse.multiplyVector3(r),a.lightPosition1VS.value.copy(r),a.lightDistance.value=t.distance,a.lightRadius.value=t.radius;var i=t.intensity*t.intensity;a.lightIntensity.value=i,a.lightColor.value.copyGammaToLinear(t.color)},XG.ImageLightProxy=function(e,t){XG.LightProxy.call(this,e,t);var a=XG.DeferredShaders.imageLight,r=XG.UniformsUtils.clone(a.uniforms),i=this.generateDefines(),o={};e.textureSpecular instanceof XG.RenderTargetCube&&(i.CUBE_SPECULAR_LINEAR=!0),e.textureDiffuse instanceof XG.RenderTargetCube&&(i.CUBE_DIFFUSE_LINEAR=!0),e.local&&(i.LIGHT_LOCAL=!0),t.specularMipFix&&(i.SPECULAR_MIP_FIX=!0,o.OES_standard_derivatives=!0),t.renderer.supportsShaderTextureLod()&&(o.EXT_shader_texture_lod=!0);var n=new XG.ShaderMaterial({uniforms:r,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,defines:i,extensions:o,blending:XG.AdditiveBlending,depthWrite:!1,transparent:!0});this.setSamplers(n);var s;e.local?(s=XG.LightProxy.geometryLightBox,n.depthTest=!0,n.side=XG.BackSide):(s=XG.LightProxy.geometryLightPlane,n.depthTest=!1,n.side=XG.FrontSide),XG.Mesh.call(this,s,n)},XG.ImageLightProxy.prototype=Object.create(XG.LightProxy.prototype),XG.ImageLightProxy.prototype.update=function(e){XG.LightProxy.prototype.update.call(this,e);var t=this.light,a=this.materials[0].uniforms;a.samplerSpecular.value=t.textureSpecular,a.samplerDiffuse.value=t.textureDiffuse,a.samplerMip.value=t.textureMip,a.maxMipSpecular.value=t.textureSpecular.mipmapCount;
  var r=t.intensity*t.intensity;if(a.lightIntensity.value=r,t.local){var i=t.size,o=t.matrixWorld.getPosition();this.position.copy(o),this.scale.copy(i),a.lightSize.value.copy(i).multiplyScalar(.5),a.lightPositionWS.value.copy(o)}},XG.FirstPersonControls=function(e,t){var a=this;this.element=t,this.enabled=!1,this.movementSpeed=1,this.decaySpeed=1,this.lookSpeed=.1,this.amplitude=.1,this.frequency=2;var r=new XG.Node;r.add(e);var i=new XG.Node;i.add(r);var o=new XG.Node;o.add(i);var n=!1,s=!1,l=!1,h=!1,d=new XG.Vector3,c=0,u=Math.PI/2,f=function(e){var t=.001;if(a.enabled!==!1){var r=e.movementX||e.mozMovementX||e.webkitMovementX||0,n=e.movementY||e.mozMovementY||e.webkitMovementY||0;o.rotation.y-=r*a.lookSpeed*t,i.rotation.x-=n*a.lookSpeed*t,i.rotation.x=XG.Math.clamp(i.rotation.x,-u,u)}},p=function(e){switch(e.keyCode){case 38:case 87:n=!0;break;case 37:case 65:l=!0;break;case 40:case 83:s=!0;break;case 39:case 68:h=!0}},m=function(e){switch(e.keyCode){case 38:case 87:n=!1;break;case 37:case 65:l=!1;break;case 40:case 83:s=!1;break;case 39:case 68:h=!1}},v=function(){a.enabled=document.pointerLockElement===a.element||document.mozPointerLockElement===a.element||document.webkitPointerLockElement===a.element?!0:!1};document.addEventListener("mousemove",f,!1),document.addEventListener("keydown",p,!1),document.addEventListener("keyup",m,!1),document.addEventListener("click",function(){var e="pointerLockElement"in document||"mozPointerLockElement"in document||"webkitPointerLockElement"in document;if(!e)return void console.warn("Pointer lock not available");var t=a.element;t.requestPointerLock=t.requestPointerLock||t.mozRequestPointerLock||t.webkitRequestPointerLock;var r=/Firefox/i.test(navigator.userAgent);if(r){var i=function(){(document.fullscreenElement===t||document.mozFullscreenElement===t||document.mozFullScreenElement===t)&&(document.removeEventListener("fullscreenchange",i),document.removeEventListener("mozfullscreenchange",i),t.requestPointerLock())};document.addEventListener("fullscreenchange",i,!1),document.addEventListener("mozfullscreenchange",i,!1),t.requestFullscreen=t.requestFullscreen||t.mozRequestFullscreen||t.mozRequestFullScreen||t.webkitRequestFullscreen,t.requestFullscreen()}else t.requestPointerLock();document.addEventListener("pointerlockchange",v,!1),document.addEventListener("mozpointerlockchange",v,!1),document.addEventListener("webkitpointerlockchange",v,!1)}),this.getRoot=function(){return o},this.attachCamera=function(e){r.add(e)},this.lookAt=function(e){o.updateMatrixWorld(),o.lookAt(e),o.rotation.x=0,o.rotation.z=0,o.rotation.y*=-1},this.update=function(e){if(c+=e,a.enabled!==!1){var t=a.movementSpeed,i=a.decaySpeed;d.x+=-d.x*i*e,d.z+=-d.z*i*e;var u=Math.sqrt(d.x*d.x+d.z*d.z);r.position.y=u*a.amplitude*Math.sin(c*a.frequency),n&&(d.z-=t*e),s&&(d.z+=t*e),l&&(d.x-=t*e),h&&(d.x+=t*e),o.translateX(d.x),o.translateY(d.y),o.translateZ(d.z)}}},XG.Loader=function(e){this.showStatus=e,this.statusDomElement=e?XG.Loader.prototype.addStatusElement():null,this.onLoadStart=function(){},this.onLoadProgress=function(){},this.onLoadComplete=function(){},this.textureMap={}},XG.Loader.prototype={constructor:XG.Loader,crossOrigin:"anonymous",addStatusElement:function(){var e=document.createElement("div");return e.style.position="absolute",e.style.right="0px",e.style.top="0px",e.style.fontSize="0.8em",e.style.textAlign="left",e.style.background="rgba(0,0,0,0.25)",e.style.color="#fff",e.style.width="120px",e.style.padding="0.5em 0.5em 0.5em 0.5em",e.style.zIndex=1e3,e.innerHTML="Loading ...",e},updateProgress:function(e){var t="Loaded ";t+=e.total?(100*e.loaded/e.total).toFixed(0)+"%":(e.loaded/1e3).toFixed(2)+" KB",this.statusDomElement.innerHTML=t},extractUrlBase:function(e){var t=e.split("/");return t.pop(),(t.length<1?".":t.join("/"))+"/"},initMaterials:function(e,t){for(var a=[],r=0;r<e.length;++r)a[r]=this.createMaterial(e[r],t);return a},needsTangents:function(e){for(var t=0,a=e.length;a>t;t++){var r=e[t];if(r instanceof XG.ShaderMaterial)return!0}return!1},createMaterial:function(e,t,a){function r(e){var t=Math.log(e)/Math.LN2;return Math.floor(t)==t}function i(e){var t=Math.log(e)/Math.LN2;return Math.pow(2,Math.round(t))}function o(e,t){var a=new Image;a.onload=function(){if(r(this.width)&&r(this.height))e.image=this;else{var t=i(this.width),a=i(this.height),o=document.createElement("canvas");o.width=t,o.height=a,o.getContext("2d").drawImage(this,0,0,t,a),e.image=o}e.needsUpdate=!0},a.crossOrigin=d.crossOrigin,a.src=t}function n(e,t){return"/"===e[e.length-1]?e+t:e+"/"+t}function s(e,t,a,r,i){var o=e;return t&&(o+="_R["+t[0]+"_"+t[1]+"]"),a&&(o+="_O["+a[0]+"_"+a[1]+"]"),r&&(o+="_W["+r[0]+"_"+r[1]+"]"),i&&(o+="_A["+i+"]"),o}function l(e,r,i,l,h,c,u){var f,p=n(t,i),m=s(p,l,h,c,u);if(void 0===d.textureMap[m]){var v,g=i.toLowerCase().endsWith(".dds"),S=i.toLowerCase().endsWith(".crn");if(g?a?(v=new XG.CompressedTexture,f=v,XG.ImageUtils.generateDummyCompressedTexture(v)):v=XG.ImageUtils.loadCompressedTexture(p):S?a?(v=new XG.CompressedTexture,f=v,XG.ImageUtils.generateDummyCompressedTexture(v)):v=XG.ImageUtils.loadCRNTexture(p):(v=new XG.Texture,o(v,p)),v.sourceFile=i,l&&(v.repeat.set(l[0],l[1]),1!==l[0]&&(v.wrapS=XG.RepeatWrapping),1!==l[1]&&(v.wrapT=XG.RepeatWrapping)),h&&v.offset.set(h[0],h[1]),c){var G={repeat:XG.RepeatWrapping,mirror:XG.MirroredRepeatWrapping};void 0!==G[c[0]]&&(v.wrapS=G[c[0]]),void 0!==G[c[1]]&&(v.wrapT=G[c[1]])}u&&(v.anisotropy=u),d.textureMap[m]=v}return e[r]=d.textureMap[m],f}function h(e){return(255*e[0]<<16)+(255*e[1]<<8)+255*e[2]}var d=this,c="PhongMaterial",u={color:15658734,opacity:1,map:null,lightMap:null,normalMap:null,bumpMap:null};if(e.shading){var f=e.shading.toLowerCase();"phong"===f?c="PhongMaterial":"basic"===f&&(c="EmissiveMaterial")}void 0!==e.blending&&void 0!==XG[e.blending]&&(u.blending=XG[e.blending]),(void 0!==e.transparent||e.transparency<1)&&(u.transparent=e.transparent),void 0!==e.depthTest&&(u.depthTest=e.depthTest),void 0!==e.depthWrite&&(u.depthWrite=e.depthWrite),void 0!==e.visible&&(u.visible=e.visible),void 0!==e.flipSided&&(u.side=XG.BackSide),void 0!==e.doubleSided&&(u.side=XG.DoubleSide),void 0!==e.vertexColors&&(u.vertexColors=e.vertexColors),void 0!==e.skinning&&(u.skinning=e.skinning),void 0!==e.wrapAround&&(u.wrapAround=e.wrapAround),void 0!==e.wrapRGB&&(u.wrapRGB=new XG.Vector3(e.wrapRGB[0],e.wrapRGB[1],e.wrapRGB[2])),e.colorDiffuse?u.color=h(e.colorDiffuse):e.DbgColor&&(u.color=e.DbgColor),e.colorSpecular&&(u.specular=h(e.colorSpecular)),e.colorAmbient&&(u.ambient=h(e.colorAmbient)),e.transparency&&(u.opacity=e.transparency),e.specularCoef&&(u.shininess=e.specularCoef);var p,m=[];e.mapDiffuse&&t&&(p=l(u,"map",e.mapDiffuse,e.mapDiffuseRepeat,e.mapDiffuseOffset,e.mapDiffuseWrap,e.mapDiffuseAnisotropy),p&&m.push([p,e.mapDiffuse])),e.mapLight&&t&&(p=l(u,"lightMap",e.mapLight,e.mapLightRepeat,e.mapLightOffset,e.mapLightWrap,e.mapLightAnisotropy),p&&m.push([p,e.mapLight])),e.mapBump&&t&&(p=l(u,"bumpMap",e.mapBump,e.mapBumpRepeat,e.mapBumpOffset,e.mapBumpWrap,e.mapBumpAnisotropy),p&&m.push([p,e.mapBump])),e.mapNormal&&t&&(p=l(u,"normalMap",e.mapNormal,e.mapNormalRepeat,e.mapNormalOffset,e.mapNormalWrap,e.mapNormalAnisotropy),p&&m.push([p,e.mapNormal])),e.mapSpecular&&t&&(p=l(u,"specularMap",e.mapSpecular,e.mapSpecularRepeat,e.mapSpecularOffset,e.mapSpecularWrap,e.mapSpecularAnisotropy),p&&m.push([p,e.mapSpecular])),e.mapGloss&&t&&(p=l(u,"glossMap",e.mapGloss,e.mapGlossRepeat,e.mapGlossOffset,e.mapGlossWrap,e.mapGlossAnisotropy),p&&m.push([p,e.mapGloss])),e.mapNormalGloss&&t&&(p=l(u,"normalGlossMap",e.mapNormalGloss,e.mapNormalGlossRepeat,e.mapNormalGlossOffset,e.mapNormalGlossWrap,e.mapNormalGlossAnisotropy),p&&m.push([p,e.mapNormalGloss])),e.mapBumpScale&&(u.bumpScale=e.mapBumpScale),e.mapNormalScale&&(u.normalScale=new XG.Vector2(e.mapNormalScale[0],e.mapNormalScale[1]));var v=new XG[c](u);return void 0!==e.DbgName&&(v.name=e.DbgName),v.properties={texturesToLoad:m},v}},XG.UTF8Loader=function(){},XG.UTF8Loader.prototype.load=function(e,t,a){this.downloadModelJson(e,a,t)},XG.UTF8Loader.MaterialCreator=function(e,t){this.materials={},this.textureMap={};for(var a in t)this.createMaterial(a,t[a],e)},XG.UTF8Loader.MaterialCreator.prototype.get=function(e){return this.materials[e]},XG.UTF8Loader.MaterialCreator.prototype.createMaterial=function(e,t,a){var r=this,i=function(e){var t=a+e;if(void 0===r.textureMap[t]){var i,o=e.toLowerCase().endsWith(".dds"),n=e.toLowerCase().endsWith(".crn");i=o?XG.ImageUtils.loadCompressedTexture(t):n?XG.ImageUtils.loadCRNTexture(t):XG.ImageUtils.loadTexture(t),r.textureMap[t]=i}return r.textureMap[t]},o={};for(var n in t){var s=t[n];switch(n.toLowerCase()){case"kd":o.color=(new XG.Color).setRGB(s[0]/255,s[1]/255,s[2]/255);break;case"ka":o.ambient=(new XG.Color).setRGB(s[0]/255,s[1]/255,s[2]/255);break;case"ks":o.specular=(new XG.Color).setRGB(s[0]/255,s[1]/255,s[2]/255);break;case"map_kd":o.map=i(s);break;case"map_ks":o.specularMap=i(s);break;case"map_light":o.lightMap=i(s);break;case"map_normal":o.normalMap=i(s);break;case"map_bump":o.bumpMap=i(s);break;case"map_gloss":o.glossMap=i(s);break;case"ns":o.shininess=s;break;case"side":var l=s.toLowerCase();o.side="double"===l?XG.DoubleSide:"back"===l?XG.BackSide:XG.FrontSide;break;case"alphatest":o.alphaTest=s;break;case"d":1>s&&(o.opacity=s,o.transparent=!0)}}!o.ambient&&o.color&&(o.ambient=o.color);var h=new XG.PhongMaterial(o);h.name=e,this.materials[e]=h},XG.UTF8Loader.GeometryCreator=function(){},XG.UTF8Loader.GeometryCreator.prototype.create=function(e,t){var a,r,i,o,n,s,l,h,d=new XG.Geometry,c=e.length/8,u=new Float32Array(3*c),f=new Float32Array(3*c),p=new Float32Array(2*c),m=e.length,v=8;for(r=0,i=0,a=i;m>a;a+=v)o=e[a],n=e[a+1],s=e[a+2],u[r++]=o,u[r++]=n,u[r++]=s;for(r=0,i=3,a=i;m>a;a+=v)l=e[a],h=e[a+1],p[r++]=l,p[r++]=h;for(r=0,i=5,a=i;m>a;a+=v)o=e[a],n=e[a+1],s=e[a+2],f[r++]=o,f[r++]=n,f[r++]=s;return d.addAttributeArray("index",t,1),d.addAttributeArray("position",u,3),d.addAttributeArray("normal",f,3),d.addAttributeArray("uv",p,2),d.offsets=[{start:0,count:t.length,index:0}],d.computeBoundingSphere(),d};var DEFAULT_DECODE_PARAMS={decodeOffsets:[-4095,-4095,-4095,0,0,-511,-511,-511],decodeScales:[1/8191,1/8191,1/8191,1/1023,1/1023,1/1023,1/1023,1/1023]};XG.UTF8Loader.prototype.decompressAttribsInner_=function(e,t,a,r,i,o,n,s){for(var l=0,h=t;a>h;h++){var d=e.charCodeAt(h);l+=d>>1^-(1&d),r[i]=s*(l+n),i+=o}},XG.UTF8Loader.prototype.decompressIndices_=function(e,t,a,r,i){for(var o=0,n=0;a>n;n++){var s=e.charCodeAt(t++);r[i++]=o-s,0===s&&o++}},XG.UTF8Loader.prototype.decompressAABBs_=function(e,t,a,r,i){for(var o=6*a,n=t+o,s=0,l=new Float32Array(o),h=t;n>h;h+=6){var d=e.charCodeAt(h+0)+r[0],c=e.charCodeAt(h+1)+r[1],u=e.charCodeAt(h+2)+r[2],f=e.charCodeAt(h+3)+1>>1,p=e.charCodeAt(h+4)+1>>1,m=e.charCodeAt(h+5)+1>>1;l[s++]=i[0]*(d+f),l[s++]=i[1]*(c+p),l[s++]=i[2]*(u+m),l[s++]=i[0]*f,l[s++]=i[1]*p,l[s++]=i[2]*m}return l},XG.UTF8Loader.prototype.decompressMesh=function(e,t,a,r,i,o){for(var n=a.decodeScales.length,s=a.decodeOffsets,l=a.decodeScales,h=t.attribRange[0],d=t.attribRange[1],c=h,u=new Float32Array(n*d),f=0;n>f;f++){var p=c+d,m=l[f];m&&this.decompressAttribsInner_(e,c,p,u,f,n,s[f],m),c=p}var v=3*t.indexRange[1],g=new Uint16Array(v);this.decompressIndices_(e,c,v,g,0);var S=void 0,G=t.bboxes;G&&(S=this.decompressAABBs_(e,G,t.names.length,s,l)),o(r,i,u,g,S,t)},XG.UTF8Loader.prototype.copyAttrib=function(e,t,a,r){for(var i=0;e>i;i++)a[i]=t[e*r+i]},XG.UTF8Loader.prototype.decodeAttrib2=function(e,t,a,r,i,o,n,s,l,h){for(var d=0;5>d;d++){var c=e.charCodeAt(i+o*d+h),u=c>>1^-(1&c);l[d]+=u,s[t*h+d]=l[d],n[t*h+d]=r[d]*(l[d]+a[d])}},XG.UTF8Loader.prototype.accumulateNormal=function(e,t,a,r,i){var o=r[8*e],n=r[8*e+1],s=r[8*e+2],l=r[8*t],h=r[8*t+1],d=r[8*t+2],c=r[8*a],u=r[8*a+1],f=r[8*a+2];l-=o,h-=n,d-=s,c-=o,u-=n,f-=s,o=h*f-d*u,n=d*c-l*f,s=l*u-h*c,i[3*e]+=o,i[3*e+1]+=n,i[3*e+2]+=s,i[3*t]+=o,i[3*t+1]+=n,i[3*t+2]+=s,i[3*a]+=o,i[3*a+1]+=n,i[3*a+2]+=s},XG.UTF8Loader.prototype.decompressMesh2=function(e,t,a,r,i,o){for(var n=96,s=a.decodeScales.length,l=a.decodeOffsets,h=a.decodeScales,d=t.attribRange[0],c=t.attribRange[1],u=t.codeRange[0],f=(t.codeRange[1],3*t.codeRange[2]),p=new Uint16Array(f),m=new Int32Array(3*c),v=new Uint16Array(s),g=new Uint16Array(s*c),S=new Float32Array(s*c),G=0,x=0,M=0;f>M;M+=3){var y=e.charCodeAt(u++),X=Math.min(M,n);if(X>y){var D,_,w,A=y%3,C=M-(y-A);switch(A){case 0:D=p[C+2],_=p[C+1],w=p[C+0];break;case 1:D=p[C+0],_=p[C+2],w=p[C+1];break;case 2:D=p[C+1],_=p[C+0],w=p[C+2]}p[x++]=D,p[x++]=_,y=e.charCodeAt(u++);var T=G-y;if(p[x++]=T,0===y){for(var b=0;5>b;b++){var P=e.charCodeAt(d+c*b+G),L=(P>>1^-(1&P))+g[s*D+b]+g[s*_+b]-g[s*w+b];v[b]=L,g[s*G+b]=L,S[s*G+b]=h[b]*(L+l[b])}G++}else this.copyAttrib(s,g,v,T);this.accumulateNormal(D,_,T,g,m)}else{var E=G-(y-X);p[x++]=E,y===X?this.decodeAttrib2(e,s,l,h,d,c,S,g,v,G++):this.copyAttrib(s,g,v,E),y=e.charCodeAt(u++);var F=G-y;p[x++]=F,0===y?this.decodeAttrib2(e,s,l,h,d,c,S,g,v,G++):this.copyAttrib(s,g,v,F),y=e.charCodeAt(u++);var R=G-y;if(p[x++]=R,0===y){for(var b=0;5>b;b++)v[b]=(g[s*E+b]+g[s*F+b])/2;this.decodeAttrib2(e,s,l,h,d,c,S,g,v,G++)}else this.copyAttrib(s,g,v,R);this.accumulateNormal(E,F,R,g,m)}}for(var M=0;c>M;M++){var U=m[3*M],N=m[3*M+1],I=m[3*M+2],B=511/Math.sqrt(U*U+N*N+I*I),O=e.charCodeAt(d+5*c+M),k=e.charCodeAt(d+6*c+M),V=e.charCodeAt(d+7*c+M);S[s*M+5]=B*U+(O>>1^-(1&O)),S[s*M+6]=B*N+(k>>1^-(1&k)),S[s*M+7]=B*I+(V>>1^-(1&V))}o(r,i,S,p,void 0,t)},XG.UTF8Loader.prototype.downloadMesh=function(e,t,a,r,i){function o(e){for(;s<a.length;){var o=a[s],l=o.indexRange;if(l){var h=l[0]+3*l[1];if(e.responseText.length<h)break;n.decompressMesh(e.responseText,o,r,t,s,i)}else{var d=o.codeRange,h=d[0]+d[1];if(e.responseText.length<h)break;n.decompressMesh2(e.responseText,o,r,t,s,i)}++s}}var n=this,s=0;getHttpRequest(e,function(e,t){(200===e.status||0===e.status)&&o(e,t)},o)},XG.UTF8Loader.prototype.downloadMeshes=function(e,t,a,r){for(var i in t){var o=t[i];this.downloadMesh(e+i,i,o,a,r)}},XG.UTF8Loader.prototype.createMeshCallback=function(e,t,a){var r=0,i=0,o={},n={},s=t.urls;for(var l in s)o[l]=s[l].length,n[l]=0,i++;var h=[],d=[],c=new XG.PhongMaterial,u=new XG.UTF8Loader.MaterialCreator(e,t.materials,this),f=new XG.UTF8Loader.GeometryCreator,p=function(e,t,s,l,p,m){var v=f.create(s,l),g=u.get(m.material);g||(g=c),h.push(v),d.push(g),n[e]++,n[e]===o[e]&&(r++,r===i&&a(h,d))};return p},XG.UTF8Loader.prototype.downloadModel=function(e,t,a,r){var i=this.createMeshCallback(t,a,r);this.downloadMeshes(e,a.urls,a.decodeParams,i)},XG.UTF8Loader.prototype.downloadModelJson=function(e,t,a){getJsonRequest(e,function(r){r.decodeParams||(r.decodeParams=t&&t.decodeParams?t.decodeParams:DEFAULT_DECODE_PARAMS),r.options=t;var i=e.substr(0,e.lastIndexOf("/")+1),o=i;t&&t.geometryBase&&(i=t.geometryBase,"/"!==i.charAt(i.length-1)&&(i+="/")),t&&t.materialBase&&(o=t.materialBase,"/"!==o.charAt(o.length-1)&&(o+="/")),this.downloadModel(i,o,r,a)}.bind(this))},XG.CTMLoader=function(e){XG.Loader.call(this,e),this.maxWorkerCount=4,this.workerPool=[],this.workerState=[],this.workerFreeCallbacks=[],window.URL=window.URL||window.webkitURL;for(var t=new Blob([XG.CTMLoader.workerString],{type:"application/x-javascript"}),a=window.URL.createObjectURL(t),r=0;r<this.maxWorkerCount;r++){var i=new Worker(a);i.index=r,this.workerPool[r]=i,this.workerState[r]=0}},XG.CTMLoader.prototype=Object.create(XG.Loader.prototype),XG.CTMLoader.prototype.loadParts=function(e,t,a){var r=this,i=void 0!==a&&a.basePath?a.basePath:this.extractUrlBase(e),o=void 0!==a&&void 0!==a.useCrunchWorker?a.useCrunchWorker:!0,n=void 0!==a?a.callbackGeometriesLoaded:null,s=void 0!==a?a.callbackProgress:null,l=function(e,t,a,r){for(var i={},n=0,s=t.length;s>n;n++){var l=t[n],h=l[0],d=l[1],c=l[2];i[h]=[d,c]}for(var u=[],n=0,s=a.length;s>n;n++){var f=a[n];if(f.properties.texturesToLoad)for(var p=0,m=f.properties.texturesToLoad.length;m>p;p++){var v=f.properties.texturesToLoad[p],g=v[0],S=v[1],l=i[S];if(l){var G=S.toLowerCase().endsWith(".crn");if(G){var d=l[0],c=l[1];o?u.push([g,d,c]):XG.ImageUtils.loadCRNTextureFromPack(g,e,d,c)}else{var d=l[0];XG.ImageUtils.loadCompressedTextureFromPack(g,e,d)}}}}if(o&&u.length>0){var x=function(){r()};XG.ImageUtils.loadMultipleCRNTexturesFromPack(u,e,x)}else r()},h=function(e,t,a,r,i){var o=new XMLHttpRequest;o.onreadystatechange=function(){if(4===o.readyState&&(200===o.status||0===o.status)){var e=o.response;l(e,t,a,r)}},i&&(o.onprogress=function(t){var a={url:e,loaded:t.loaded,total:t.total};i(a)}),o.open("GET",e,!0),o.responseType="arraybuffer",o.send(null)},d=function(e){function a(){u&&f&&t(c,d)}function o(t){p+=1,c.push(t),p===e.offsets.length&&(u=!0,n&&n(c,d),a())}function l(){m+=1,m===e.textures.length&&(f=!0,a())}for(var d=[],c=[],u=!1,f=!1,p=0,m=0,v=e.textures&&e.textureOffsets,g=0;g<e.materials.length;g++)d[g]=r.createMaterial(e.materials[g],i,v);var S=i+e.data,G={offsets:e.offsets,callbackProgress:s};if(r.load(S,o,G),v)for(var g=0,x=e.textures.length;x>g;g++){var M=i+e.textures[g],y=e.textureOffsets[g];h(M,y,d,l,s)}else f=!0},c=new XMLHttpRequest;c.onreadystatechange=function(){if(4===c.readyState&&(200===c.status||0===c.status)){var e=JSON.parse(c.responseText);d(e)}},c.open("GET",e,!0),c.overrideMimeType&&c.overrideMimeType("text/plain; charset=x-user-defined"),c.setRequestHeader("Content-Type","text/plain"),c.send(null)},XG.CTMLoader.prototype.getWorker=function(e){for(var t,a=0,r=this.workerPool.length;r>a;a++){var i=this.workerState[a];if(0===i){t=this.workerPool[a],this.workerState[a]=1;break}}void 0===t?this.workerFreeCallbacks.push(e):e(t)},XG.CTMLoader.prototype.releaseWorker=function(e){var t=this.workerFreeCallbacks.shift();t?t(e):this.workerState[e.index]=0},XG.CTMLoader.prototype.load=function(e,t,a){var r=this,i=void 0!==a&&void 0!==a.offsets?a.offsets:[0],o=void 0!==a&&void 0!==a.callbackProgress?a.callbackProgress:null,n=new XMLHttpRequest;n.onreadystatechange=function(){if(4===n.readyState)if(200===n.status||0===n.status){var a=n.response,o=function(e){e.onmessage=function(a){for(var i=a.data.f,o=0;o<i.length;o++){var n=i[o];r.createModelBuffers(n,t)}Date.now();r.releaseWorker(e)};Date.now();e.postMessage=e.webkitPostMessage||e.postMessage,e.postMessage({data:a,offsets:i},[a])};r.getWorker(o)}else console.error("XG.CTMLoader: Couldn't load ["+e+"] ["+n.status+"]")},o&&(n.onprogress=function(t){var a={url:e,loaded:t.loaded,total:t.total};o(a)}),n.open("GET",e,!0),n.responseType="arraybuffer",n.send(null)},XG.CTMLoader.prototype.createModelBuffers=function(e,t){var a=function(){var t=this,a=!0;XG.Geometry.call(this);var r,i,o=e.body.indices,n=e.body.vertices,s=e.body.normals;if(void 0!==e.body.uvMaps&&e.body.uvMaps.length>0&&(r=e.body.uvMaps[0].uv),void 0!==e.body.attrMaps&&e.body.attrMaps.length>0&&"Color"===e.body.attrMaps[0].name&&(i=e.body.attrMaps[0].attr),a){var l,h,d,c=new Uint32Array(o.length),u=new Float32Array(n.length);s&&(l=new Float32Array(s.length)),r&&(h=new Float32Array(r.length)),i&&(d=new Float32Array(i.length));for(var f,p,m,v={},g=0,S=function(e){if(void 0===v[e]){v[e]=g;var t=3*e,a=3*e+1,o=3*e+2,c=3*g,f=3*g+1,p=3*g+2;u[c]=n[t],u[f]=n[a],u[p]=n[o],s&&(l[c]=s[t],l[f]=s[a],l[p]=s[o]),r&&(h[2*g]=r[2*e],h[2*g+1]=r[2*e+1]),i&&(d[4*g]=i[4*e],d[4*g+1]=i[4*e+1],d[4*g+2]=i[4*e+2],d[4*g+3]=i[4*e+3]),g+=1}},G=0;G<o.length;G+=3)f=o[G],p=o[G+1],m=o[G+2],S(f),S(p),S(m),c[G]=v[f],c[G+1]=v[p],c[G+2]=v[m];o=c,n=u,s&&(s=l),r&&(r=h),i&&(i=d)}t.offsets=[];for(var x=o,M=0,y=n.length,X=0,D=y,G=0;G<x.length;){for(var _=0;3>_;++_){var w=x[G++];y>w&&(y=w),w>X&&(X=w)}if(X-y>65534){G-=3;for(var A=M;G>A;++A)x[A]-=D;t.offsets.push({start:M,count:G-M,index:D}),M=G,y=n.length,X=0}D=y}for(var A=M;G>A;++A)x[A]-=D;t.offsets.push({start:M,count:G-M,index:D});var C=new Uint16Array(o);t.addAttributeArray("index",C,1),t.addAttributeArray("position",n,3),void 0!==s&&t.addAttributeArray("normal",s,3),void 0!==r&&t.addAttributeArray("uv",r,2),void 0!==i&&t.addAttributeArray("color",i,4)};a.prototype=Object.create(XG.Geometry.prototype);var r=new a;void 0===r.attributes.normal&&r.computeVertexNormals(),t(r)},XG.CTMLoader.workerString=["var LZMA = LZMA || {};","","LZMA.OutWindow = function(){","  this._windowSize = 0;","};","","LZMA.OutWindow.prototype.create = function(windowSize){","  if ( (!this._buffer) || (this._windowSize !== windowSize) ){","    this._buffer = [];","  }","  this._windowSize = windowSize;","  this._pos = 0;","  this._streamPos = 0;","};","","LZMA.OutWindow.prototype.flush = function(){","  var size = this._pos - this._streamPos;","  if (size !== 0){","    while(size --){","      this._stream.writeByte(this._buffer[this._streamPos ++]);","    }","    if (this._pos >= this._windowSize){","      this._pos = 0;","    }","    this._streamPos = this._pos;","  }","};","","LZMA.OutWindow.prototype.releaseStream = function(){","  this.flush();","  this._stream = null;","};","","LZMA.OutWindow.prototype.setStream = function(stream){","  this.releaseStream();","  this._stream = stream;","};","","LZMA.OutWindow.prototype.init = function(solid){","  if (!solid){","    this._streamPos = 0;","    this._pos = 0;","  }","};","","LZMA.OutWindow.prototype.copyBlock = function(distance, len){","  var pos = this._pos - distance - 1;","  if (pos < 0){","    pos += this._windowSize;","  }","  while(len --){","    if (pos >= this._windowSize){","      pos = 0;","    }","    this._buffer[this._pos ++] = this._buffer[pos ++];","    if (this._pos >= this._windowSize){","      this.flush();","    }","  }","};","","LZMA.OutWindow.prototype.putByte = function(b){","  this._buffer[this._pos ++] = b;","  if (this._pos >= this._windowSize){","    this.flush();","  }","};","","LZMA.OutWindow.prototype.getByte = function(distance){","  var pos = this._pos - distance - 1;","  if (pos < 0){","    pos += this._windowSize;","  }","  return this._buffer[pos];","};","","LZMA.RangeDecoder = function(){","};","","LZMA.RangeDecoder.prototype.setStream = function(stream){","  this._stream = stream;","};","","LZMA.RangeDecoder.prototype.releaseStream = function(){","  this._stream = null;","};","","LZMA.RangeDecoder.prototype.init = function(){","  var i = 5;","","  this._code = 0;","  this._range = -1;","","  while(i --){","    this._code = (this._code << 8) | this._stream.readByte();","  }","};","","LZMA.RangeDecoder.prototype.decodeDirectBits = function(numTotalBits){","  var result = 0, i = numTotalBits, t;","","  while(i --){","    this._range >>>= 1;","    t = (this._code - this._range) >>> 31;","    this._code -= this._range & (t - 1);","    result = (result << 1) | (1 - t);","","    if ( (this._range & 0xff000000) === 0){","      this._code = (this._code << 8) | this._stream.readByte();","      this._range <<= 8;","    }","  }","","  return result;","};","","LZMA.RangeDecoder.prototype.decodeBit = function(probs, index){","  var prob = probs[index],","      newBound = (this._range >>> 11) * prob;","","  if ( (this._code ^ 0x80000000) < (newBound ^ 0x80000000) ){","    this._range = newBound;","    probs[index] += (2048 - prob) >>> 5;","    if ( (this._range & 0xff000000) === 0){","      this._code = (this._code << 8) | this._stream.readByte();","      this._range <<= 8;","    }","    return 0;","  }","","  this._range -= newBound;","  this._code -= newBound;","  probs[index] -= prob >>> 5;","  if ( (this._range & 0xff000000) === 0){","    this._code = (this._code << 8) | this._stream.readByte();","    this._range <<= 8;","  }","  return 1;","};","","LZMA.initBitModels = function(probs, len){","  while(len --){","    probs[len] = 1024;","  }","};","","LZMA.BitTreeDecoder = function(numBitLevels){","  this._models = [];","  this._numBitLevels = numBitLevels;","};","","LZMA.BitTreeDecoder.prototype.init = function(){","  LZMA.initBitModels(this._models, 1 << this._numBitLevels);","};","","LZMA.BitTreeDecoder.prototype.decode = function(rangeDecoder){","  var m = 1, i = this._numBitLevels;","","  while(i --){","    m = (m << 1) | rangeDecoder.decodeBit(this._models, m);","  }","  return m - (1 << this._numBitLevels);","};","","LZMA.BitTreeDecoder.prototype.reverseDecode = function(rangeDecoder){","  var m = 1, symbol = 0, i = 0, bit;","","  for (; i < this._numBitLevels; ++ i){","    bit = rangeDecoder.decodeBit(this._models, m);","    m = (m << 1) | bit;","    symbol |= bit << i;","  }","  return symbol;","};","","LZMA.reverseDecode2 = function(models, startIndex, rangeDecoder, numBitLevels){","  var m = 1, symbol = 0, i = 0, bit;","","  for (; i < numBitLevels; ++ i){","    bit = rangeDecoder.decodeBit(models, startIndex + m);","    m = (m << 1) | bit;","    symbol |= bit << i;","  }","  return symbol;","};","","LZMA.LenDecoder = function(){","  this._choice = [];","  this._lowCoder = [];","  this._midCoder = [];","  this._highCoder = new LZMA.BitTreeDecoder(8);","  this._numPosStates = 0;","};","","LZMA.LenDecoder.prototype.create = function(numPosStates){","  for (; this._numPosStates < numPosStates; ++ this._numPosStates){","    this._lowCoder[this._numPosStates] = new LZMA.BitTreeDecoder(3);","    this._midCoder[this._numPosStates] = new LZMA.BitTreeDecoder(3);","  }","};","","LZMA.LenDecoder.prototype.init = function(){","  var i = this._numPosStates;","  LZMA.initBitModels(this._choice, 2);","  while(i --){","    this._lowCoder[i].init();","    this._midCoder[i].init();","  }","  this._highCoder.init();","};","","LZMA.LenDecoder.prototype.decode = function(rangeDecoder, posState){","  if (rangeDecoder.decodeBit(this._choice, 0) === 0){","    return this._lowCoder[posState].decode(rangeDecoder);","  }","  if (rangeDecoder.decodeBit(this._choice, 1) === 0){","    return 8 + this._midCoder[posState].decode(rangeDecoder);","  }","  return 16 + this._highCoder.decode(rangeDecoder);","};","","LZMA.Decoder2 = function(){","  this._decoders = [];","};","","LZMA.Decoder2.prototype.init = function(){","  LZMA.initBitModels(this._decoders, 0x300);","};","","LZMA.Decoder2.prototype.decodeNormal = function(rangeDecoder){","  var symbol = 1;","","  do{","    symbol = (symbol << 1) | rangeDecoder.decodeBit(this._decoders, symbol);","  }while(symbol < 0x100);","","  return symbol & 0xff;","};","","LZMA.Decoder2.prototype.decodeWithMatchByte = function(rangeDecoder, matchByte){","  var symbol = 1, matchBit, bit;","","  do{","    matchBit = (matchByte >> 7) & 1;","    matchByte <<= 1;","    bit = rangeDecoder.decodeBit(this._decoders, ( (1 + matchBit) << 8) + symbol);","    symbol = (symbol << 1) | bit;","    if (matchBit !== bit){","      while(symbol < 0x100){","        symbol = (symbol << 1) | rangeDecoder.decodeBit(this._decoders, symbol);","      }","      break;","    }","  }while(symbol < 0x100);","","  return symbol & 0xff;","};","","LZMA.LiteralDecoder = function(){","};","","LZMA.LiteralDecoder.prototype.create = function(numPosBits, numPrevBits){","  var i;","","  if (this._coders","    && (this._numPrevBits === numPrevBits)","    && (this._numPosBits === numPosBits) ){","    return;","  }","  this._numPosBits = numPosBits;","  this._posMask = (1 << numPosBits) - 1;","  this._numPrevBits = numPrevBits;","","  this._coders = [];","","  i = 1 << (this._numPrevBits + this._numPosBits);","  while(i --){","    this._coders[i] = new LZMA.Decoder2();","  }","};","","LZMA.LiteralDecoder.prototype.init = function(){","  var i = 1 << (this._numPrevBits + this._numPosBits);","  while(i --){","    this._coders[i].init();","  }","};","","LZMA.LiteralDecoder.prototype.getDecoder = function(pos, prevByte){","  return this._coders[( (pos & this._posMask) << this._numPrevBits)","    + ( (prevByte & 0xff) >>> (8 - this._numPrevBits) )];","};","","LZMA.Decoder = function(){","  this._outWindow = new LZMA.OutWindow();","  this._rangeDecoder = new LZMA.RangeDecoder();","  this._isMatchDecoders = [];","  this._isRepDecoders = [];","  this._isRepG0Decoders = [];","  this._isRepG1Decoders = [];","  this._isRepG2Decoders = [];","  this._isRep0LongDecoders = [];","  this._posSlotDecoder = [];","  this._posDecoders = [];","  this._posAlignDecoder = new LZMA.BitTreeDecoder(4);","  this._lenDecoder = new LZMA.LenDecoder();","  this._repLenDecoder = new LZMA.LenDecoder();","  this._literalDecoder = new LZMA.LiteralDecoder();","  this._dictionarySize = -1;","  this._dictionarySizeCheck = -1;","","  this._posSlotDecoder[0] = new LZMA.BitTreeDecoder(6);","  this._posSlotDecoder[1] = new LZMA.BitTreeDecoder(6);","  this._posSlotDecoder[2] = new LZMA.BitTreeDecoder(6);","  this._posSlotDecoder[3] = new LZMA.BitTreeDecoder(6);","};","","LZMA.Decoder.prototype.setDictionarySize = function(dictionarySize){","  if (dictionarySize < 0){","    return false;","  }","  if (this._dictionarySize !== dictionarySize){","    this._dictionarySize = dictionarySize;","    this._dictionarySizeCheck = Math.max(this._dictionarySize, 1);","    this._outWindow.create( Math.max(this._dictionarySizeCheck, 4096) );","  }","  return true;","};","","LZMA.Decoder.prototype.setLcLpPb = function(lc, lp, pb){","  var numPosStates = 1 << pb;","","  if (lc > 8 || lp > 4 || pb > 4){","    return false;","  }","","  this._literalDecoder.create(lp, lc);","","  this._lenDecoder.create(numPosStates);","  this._repLenDecoder.create(numPosStates);","  this._posStateMask = numPosStates - 1;","","  return true;","};","","LZMA.Decoder.prototype.init = function(){","  var i = 4;","","  this._outWindow.init(false);","","  LZMA.initBitModels(this._isMatchDecoders, 192);","  LZMA.initBitModels(this._isRep0LongDecoders, 192);","  LZMA.initBitModels(this._isRepDecoders, 12);","  LZMA.initBitModels(this._isRepG0Decoders, 12);","  LZMA.initBitModels(this._isRepG1Decoders, 12);","  LZMA.initBitModels(this._isRepG2Decoders, 12);","  LZMA.initBitModels(this._posDecoders, 114);","","  this._literalDecoder.init();","","  while(i --){","    this._posSlotDecoder[i].init();","  }","","  this._lenDecoder.init();","  this._repLenDecoder.init();","  this._posAlignDecoder.init();","  this._rangeDecoder.init();","};","","LZMA.Decoder.prototype.decode = function(inStream, outStream, outSize){","  var state = 0, rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0, nowPos64 = 0, prevByte = 0,","      posState, decoder2, len, distance, posSlot, numDirectBits;","","  this._rangeDecoder.setStream(inStream);","  this._outWindow.setStream(outStream);","","  this.init();","","  while(outSize < 0 || nowPos64 < outSize){","    posState = nowPos64 & this._posStateMask;","","    if (this._rangeDecoder.decodeBit(this._isMatchDecoders, (state << 4) + posState) === 0){","      decoder2 = this._literalDecoder.getDecoder(nowPos64 ++, prevByte);","","      if (state >= 7){","        prevByte = decoder2.decodeWithMatchByte(this._rangeDecoder, this._outWindow.getByte(rep0) );","      }else{","        prevByte = decoder2.decodeNormal(this._rangeDecoder);","      }","      this._outWindow.putByte(prevByte);","","      state = state < 4? 0: state - (state < 10? 3: 6);","","    }else{","","      if (this._rangeDecoder.decodeBit(this._isRepDecoders, state) === 1){","        len = 0;","        if (this._rangeDecoder.decodeBit(this._isRepG0Decoders, state) === 0){","          if (this._rangeDecoder.decodeBit(this._isRep0LongDecoders, (state << 4) + posState) === 0){","            state = state < 7? 9: 11;","            len = 1;","          }","        }else{","          if (this._rangeDecoder.decodeBit(this._isRepG1Decoders, state) === 0){","            distance = rep1;","          }else{","            if (this._rangeDecoder.decodeBit(this._isRepG2Decoders, state) === 0){","              distance = rep2;","            }else{","              distance = rep3;","              rep3 = rep2;","            }","            rep2 = rep1;","          }","          rep1 = rep0;","          rep0 = distance;","        }","        if (len === 0){","          len = 2 + this._repLenDecoder.decode(this._rangeDecoder, posState);","          state = state < 7? 8: 11;","        }","      }else{","        rep3 = rep2;","        rep2 = rep1;","        rep1 = rep0;","","        len = 2 + this._lenDecoder.decode(this._rangeDecoder, posState);","        state = state < 7? 7: 10;","","        posSlot = this._posSlotDecoder[len <= 5? len - 2: 3].decode(this._rangeDecoder);","        if (posSlot >= 4){","","          numDirectBits = (posSlot >> 1) - 1;","          rep0 = (2 | (posSlot & 1) ) << numDirectBits;","","          if (posSlot < 14){","            rep0 += LZMA.reverseDecode2(this._posDecoders,","                rep0 - posSlot - 1, this._rangeDecoder, numDirectBits);","          }else{","            rep0 += this._rangeDecoder.decodeDirectBits(numDirectBits - 4) << 4;","            rep0 += this._posAlignDecoder.reverseDecode(this._rangeDecoder);","            if (rep0 < 0){","              if (rep0 === -1){","                break;","              }","              return false;","            }","          }","        }else{","          rep0 = posSlot;","        }","      }","","      if (rep0 >= nowPos64 || rep0 >= this._dictionarySizeCheck){","        return false;","      }","","      this._outWindow.copyBlock(rep0, len);","      nowPos64 += len;","      prevByte = this._outWindow.getByte(0);","    }","  }","","  this._outWindow.flush();","  this._outWindow.releaseStream();","  this._rangeDecoder.releaseStream();","","  return true;","};","","LZMA.Decoder.prototype.setDecoderProperties = function(properties){","  var value, lc, lp, pb, dictionarySize;","","  if (properties.size < 5){","    return false;","  }","","  value = properties.readByte();","  lc = value % 9;","  value = ~~(value / 9);","  lp = value % 5;","  pb = ~~(value / 5);","","  if ( !this.setLcLpPb(lc, lp, pb) ){","    return false;","  }","","  dictionarySize = properties.readByte();","  dictionarySize |= properties.readByte() << 8;","  dictionarySize |= properties.readByte() << 16;","  dictionarySize += properties.readByte() * 16777216;","","  return this.setDictionarySize(dictionarySize);","};","","LZMA.decompress = function(properties, inStream, outStream, outSize){","  var decoder = new LZMA.Decoder();","","  if ( !decoder.setDecoderProperties(properties) ){",'    throw "Incorrect stream properties";',"  }","","  if ( !decoder.decode(inStream, outStream, outSize) ){",'    throw "Error in data stream";',"  }","","  return true;","};","","LZMA.decompressFile = function(inStream, outStream){","  var decoder = new LZMA.Decoder(), outSize;","","  if ( !decoder.setDecoderProperties(inStream) ){",'    throw "Incorrect stream properties";',"  }","","  outSize = inStream.readByte();","  outSize |= inStream.readByte() << 8;","  outSize |= inStream.readByte() << 16;","  outSize += inStream.readByte() * 16777216;","","  inStream.readByte();","  inStream.readByte();","  inStream.readByte();","  inStream.readByte();","","  if ( !decoder.decode(inStream, outStream, outSize) ){",'    throw "Error in data stream";',"  }","","  return true;","};","","var CTM = CTM || {};","","CTM.CompressionMethod = {","  RAW: 0x00574152,","  MG1: 0x0031474d,","  MG2: 0x0032474d","};","","CTM.Flags = {","  NORMALS: 0x00000001","};","","CTM.File = function(stream){","  this.load(stream);","};","","CTM.File.prototype.load = function(stream){","  this.header = new CTM.FileHeader(stream);","","  this.body = new CTM.FileBody(this.header);","","  this.getReader().read(stream, this.body);","};","","CTM.File.prototype.getReader = function(){","  var reader;","","  switch(this.header.compressionMethod){","    case CTM.CompressionMethod.RAW:","      reader = new CTM.ReaderRAW();","      break;","    case CTM.CompressionMethod.MG1:","      reader = new CTM.ReaderMG1();","      break;","    case CTM.CompressionMethod.MG2:","      reader = new CTM.ReaderMG2();","      break;","  }","","  return reader;","};","","CTM.FileHeader = function(stream){",'  stream.readInt32(); //magic "OCTM"',"  this.fileFormat = stream.readInt32();","  this.compressionMethod = stream.readInt32();","  this.vertexCount = stream.readInt32();","  this.triangleCount = stream.readInt32();","  this.uvMapCount = stream.readInt32();","  this.attrMapCount = stream.readInt32();","  this.flags = stream.readInt32();","  this.comment = stream.readString();","};","","CTM.FileHeader.prototype.hasNormals = function(){","  return this.flags & CTM.Flags.NORMALS;","};","","CTM.FileBody = function(header){","  var i = header.triangleCount * 3,","      v = header.vertexCount * 3,","      n = header.hasNormals()? header.vertexCount * 3: 0,","      u = header.vertexCount * 2,","      a = header.vertexCount * 4,","      j = 0;","","  var data = new ArrayBuffer(","    (i + v + n + (u * header.uvMapCount) + (a * header.attrMapCount) ) * 4);","","  this.indices = new Uint32Array(data, 0, i);","","  this.vertices = new Float32Array(data, i * 4, v);","","  if ( header.hasNormals() ){","    this.normals = new Float32Array(data, (i + v) * 4, n);","  }","","  if (header.uvMapCount){","    this.uvMaps = [];","    for (j = 0; j < header.uvMapCount; ++ j){","      this.uvMaps[j] = {uv: new Float32Array(data,","        (i + v + n + (j * u) ) * 4, u) };","    }","  }","","  if (header.attrMapCount){","    this.attrMaps = [];","    for (j = 0; j < header.attrMapCount; ++ j){","      this.attrMaps[j] = {attr: new Float32Array(data,","        (i + v + n + (u * header.uvMapCount) + (j * a) ) * 4, a) };","    }","  }","};","","CTM.FileMG2Header = function(stream){",'  stream.readInt32(); //magic "MG2H"',"  this.vertexPrecision = stream.readFloat32();","  this.normalPrecision = stream.readFloat32();","  this.lowerBoundx = stream.readFloat32();","  this.lowerBoundy = stream.readFloat32();","  this.lowerBoundz = stream.readFloat32();","  this.higherBoundx = stream.readFloat32();","  this.higherBoundy = stream.readFloat32();","  this.higherBoundz = stream.readFloat32();","  this.divx = stream.readInt32();","  this.divy = stream.readInt32();","  this.divz = stream.readInt32();","","  this.sizex = (this.higherBoundx - this.lowerBoundx) / this.divx;","  this.sizey = (this.higherBoundy - this.lowerBoundy) / this.divy;","  this.sizez = (this.higherBoundz - this.lowerBoundz) / this.divz;","};","","CTM.ReaderRAW = function(){","};","","CTM.ReaderRAW.prototype.read = function(stream, body){","  this.readIndices(stream, body.indices);","  this.readVertices(stream, body.vertices);","","  if (body.normals){","    this.readNormals(stream, body.normals);","  }","  if (body.uvMaps){","    this.readUVMaps(stream, body.uvMaps);","  }","  if (body.attrMaps){","    this.readAttrMaps(stream, body.attrMaps);","  }","};","","CTM.ReaderRAW.prototype.readIndices = function(stream, indices){",'  stream.readInt32(); //magic "INDX"',"  stream.readArrayInt32(indices);","};","","CTM.ReaderRAW.prototype.readVertices = function(stream, vertices){",'  stream.readInt32(); //magic "VERT"',"  stream.readArrayFloat32(vertices);","};","","CTM.ReaderRAW.prototype.readNormals = function(stream, normals){",'  stream.readInt32(); //magic "NORM"',"  stream.readArrayFloat32(normals);","};","","CTM.ReaderRAW.prototype.readUVMaps = function(stream, uvMaps){","  var i = 0;","  for (; i < uvMaps.length; ++ i){",'    stream.readInt32(); //magic "TEXC"',"","    uvMaps[i].name = stream.readString();","    uvMaps[i].filename = stream.readString();","    stream.readArrayFloat32(uvMaps[i].uv);","  }","};","","CTM.ReaderRAW.prototype.readAttrMaps = function(stream, attrMaps){","  var i = 0;","  for (; i < attrMaps.length; ++ i){",'    stream.readInt32(); //magic "ATTR"',"","    attrMaps[i].name = stream.readString();","    stream.readArrayFloat32(attrMaps[i].attr);","  }","};","","CTM.ReaderMG1 = function(){","};","","CTM.ReaderMG1.prototype.read = function(stream, body){","  this.readIndices(stream, body.indices);","  this.readVertices(stream, body.vertices);","","  if (body.normals){","    this.readNormals(stream, body.normals);","  }","  if (body.uvMaps){","    this.readUVMaps(stream, body.uvMaps);","  }","  if (body.attrMaps){","    this.readAttrMaps(stream, body.attrMaps);","  }","};","","CTM.ReaderMG1.prototype.readIndices = function(stream, indices){",'  stream.readInt32(); //magic "INDX"',"  stream.readInt32(); //packed size","","  var interleaved = new CTM.InterleavedStream(indices, 3);","  LZMA.decompress(stream, stream, interleaved, interleaved.data.length);","","  CTM.restoreIndices(indices, indices.length);","};","","CTM.ReaderMG1.prototype.readVertices = function(stream, vertices){",'  stream.readInt32(); //magic "VERT"',"  stream.readInt32(); //packed size","","  var interleaved = new CTM.InterleavedStream(vertices, 1);","  LZMA.decompress(stream, stream, interleaved, interleaved.data.length);","};","","CTM.ReaderMG1.prototype.readNormals = function(stream, normals){",'  stream.readInt32(); //magic "NORM"',"  stream.readInt32(); //packed size","","  var interleaved = new CTM.InterleavedStream(normals, 3);","  LZMA.decompress(stream, stream, interleaved, interleaved.data.length);","};","","CTM.ReaderMG1.prototype.readUVMaps = function(stream, uvMaps){","  var i = 0;","  for (; i < uvMaps.length; ++ i){",'    stream.readInt32(); //magic "TEXC"',"","    uvMaps[i].name = stream.readString();","    uvMaps[i].filename = stream.readString();","","    stream.readInt32(); //packed size","","    var interleaved = new CTM.InterleavedStream(uvMaps[i].uv, 2);","    LZMA.decompress(stream, stream, interleaved, interleaved.data.length);","  }","};","","CTM.ReaderMG1.prototype.readAttrMaps = function(stream, attrMaps){","  var i = 0;","  for (; i < attrMaps.length; ++ i){",'    stream.readInt32(); //magic "ATTR"',"","    attrMaps[i].name = stream.readString();","","    stream.readInt32(); //packed size","","    var interleaved = new CTM.InterleavedStream(attrMaps[i].attr, 4);","    LZMA.decompress(stream, stream, interleaved, interleaved.data.length);","  }","};","","CTM.ReaderMG2 = function(){","};","","CTM.ReaderMG2.prototype.read = function(stream, body){","  this.MG2Header = new CTM.FileMG2Header(stream);","","  this.readVertices(stream, body.vertices);","  this.readIndices(stream, body.indices);","","  if (body.normals){","    this.readNormals(stream, body);","  }","  if (body.uvMaps){","    this.readUVMaps(stream, body.uvMaps);","  }","  if (body.attrMaps){","    this.readAttrMaps(stream, body.attrMaps);","  }","};","","CTM.ReaderMG2.prototype.readVertices = function(stream, vertices){",'  stream.readInt32(); //magic "VERT"',"  stream.readInt32(); //packed size","","  var interleaved = new CTM.InterleavedStream(vertices, 3);","  LZMA.decompress(stream, stream, interleaved, interleaved.data.length);","","  var gridIndices = this.readGridIndices(stream, vertices);","","  CTM.restoreVertices(vertices, this.MG2Header, gridIndices, this.MG2Header.vertexPrecision);","};","","CTM.ReaderMG2.prototype.readGridIndices = function(stream, vertices){",'  stream.readInt32(); //magic "GIDX"',"  stream.readInt32(); //packed size","","  var gridIndices = new Uint32Array(vertices.length / 3);","","  var interleaved = new CTM.InterleavedStream(gridIndices, 1);","  LZMA.decompress(stream, stream, interleaved, interleaved.data.length);","","  CTM.restoreGridIndices(gridIndices, gridIndices.length);","","  return gridIndices;","};","","CTM.ReaderMG2.prototype.readIndices = function(stream, indices){",'  stream.readInt32(); //magic "INDX"',"  stream.readInt32(); //packed size","","  var interleaved = new CTM.InterleavedStream(indices, 3);","  LZMA.decompress(stream, stream, interleaved, interleaved.data.length);","","  CTM.restoreIndices(indices, indices.length);","};","","CTM.ReaderMG2.prototype.readNormals = function(stream, body){",'  stream.readInt32(); //magic "NORM"',"  stream.readInt32(); //packed size","","  var interleaved = new CTM.InterleavedStream(body.normals, 3);","  LZMA.decompress(stream, stream, interleaved, interleaved.data.length);","","  var smooth = CTM.calcSmoothNormals(body.indices, body.vertices);","","  CTM.restoreNormals(body.normals, smooth, this.MG2Header.normalPrecision);","};","","CTM.ReaderMG2.prototype.readUVMaps = function(stream, uvMaps){","  var i = 0;","  for (; i < uvMaps.length; ++ i){",'    stream.readInt32(); //magic "TEXC"',"","    uvMaps[i].name = stream.readString();","    uvMaps[i].filename = stream.readString();","","    var precision = stream.readFloat32();","","    stream.readInt32(); //packed size","","    var interleaved = new CTM.InterleavedStream(uvMaps[i].uv, 2);","    LZMA.decompress(stream, stream, interleaved, interleaved.data.length);","","    CTM.restoreMap(uvMaps[i].uv, 2, precision);","  }","};","","CTM.ReaderMG2.prototype.readAttrMaps = function(stream, attrMaps){","  var i = 0;","  for (; i < attrMaps.length; ++ i){",'    stream.readInt32(); //magic "ATTR"',"","    attrMaps[i].name = stream.readString();","","    var precision = stream.readFloat32();","","    stream.readInt32(); //packed size","","    var interleaved = new CTM.InterleavedStream(attrMaps[i].attr, 4);","    LZMA.decompress(stream, stream, interleaved, interleaved.data.length);","","    CTM.restoreMap(attrMaps[i].attr, 4, precision);","  }","};","","CTM.restoreIndices = function(indices, len){","  var i = 3;","  if (len > 0){","    indices[2] += indices[0];","    indices[1] += indices[0];","  }","  for (; i < len; i += 3){","    indices[i] += indices[i - 3];","","    if (indices[i] === indices[i - 3]){","      indices[i + 1] += indices[i - 2];","    }else{","      indices[i + 1] += indices[i];","    }","","    indices[i + 2] += indices[i];","  }","};","","CTM.restoreGridIndices = function(gridIndices, len){","  var i = 1;","  for (; i < len; ++ i){","    gridIndices[i] += gridIndices[i - 1];","  }","};","","CTM.restoreVertices = function(vertices, grid, gridIndices, precision){","  var gridIdx, delta, x, y, z,","      intVertices = new Uint32Array(vertices.buffer, vertices.byteOffset, vertices.length),","      ydiv = grid.divx, zdiv = ydiv * grid.divy,","      prevGridIdx = 0x7fffffff, prevDelta = 0,","      i = 0, j = 0, len = gridIndices.length;","","  for (; i < len; j += 3){","    x = gridIdx = gridIndices[i ++];","","    z = ~~(x / zdiv);","    x -= ~~(z * zdiv);","    y = ~~(x / ydiv);","    x -= ~~(y * ydiv);","","    delta = intVertices[j];","    if (gridIdx === prevGridIdx){","      delta += prevDelta;","    }","","    vertices[j]     = grid.lowerBoundx +","      x * grid.sizex + precision * delta;","    vertices[j + 1] = grid.lowerBoundy +","      y * grid.sizey + precision * intVertices[j + 1];","    vertices[j + 2] = grid.lowerBoundz +","      z * grid.sizez + precision * intVertices[j + 2];","","    prevGridIdx = gridIdx;","    prevDelta = delta;","  }","};","","CTM.restoreNormals = function(normals, smooth, precision){","  var ro, phi, theta, sinPhi,","      nx, ny, nz, by, bz, len,","      intNormals = new Uint32Array(normals.buffer, normals.byteOffset, normals.length),","      i = 0, k = normals.length,","      PI_DIV_2 = 3.141592653589793238462643 * 0.5;","","  for (; i < k; i += 3){","    ro = intNormals[i] * precision;","    phi = intNormals[i + 1];","","    if (phi === 0){","      normals[i]     = smooth[i]     * ro;","      normals[i + 1] = smooth[i + 1] * ro;","      normals[i + 2] = smooth[i + 2] * ro;","    }else{","","      if (phi <= 4){","        theta = (intNormals[i + 2] - 2) * PI_DIV_2;","      }else{","        theta = ( (intNormals[i + 2] * 4 / phi) - 2) * PI_DIV_2;","      }","","      phi *= precision * PI_DIV_2;","      sinPhi = ro * Math.sin(phi);","","      nx = sinPhi * Math.cos(theta);","      ny = sinPhi * Math.sin(theta);","      nz = ro * Math.cos(phi);","","      bz = smooth[i + 1];","      by = smooth[i] - smooth[i + 2];","","      len = Math.sqrt(2 * bz * bz + by * by);","      if (len > 1e-20){","        by /= len;","        bz /= len;","      }","","      normals[i]     = smooth[i]     * nz +","        (smooth[i + 1] * bz - smooth[i + 2] * by) * ny - bz * nx;","      normals[i + 1] = smooth[i + 1] * nz -","        (smooth[i + 2]      + smooth[i]   ) * bz  * ny + by * nx;","      normals[i + 2] = smooth[i + 2] * nz +","        (smooth[i]     * by + smooth[i + 1] * bz) * ny + bz * nx;","    }","  }","};","","CTM.restoreMap = function(map, count, precision){","  var delta, value,","      intMap = new Uint32Array(map.buffer, map.byteOffset, map.length),","      i = 0, j, len = map.length;","","  for (; i < count; ++ i){","    delta = 0;","","    for (j = i; j < len; j += count){","      value = intMap[j];","","      delta += value & 1? -( (value + 1) >> 1): value >> 1;","","      map[j] = delta * precision;","    }","  }","};","","CTM.calcSmoothNormals = function(indices, vertices){","  var smooth = new Float32Array(vertices.length),","      indx, indy, indz, nx, ny, nz,","      v1x, v1y, v1z, v2x, v2y, v2z, len,","      i, k;","","  for (i = 0, k = indices.length; i < k;){","    indx = indices[i ++] * 3;","    indy = indices[i ++] * 3;","    indz = indices[i ++] * 3;","","    v1x = vertices[indy]     - vertices[indx];","    v2x = vertices[indz]     - vertices[indx];","    v1y = vertices[indy + 1] - vertices[indx + 1];","    v2y = vertices[indz + 1] - vertices[indx + 1];","    v1z = vertices[indy + 2] - vertices[indx + 2];","    v2z = vertices[indz + 2] - vertices[indx + 2];","","    nx = v1y * v2z - v1z * v2y;","    ny = v1z * v2x - v1x * v2z;","    nz = v1x * v2y - v1y * v2x;","","    len = Math.sqrt(nx * nx + ny * ny + nz * nz);","    if (len > 1e-10){","      nx /= len;","      ny /= len;","      nz /= len;","    }","","    smooth[indx]     += nx;","    smooth[indx + 1] += ny;","    smooth[indx + 2] += nz;","    smooth[indy]     += nx;","    smooth[indy + 1] += ny;","    smooth[indy + 2] += nz;","    smooth[indz]     += nx;","    smooth[indz + 1] += ny;","    smooth[indz + 2] += nz;","  }","","  for (i = 0, k = smooth.length; i < k; i += 3){","    len = Math.sqrt(smooth[i] * smooth[i] +","      smooth[i + 1] * smooth[i + 1] +","      smooth[i + 2] * smooth[i + 2]);","","    if(len > 1e-10){","      smooth[i]     /= len;","      smooth[i + 1] /= len;","      smooth[i + 2] /= len;","    }","  }","","  return smooth;","};","","CTM.isLittleEndian = (function(){","  var buffer = new ArrayBuffer(2),","      bytes = new Uint8Array(buffer),","      ints = new Uint16Array(buffer);","","  bytes[0] = 1;","","  return ints[0] === 1;","}());","","CTM.InterleavedStream = function(data, count){","  this.data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);","  this.offset = CTM.isLittleEndian? 3: 0;","  this.count = count * 4;","  this.len = this.data.length;","};","","CTM.InterleavedStream.prototype.writeByte = function(value){","  this.data[this.offset] = value;","","  this.offset += this.count;","  if (this.offset >= this.len){","","    this.offset -= this.len - 4;","    if (this.offset >= this.count){","","      this.offset -= this.count + (CTM.isLittleEndian? 1: -1);","    }","  }","};","","CTM.Stream = function(data){","  this.data = data;","  this.chardata = new DataView(data);","  this.offset = 0;","};","","CTM.Stream.prototype.TWO_POW_MINUS23 = Math.pow(2, -23);","","CTM.Stream.prototype.TWO_POW_MINUS126 = Math.pow(2, -126);","","CTM.Stream.prototype.readByte = function(){","  return this.chardata.getUint8(this.offset++);","};","","CTM.Stream.prototype.readInt32 = function(){","var v = this.chardata.getInt32(this.offset, CTM.isLittleEndian);","this.offset += 4;","return v;","};","","CTM.Stream.prototype.readFloat32 = function(){","var v = this.chardata.getFloat32(this.offset, CTM.isLittleEndian);","this.offset += 4;","return v;","};","","CTM.Stream.prototype.readString = function(){","  var len = this.readInt32();","","  this.offset += len;","","	var tmp = new Uint8Array(this.data,this.offset - len, len);","	return String.fromCharCode.apply(null,tmp);","};","","CTM.Stream.prototype.readArrayInt32 = function(array){","  var i = 0, len = array.length;","","  while(i < len){","    array[i ++] = this.readInt32();","  }","","  return array;","};","","CTM.Stream.prototype.readArrayFloat32 = function(array){","  var i = 0, len = array.length;","","  while(i < len){","    array[i ++] = this.readFloat32();","  }","","  return array;","};","","self.onmessage = function( event ) {","var s = Date.now();","","	var files = [];","","	for ( var i = 0; i < event.data.offsets.length; i ++ ) {","","		var stream = new CTM.Stream( event.data.data );","		stream.offset = event.data.offsets[ i ];","","		files[ i ] = new CTM.File( stream );","","	}","","var e = Date.now();",'	self.postMessage( {"f":files,"t":e-s} );',"","}"].join("\n"),XG.JSONLoader=function(e){XG.Loader.call(this,e),this.withCredentials=!1
  },XG.JSONLoader.prototype=Object.create(XG.Loader.prototype),XG.JSONLoader.prototype.load=function(e,t,a){this.onLoadStart(),this.loadAjaxJSON(this,e,t,a)},XG.JSONLoader.prototype.loadAjaxJSON=function(e,t,a,r){void 0===r&&(r={});var i=r.texturePath?r.texturePath:this.extractUrlBase(t),o=r.mergeMaterials,n=r.callbackProgress,s=new XMLHttpRequest,l=0;s.onreadystatechange=function(){if(s.readyState===s.DONE)if(200===s.status||0===s.status){if(s.responseText){var r=JSON.parse(s.responseText);e.createModel(r,a,i,o)}else console.warn("XG.JSONLoader: ["+t+"] seems to be unreachable or file there is empty");e.onLoadComplete()}else console.error("XG.JSONLoader: Couldn't load ["+t+"] ["+s.status+"]");else s.readyState===s.LOADING?n&&(0===l&&(l=s.getResponseHeader("Content-Length")),n({total:l,loaded:s.responseText.length})):s.readyState===s.HEADERS_RECEIVED&&(l=s.getResponseHeader("Content-Length"))},s.open("GET",t,!0),s.withCredentials=this.withCredentials,s.send(null)},XG.JSONLoader.prototype.generateMaterialChunks=function(e,t,a){function r(e,t){return e&1<<t}for(var i,o,n,s,l,h,d,c,u,f,p,m,v=[],g=e.faces,S=g.length,G=0;S>G;){i=g[G++],o=r(i,0),n=r(i,1),l=r(i,2),h=r(i,3),d=r(i,4),c=r(i,5),u=r(i,6),f=r(i,7),o?(p=2,m=4):(p=1,m=3),G+=m,n?(s=g[G++],a&&(s=0)):s=0,void 0===v[s]?v[s]={nTriangles:p,hasNormals:!1,hasUvs:!1,hasColors:!1,hasIndices:!1,indexOffset:0,vertexOffset:0,positionOffset:0,normalOffset:0,colorOffset:0,uvOffset:[],skinWeightOffset:0,skinIndexOffset:0,indexMap:{}}:v[s].nTriangles+=p;var x=v[s];l&&(G+=t),h&&(G+=t*m),d&&(G+=1),c&&(G+=m),u&&(G+=1),f&&(G+=m),(d||c)&&(x.hasNormals|=!0),(l||h)&&(x.hasUvs|=!0),(u||f)&&(x.hasColors|=!0)}return v},XG.JSONLoader.prototype.generateGeometries=function(e,t,a){for(var r=[],i=0,o=e.length;o>i;i++){var n=e[i];if(void 0!==n){var s=new XG.Geometry;s.numPrimitives=n.nTriangles,s.numVertices=3*n.nTriangles;var l=Uint16Array;if(s.numVertices>65536&&(l=XG.elementIndexUintAvailable?Uint32Array:null),null!==l&&(s.addIndex("index",l,3),s.offsets.push({start:0,index:0,count:3*n.nTriangles}),n.hasIndices=!0),s.addAttribute("position",Float32Array,3),n.hasUvs&&s.addAttribute("uv",Float32Array,2),n.hasColors&&s.addAttribute("color",Float32Array,3),s.addAttribute("normal",Float32Array,3),n.hasUvs){n.uvOffset[0]=0;for(var h=1;a>h;h++)s.addAttribute("uv"+(h+1),Float32Array,2),n.uvOffset[h]=0}if(t.skinWeights&&s.addAttribute("skinWeight",Float32Array,4),t.skinIndices&&s.addAttribute("skinIndex",Float32Array,4),void 0===t.morphTargets&&(t.morphTargets=[]),void 0===t.morphColors&&(t.morphColors=[]),t.morphTargets.length>0){s.addVirtualAttribute("morphTarget0"),s.addVirtualAttribute("morphTarget1"),s.addVirtualAttribute("morphTarget2"),s.addVirtualAttribute("morphTarget3"),s.addVirtualAttribute("morphNormal0"),s.addVirtualAttribute("morphNormal1"),s.addVirtualAttribute("morphNormal2"),s.addVirtualAttribute("morphNormal3");for(var h=0,d=t.morphTargets.length;d>h;h++){var c=t.morphTargets[h].name;s.addUnattachedAttribute("mp_"+h,Float32Array,3),s.addUnattachedAttribute("mn_"+h,Float32Array,3),s.morphTargets[h]={name:c,index:s.attributesList.length-2}}}if(t.morphColors.length>0){for(var h=0,d=t.morphColors.length;d>h;h++){{var u=t.morphColors[h],c=u.name;u.colors}s.addUnattachedAttribute("mc_"+h,Float32Array,3),s.morphColors[h]={name:c,index:s.attributesList.length-1,faceColors:!0}}n.hasColors||(s.addVirtualAttribute("color"),s.virtualAttributes.color.mapped=s.attributesList[s.morphColors[0].index])}r[i]=s,s.bones=t.bones;var f=[];t.animations&&(f=t.animations),t.animation&&f.push(t.animation),s.animations=f}}return r},XG.JSONLoader.prototype.fillGeometries=function(e,t,a,r,i){function o(e,t){return e&1<<t}function n(e,t,a,r,i){e[t]=a[3*r]*i,e[t+1]=a[3*r+1]*i,e[t+2]=a[3*r+2]*i}function s(e,t,a,r){e[t]=a[3*r],e[t+1]=a[3*r+1],e[t+2]=a[3*r+2]}function l(e,t,a,r,i){ct=e[3*t],ut=e[3*t+1],ft=e[3*t+2],pt.set(ct,ut,ft),ct=e[3*a],ut=e[3*a+1],ft=e[3*a+2],mt.set(ct,ut,ft),ct=e[3*r],ut=e[3*r+1],ft=e[3*r+2],vt.set(ct,ut,ft),gt.sub(vt,mt),St.sub(pt,mt),gt.crossSelf(St),i[3*t]+=Gt[0],i[3*t+1]+=Gt[1],i[3*t+2]+=Gt[2],i[3*a]+=Gt[0],i[3*a+1]+=Gt[1],i[3*a+2]+=Gt[2],i[3*r]+=Gt[0],i[3*r+1]+=Gt[1],i[3*r+2]+=Gt[2]}var h,d,c,u,f,p,m,v,g,S,G,x,M,y,X,D,_,w,A,C,T,b,P,L,E,F,R,U,N,I,B,O,k,V,H,z,W,j,q,K,Z,Y,Q,J,$,et,tt=void 0!==a.scale?1/a.scale:1,at=new XG.Color,rt=a.faces,it=a.vertices,ot=a.normals,nt=a.colors,st=a.skinWeights,lt=a.skinIndices,ht=new Float32Array(a.vertices.length);if(void 0!==a.morphTargets){var dt=[];for($=0,et=a.morphTargets.length;et>$;$++)dt[$]=new Float32Array(a.vertices.length)}for(var ct,ut,ft,pt=new XG.Vector3,mt=new XG.Vector3,vt=new XG.Vector3,gt=new XG.Vector3,St=new XG.Vector3,Gt=gt.data,xt=0,Mt=0,yt=rt.length;yt>Mt;){f=rt[Mt++],p=o(f,0),m=o(f,1),v=o(f,2),g=o(f,3),S=o(f,4),G=o(f,5),x=o(f,6),M=o(f,7),p?(T=rt[Mt++],b=rt[Mt++],P=rt[Mt++],L=rt[Mt++],Y=4):(T=rt[Mt++],b=rt[Mt++],P=rt[Mt++],Y=3),m?(u=rt[Mt++],i&&(u=0)):u=0,F=t[u],E=e[u],F.hasIndices&&(R=E.attributes.index.array),U=E.attributes.position.array,F.hasNormals&&(N=E.attributes.normal.array),F.hasUvs&&(I=E.attributes.uv.array),F.hasColors&&(B=E.attributes.color.array),V=F.indexOffset,H=F.positionOffset,q=F.vertexOffset;var Xt=F.indexMap;if(p?(F.hasIndices?(R[V]=q,R[V+1]=q+1,R[V+2]=q+3,R[V+3]=q+1,R[V+4]=q+2,R[V+5]=q+3,F.positionOffset+=12):F.positionOffset+=18,F.indexOffset+=6,F.vertexOffset+=4):(F.hasIndices&&(R[V]=q,R[V+1]=q+1,R[V+2]=q+2),F.indexOffset+=3,F.vertexOffset+=3,F.positionOffset+=9),F.hasIndices){for(n(U,H,it,T,tt),n(U,H+3,it,b,tt),n(U,H+6,it,P,tt),Xt[H]=T,Xt[H+3]=b,Xt[H+6]=P,l(it,T,b,P,ht),p&&(n(U,H+9,it,L,tt),Xt[H+9]=L),Q=0,J=a.morphTargets.length;J>Q;Q++){var Dt=E.attributes["mp_"+Q].array,_t=a.morphTargets[Q].vertices;n(Dt,H,_t,T,tt),n(Dt,H+3,_t,b,tt),n(Dt,H+6,_t,P,tt),l(_t,T,b,P,dt[Q]),p&&n(Dt,H+9,_t,L,tt)}for(Q=0,J=a.morphColors.length;J>Q;Q++){var wt=E.attributes["mc_"+Q].array,At=a.morphColors[Q].colors;s(wt,H,At,xt),s(wt,H+3,At,xt),s(wt,H+6,At,xt),p&&s(Dt,H+9,At,xt)}}else if(p){for(n(U,H,it,T,tt),n(U,H+3,it,b,tt),n(U,H+6,it,L,tt),n(U,H+9,it,b,tt),n(U,H+12,it,P,tt),n(U,H+15,it,L,tt),Xt[H]=T,Xt[H+3]=b,Xt[H+6]=L,Xt[H+9]=b,Xt[H+12]=P,Xt[H+15]=L,Q=0,J=a.morphTargets.length;J>Q;Q++){var Dt=E.attributes["mp_"+Q].array,_t=a.morphTargets[Q].vertices;n(Dt,H,_t,T,tt),n(Dt,H+3,_t,b,tt),n(Dt,H+6,_t,L,tt),n(Dt,H+9,_t,b,tt),n(Dt,H+12,_t,P,tt),n(Dt,H+15,_t,L,tt)}for(Q=0,J=a.morphColors.length;J>Q;Q++){var wt=E.attributes["mc_"+Q].array,At=a.morphColors[Q].colors;s(wt,H,At,xt),s(wt,H+3,At,xt),s(wt,H+6,At,xt),s(wt,H+9,At,xt),s(wt,H+12,At,xt),s(wt,H+15,At,xt)}}else{for(n(U,H,it,T,tt),n(U,H+3,it,b,tt),n(U,H+6,it,P,tt),Xt[H]=T,Xt[H+3]=b,Xt[H+6]=P,Q=0,J=a.morphTargets.length;J>Q;Q++){var Dt=E.attributes["mp_"+Q].array,_t=a.morphTargets[Q].vertices;n(Dt,H,_t,T,tt),n(Dt,H+3,_t,b,tt),n(Dt,H+6,_t,P,tt)}for(Q=0,J=a.morphColors.length;J>Q;Q++){var wt=E.attributes["mc_"+Q].array,At=a.morphColors[Q].colors;s(wt,H,At,xt),s(wt,H+3,At,xt),s(wt,H+6,At,xt)}}if(a.skinWeights&&(O=E.attributes.skinWeight.array,K=F.skinWeightOffset,O[K]=st[2*T],O[K+1]=st[2*T+1],O[K+2]=0,O[K+3]=0,O[K+4]=st[2*b],O[K+5]=st[2*b+1],O[K+6]=0,O[K+7]=0,O[K+8]=st[2*P],O[K+9]=st[2*P+1],O[K+10]=0,O[K+11]=0,p?(O[K+12]=st[2*L],O[K+13]=st[2*L+1],O[K+14]=0,O[K+15]=0,F.skinWeightOffset+=16):F.skinWeightOffset+=12),a.skinIndices&&(k=E.attributes.skinIndex.array,Z=F.skinIndexOffset,k[Z]=lt[2*T],k[Z+1]=lt[2*T+1],k[Z+2]=0,k[Z+3]=0,k[Z+4]=lt[2*b],k[Z+5]=lt[2*b+1],k[Z+6]=0,k[Z+7]=0,k[Z+8]=lt[2*P],k[Z+9]=lt[2*P+1],k[Z+10]=0,k[Z+11]=0,p?(k[Z+12]=lt[2*L],k[Z+13]=lt[2*L+1],k[Z+14]=0,k[Z+15]=0,F.skinIndexOffset+=16):F.skinIndexOffset+=12),v)for(Q=0;r>Q;Q++)for(y=a.uvs[Q],c=rt[Mt++],X=y[2*c],D=y[2*c+1],_=0===Q?I:E.attributes["uv"+(Q+1)].array,$=0;Y>$;$++)W=F.uvOffset[Q],_[W]=X,_[W+1]=D,F.uvOffset[Q]+=2;if(g)for(Q=0;r>Q;Q++){for(y=a.uvs[Q],_=0===Q?I:E.attributes["uv"+(Q+1)].array,$=0;Y>$;$++)W=F.uvOffset[Q],c=rt[Mt++],X=y[2*c],D=y[2*c+1],_[W]=X,_[W+1]=D,F.uvOffset[Q]+=2;if(p&&!F.hasIndices){var Ct=F.uvOffset[Q]-4,Tt=_[Ct],bt=_[Ct+1];_[Ct]=X,_[Ct+1]=D,_[Ct+2]=_[Ct-2],_[Ct+3]=_[Ct-1],_[Ct+4]=Tt,_[Ct+5]=bt,_[Ct+6]=X,_[Ct+7]=D,F.uvOffset[Q]+=4}}if(S)for(d=3*rt[Mt++],w=ot[d++],A=ot[d++],C=ot[d],$=0;Y>$;$++)z=F.normalOffset,N[z]=w,N[z+1]=A,N[z+2]=C,F.normalOffset+=3;if(G){for(Q=0;Y>Q;Q++)z=F.normalOffset,d=3*rt[Mt++],w=ot[d++],A=ot[d++],C=ot[d],N[z]=w,N[z+1]=A,N[z+2]=C,F.normalOffset+=3;if(p&&!F.hasIndices){var Ct=F.normalOffset-6,Pt=N[Ct],Lt=N[Ct+1],Et=N[Ct+2];N[Ct]=w,N[Ct+1]=A,N[Ct+2]=C,N[Ct+3]=N[Ct-3],N[Ct+4]=N[Ct-2],N[Ct+5]=N[Ct-1],N[Ct+6]=Pt,N[Ct+7]=Lt,N[Ct+8]=Et,N[Ct+9]=w,N[Ct+10]=A,N[Ct+11]=C,F.normalOffset+=6}}if(x)for(j=F.colorOffset,h=rt[Mt++],at.setHex(nt[h]),$=0;Y>$;$++)B[j]=at.r,B[j+1]=at.g,B[j+2]=at.b,F.colorOffset+=3;if(M){for(j=F.colorOffset,Q=0;Y>Q;Q++)h=rt[Mt++],at.setHex(nt[h]),B[j]=at.r,B[j+1]=at.g,B[j+2]=at.b,F.colorOffset+=3;if(p&&!F.hasIndices){var Ct=F.colorOffset-6,Pt=B[Ct],Lt=B[Ct+1],Et=B[Ct+2];B[Ct]=w,B[Ct+1]=A,B[Ct+2]=C,B[Ct+3]=B[Ct-3],B[Ct+4]=B[Ct-2],B[Ct+5]=B[Ct-1],B[Ct+6]=Pt,B[Ct+7]=Lt,B[Ct+8]=Et,B[Ct+9]=w,B[Ct+10]=A,B[Ct+11]=C,F.colorOffset+=6}}xt+=1}var Ft;for(Q=0,J=ht.length;J>Q;Q+=3)w=ht[Q],A=ht[Q+1],C=ht[Q+2],Ft=1/Math.sqrt(w*w+A*A+C*C),ht[Q]*=Ft,ht[Q+1]*=Ft,ht[Q+2]*=Ft;if(void 0!==a.morphTargets)for($=0,et=a.morphTargets.length;et>$;$++){var Rt=dt[$];for(Q=0,J=Rt.length;J>Q;Q+=3)w=Rt[Q],A=Rt[Q+1],C=Rt[Q+2],Ft=1/Math.sqrt(w*w+A*A+C*C),Rt[Q]*=Ft,Rt[Q+1]*=Ft,Rt[Q+2]*=Ft}for(Q=0,J=t.length;J>Q;Q++){var Ut=t[Q];if(!Ut.hasNormals){E=e[Q],N=E.attributes.normal.array;for(Mt in Ut.indexMap){var Nt=Ut.indexMap[Mt];Mt=parseInt(Mt),N[Mt+0]=ht[3*Nt],N[Mt+1]=ht[3*Nt+1],N[Mt+2]=ht[3*Nt+2]}if(void 0!==a.morphTargets)for($=0,et=a.morphTargets.length;et>$;$++){var Rt=dt[$],It=E.attributes["mn_"+$].array;for(Mt in Ut.indexMap){var Nt=Ut.indexMap[Mt];Mt=parseInt(Mt),It[Mt+0]=Rt[3*Nt],It[Mt+1]=Rt[3*Nt+1],It[Mt+2]=Rt[3*Nt+2]}}}}},XG.JSONLoader.prototype.createModel=function(e,t,a,r){for(var i=0,o=0;o<e.uvs.length;o++)e.uvs[o].length&&i++;var n=this.generateMaterialChunks(e,i,r),s=this.generateGeometries(n,e,i);this.fillGeometries(s,n,e,i,r);var l=this.initMaterials(e.materials,a);t(s,l)},XG.RenderTarget=function(e,t,a){this.id=XG.TextureIdCount++,this.width=e,this.height=t,a=a||{},this.wrapS=void 0!==a.wrapS?a.wrapS:XG.ClampToEdgeWrapping,this.wrapT=void 0!==a.wrapT?a.wrapT:XG.ClampToEdgeWrapping,this.magFilter=void 0!==a.magFilter?a.magFilter:XG.LinearFilter,this.minFilter=void 0!==a.minFilter?a.minFilter:XG.LinearMipMapLinearFilter,this.anisotropy=void 0!==a.anisotropy?a.anisotropy:1,this.offset=new XG.Vector2(0,0),this.repeat=new XG.Vector2(1,1),this.internalFormat=void 0!==a.internalFormat?a.internalFormat:XG.RGBAFormat,this.format=void 0!==a.format?a.format:XG.RGBAFormat,this.type=void 0!==a.type?a.type:XG.UnsignedByteType,this.depthBuffer=void 0!==a.depthBuffer?a.depthBuffer:!0,this.stencilBuffer=void 0!==a.stencilBuffer?a.stencilBuffer:!0,this.mipmapCount=0,this.generateMipmaps=!0,this.shareDepthFrom=null,this.useDepthTexture=void 0!==a.useDepthTexture?a.useDepthTexture:!1,this.depthTextureType=void 0!==a.depthTextureType?a.depthTextureType:XG.UnsignedIntType,this.depthTexture=null,this.useColorTexture=void 0!==a.useColorTexture?a.useColorTexture:!0,this.needsUpdate=!0,this.onUpdate=null},XG.RenderTarget.prototype.setSize=function(e,t){this.width=e,this.height=t,this.needsUpdate=!0},XG.RenderTarget.prototype.clone=function(){var e=new XG.RenderTarget(this.width,this.height);return e.wrapS=this.wrapS,e.wrapT=this.wrapT,e.magFilter=this.magFilter,e.minFilter=this.minFilter,e.anisotropy=this.anisotropy,e.offset.copy(this.offset),e.repeat.copy(this.repeat),e.internalFormat=this.internalFormat,e.format=this.format,e.type=this.type,e.depthBuffer=this.depthBuffer,e.stencilBuffer=this.stencilBuffer,e.mipmapCount=this.mipmapCount,e.generateMipmaps=this.generateMipmaps,e.shareDepthFrom=this.shareDepthFrom,e.useDepthTexture=this.useDepthTexture,e.depthTextureType=this.depthTextureType,e.depthTexture=this.depthTexture,e.useColorTexture=this.useColorTexture,e},XG.RenderTargetCube=function(e,t,a){XG.RenderTarget.call(this,e,t,a),this.activeCubeFace=0},XG.RenderTargetCube.prototype=Object.create(XG.RenderTarget.prototype),XG.RenderTargetArray=function(e,t,a,r,i){i=i||{},this.width=e,this.height=t,this.colorTexture=[],this.depthTexture=null;for(var o=0;a>o;o++)this.colorTexture.push(new XG.RenderTarget(e,t,i));r&&(this.depthTexture=new XG.RenderTarget(e,t,{magFilter:XG.LinearFilter,minFilter:XG.LinearFilter})),this.depthBuffer=void 0!==i.depthBuffer?i.depthBuffer:!0,this.stencilBuffer=void 0!==i.stencilBuffer?i.stencilBuffer:!0,this.generateMipmaps=!0,this.needsUpdate=!0,this.onUpdate=null},XG.RenderTargetArray.prototype.clone=function(){for(var e=new XG.RenderTargetArray(this.width,this.height),t=this.colorTexture.length,a=0;t>a;a++)e.colorTexture.push(this.colorTexture[a].clone());return this.depthTexture&&(e.depthTexture=this.depthTexture.clone()),e.generateMipmaps=this.generateMipmaps,e.depthBuffer=this.depthBuffer,e.stencilBuffer=this.stencilBuffer,e},XG.RenderTargetArray.prototype.setSize=function(e,t){this.width=e,this.height=t;for(var a=this.colorTexture.length,r=0;a>r;r++)this.colorTexture[r].setSize(e,t);this.depthTexture&&this.depthTexture.setSize(e,t),this.needsUpdate=!0},XG.DebugUtils={},XG.DebugUtils.parseTranslatedShaderErrorLog=function(e){for(var t,a,r,i,o,n=/\((\d+),(\d+)-(\d+)\): (.*)/g,s={};t=n.exec(e);)t.length<5||(a=t[1],r=t[2]-1,i=t[3]-1,o=t[4],void 0===s[a]?s[a]={start:r,end:i,lineText:o}:s[a].text+=", "+o);return s},XG.DebugUtils.parseGLSLShaderErrorLog=function(e){for(var t,a,r,i,o,n=e.split("\n").join("").split("WARNING").join("\nWARNING"),s=/(ERROR|WARNING): (\d+):(\d+): (.*)/g,l={};t=s.exec(n);)t.length<4||(o=t[1],a=t[2],r=t[3],i=t[4],void 0===l[r]?l[r]={fileNum:a,lineText:i,type:o}:l[r].text+=", "+i);return l},XG.DebugUtils.printHighlightedLine=function(e,t,a,r,i){var o="%c"+i.substring(0,1).toUpperCase()+i.substring(1)+"\n",n="%c"+r+":",s="%c"+e.substring(0,t),l="%c"+e.substring(t,a+1),h="%c"+e.substring(a+1);console.warn(o+n+s+l+h,"color:saddlebrown","color:gray","color:gray","color:goldenrod","color:gray")},XG.DebugUtils.prettyPrintTranslatedShaderErrors=function(e,t){for(var a=e.split("\n"),r=0,i=a.length;i>r;r++){var o=a[r],n=r+1;t[n]&&XG.DebugUtils.printHighlightedLine(o,t[n].start,t[n].end,n,t[n].lineText)}},XG.DebugUtils.prettyPrintShaderErrors=function(e,t){for(var a=[],r=e.split("\n"),i=0,o=r.length;o>i;i++){var n=i+1,s=n+": "+r[i];if(t[n]){a.length>0&&(console.log(a.join("\n")),a=[]);var l=t[n].lineText,h=t[n].type;"ERROR"===h?console.error("ERROR: "+l+"\n"+s):console.warn("WARNING: "+l+"\n"+s)}}console.log(a.join("\n"))},XG.DebugUtils.addLineNumbers=function(e){for(var t=e.split("\n"),a=0,r=t.length;r>a;a++)t[a]=a+1+": "+t[a];return t.join("\n")},XG.DebugUtils.translateGLErrorCode=function(e){switch(e){case 0:return"NO_ERROR";case 1280:return"INVALID_ENUM";case 1281:return"INVALID_VALUE";case 1282:return"INVALID_OPERATION";case 1283:return"STACK_OVERFLOW";case 1284:return"STACK_UNDERFLOW";case 1285:return"OUT_OF_MEMORY";case 1286:return"INVALID_FRAMEBUFFER_OPERATION"}return"UNKNOWN_ERROR ["+e+"]"},XG.ImageUtils={crossOrigin:"anonymous"},XG.ImageUtils.loadTexture=function(e,t,a){var r=new Image,i=new XG.Texture(r);return r.onload=function(){i.image=r,i.needsUpdate=!0,t&&t(i)},a&&(r.onerror=a),r.crossOrigin=this.crossOrigin,r.src=e,i.sourceFile=e,i},XG.ImageUtils.loadMultipleCRNTexturesFromPack=function(e,t,a){for(var r=!1,i=(Date.now(),[]),o=[],n=0,s=e.length;s>n;n++){var l=e[n],h=l[0],d=l[1],c=l[2];i.push([d,c]),o.push(h)}if(r);else var u=new Worker("js/crunch/CrunchWorker.js");u.onmessage=function(e){for(var t=e.data.textureData,r=0,i=t.length;i>r;r++){var n=t[r],s=o[r];s.format=n.format,s.mipmaps=n.mipmaps,s.image.width=n.width,s.image.height=n.height,s.generateMipmaps=!1,s.needsUpdate=!0}Date.now();a&&a()},u.postMessage({buffer:t,offsets:i},[t])},XG.ImageUtils.loadCRNTextureFromPack=function(e,t,a,r,i){var o=!0,n=XG.ImageUtils.parseCRN(t,o,a,r);return e.format=n.format,e.mipmaps=n.mipmaps,e.image.width=n.width,e.image.height=n.height,e.generateMipmaps=!1,e.needsUpdate=!0,i&&i(e),e},XG.ImageUtils.loadCompressedTextureFromPack=function(e,t,a,r){var i=!0,o=XG.ImageUtils.parseDDS(t,i,a);return e.format=o.format,e.mipmaps=o.mipmaps,e.image.width=o.width,e.image.height=o.height,e.generateMipmaps=!1,e.needsUpdate=!0,r&&r(e),e},XG.ImageUtils.loadCompressedTexture=function(e,t,a){var r=new XG.CompressedTexture,i=new XMLHttpRequest;return i.onload=function(){var e=i.response,a=!0,o=0,n=XG.ImageUtils.parseDDS(e,a,o);r.format=n.format,r.mipmaps=n.mipmaps,r.image.width=n.width,r.image.height=n.height,r.generateMipmaps=!1,r.needsUpdate=!0,t&&t(r)},i.onerror=a,i.open("GET",e,!0),i.responseType="arraybuffer",i.send(null),r},XG.ImageUtils.loadPVRTexture=function(e,t,a){var r=new XG.CompressedTexture,i=new XMLHttpRequest;return i.onload=function(){var e=i.response,a=!0,o=0,n=XG.ImageUtils.parsePVR(e,a,o);r.format=n.format,r.mipmaps=n.mipmaps,r.image.width=n.width,r.image.height=n.height,r.generateMipmaps=!1,r.needsUpdate=!0,t&&t(r)},i.onerror=a,i.open("GET",e,!0),i.responseType="arraybuffer",i.send(null),r},XG.ImageUtils.loadATCTexture=function(){},XG.ImageUtils.loadETCTexture=function(){},XG.ImageUtils.loadCRNTexture=function(e,t,a){var r=new XG.CompressedTexture,i=new XMLHttpRequest;return i.onload=function(){var e=i.response,a=!0,o=XG.ImageUtils.parseCRN(e,a,0);r.format=o.format,r.mipmaps=o.mipmaps,r.image.width=o.width,r.image.height=o.height,r.generateMipmaps=!1,r.needsUpdate=!0,t&&t(r)},i.onerror=a,i.open("GET",e,!0),i.responseType="arraybuffer",i.send(null),r},XG.ImageUtils.loadTextureCube=function(e,t,a){var r=[];r.loadCount=0;var i=new XG.Texture;i.image=r,i.flipY=!1;for(var o=0,n=e.length;n>o;++o){var s=new Image;r[o]=s,s.onload=function(){r.loadCount+=1,6===r.loadCount&&(i.needsUpdate=!0,i.mipmapCount=0,t&&t(i))},s.onerror=a,s.crossOrigin=this.crossOrigin,s.src=e[o]}return i},XG.ImageUtils.loadCompressedTextureCube=function(e,t,a){var r=[];r.loadCount=0;var i=new XG.CompressedTexture;i.image=r,i.flipY=!1,i.generateMipmaps=!1;var o=function(e,a){return function(){var o=e.response,n=!0,s=0,l=XG.ImageUtils.parseDDS(o,n,s);a.format=l.format,a.mipmaps=l.mipmaps,a.width=l.width,a.height=l.height,r.loadCount+=1,6===r.loadCount&&(i.format=l.format,i.mipmapCount=l.mipmapCount,i.needsUpdate=!0,t&&t(i))}};if(e instanceof Array)for(var n=0,s=e.length;s>n;++n){var l={};r[n]=l;var h=new XMLHttpRequest;h.onload=o(h,l),h.onerror=a;var d=e[n];h.open("GET",d,!0),h.responseType="arraybuffer",h.send(null)}else{var d=e,h=new XMLHttpRequest;h.onload=function(){var e=h.response,a=!0,o=0,n=XG.ImageUtils.parseDDS(e,a,o);if(n.isCubemap){for(var s=n.mipmaps.length/n.mipmapCount,l=0;s>l;l++){r[l]={mipmaps:[]};for(var d=0;d<n.mipmapCount;d++)r[l].mipmaps.push(n.mipmaps[l*n.mipmapCount+d]),r[l].format=n.format,r[l].width=n.width,r[l].height=n.height}i.format=n.format,i.mipmapCount=n.mipmapCount,i.needsUpdate=!0,t&&t(i)}},h.onerror=a,h.open("GET",d,!0),h.responseType="arraybuffer",h.send(null)}return i},XG.ImageUtils.loadCRNTextureCube=function(e,t,a){var r=[];r.loadCount=0;var i=new XG.CompressedTexture;i.image=r,i.flipY=!1,i.generateMipmaps=!1;var o=function(e,a){return function(){var o=e.response,n=!0,s=0,l=XG.ImageUtils.parseCRN(o,n,s);a.format=l.format,a.mipmaps=l.mipmaps,a.width=l.width,a.height=l.height,r.loadCount+=1,6===r.loadCount&&(i.format=l.format,i.mipmapCount=l.mipmapCount,i.needsUpdate=!0,t&&t(i))}};if(e instanceof Array)for(var n=0,s=e.length;s>n;++n){var l={};r[n]=l;var h=new XMLHttpRequest;h.onload=o(h,l),h.onerror=a;var d=e[n];h.open("GET",d,!0),h.responseType="arraybuffer",h.send(null)}else console.warn("Loading cubemap from cube CRN file not implemented!");return i},XG.ImageUtils.textureLevelSize=function(e,t,a){switch(e){case XG.RGB_S3TC_DXT1_Format:case XG.RGB_ATC_Format:case XG.RGB_ETC1_Format:return(t+3>>2)*(a+3>>2)*8;case XG.RGBA_S3TC_DXT3_Format:case XG.RGBA_S3TC_DXT5_Format:case XG.RGBA_ATC_EXPLICIT_ALPHA_Format:case XG.RGBA_ATC_INTERPOLATED_ALPHA_Format:return(t+3>>2)*(a+3>>2)*16;case XG.RGB_PVRTC_4BPPV1_Format:case XG.RGBA_PVRTC_4BPPV1_Format:return Math.floor((Math.max(t,8)*Math.max(a,8)*4+7)/8);case XG.RGB_PVRTC_2BPPV1_Format:case XG.RGBA_PVRTC_2BPPV1_Format:return Math.floor((Math.max(t,16)*Math.max(a,8)*2+7)/8);default:return 0}},XG.ImageUtils.parsePVR=function(e,t,a){void 0===a&&(a=0);var r={mipmaps:[],width:0,height:0,format:null,mipmapCount:1},i=0,o=1,n=2,s=3,l=6,h=7,d=9,c=5,u=13,f=55727696,p=0,m=2,v=6,g=7,S=11,G=12,x=new Int32Array(e,0,u);x[p]!==f&&console.error("ImageUtils.parsePVR(): Invalid magic number in PVR header");var M,y=x[m];switch(y){case i:M=XG.RGB_PVRTC_2BPPV1_Format;break;case o:M=XG.RGBA_PVRTC_2BPPV1_Format;break;case n:M=XG.RGB_PVRTC_4BPPV1_Format;break;case s:M=XG.RGBA_PVRTC_4BPPV1_Format;break;case l:M=XG.RGB_ETC1_Format;break;case h:M=XG.RGB_S3TC_DXT1_Format;break;case d:M=XG.RGBA_S3TC_DXT3_Format;break;case c:M=XG.RGBA_S3TC_DXT5_Format;break;default:console.error("Unsupported PVR format: "+y)}r.format=M;for(var X=x[g],D=x[v],_=x[S],w=x[G]+52,A=new Uint8Array(e,w),C=0,T=4,b=0;_>b;++b){var P=XG.ImageUtils.textureLevelSize(M,X,D),L=new Uint8Array(A.buffer,A.byteOffset+C,P),E={data:L,width:X,height:D,unpackAlignment:T};r.mipmaps.push(E),X>>=1,D>>=1,C+=P}return r},XG.ImageUtils.parseDDS=function(e,t,a){function r(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}function i(e){return String.fromCharCode(255&e,e>>8&255,e>>16&255,e>>24&255)}void 0===a&&(a=0);var o={mipmaps:[],width:0,height:0,format:null,mipmapCount:1},n=542327876,s=131072,l=512,h=4,d=64,c=64,u=65,f=r("DXT1"),p=r("DXT3"),m=r("DXT5"),v=31,g=0,S=1,G=2,x=3,M=4,y=7,X=20,D=21,_=28,w=new Uint32Array(e,a,v);if(w[g]!==n)return console.error("ImageUtils.parseDDS(): Invalid magic number in DDS header"),o;if(!w[X]&h)return console.error("ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code"),o;var A=!0,C=0,T=w[D];switch(T){case f:C=8,o.format=XG.RGB_S3TC_DXT1_Format;break;case p:C=16,o.format=XG.RGBA_S3TC_DXT3_Format;break;case m:C=16,o.format=XG.RGBA_S3TC_DXT5_Format;break;default:if(!(w[X]&d))return console.error("ImageUtils.parseDDS(): Unsupported FourCC code: ",T,i(T)),o;if(w[20]===u)o.format=XG.RGBAFormat,A=!1;else{if(w[20]!==c)return console.error("ImageUtils.parseDDS(): Unsupported uncompressed format"),o;o.format=XG.RGBFormat,A=!1}}o.mipmapCount=1,w[G]&s&&t!==!1&&(o.mipmapCount=Math.max(1,w[y])),o.isCubemap=w[_]&l?!0:!1,o.width=w[M],o.height=w[x];for(var b,P,L,E=a+w[S]+4,F=o.width,R=o.height,U=o.isCubemap?6:1,N=0;U>N;N++){for(var I=0;I<o.mipmapCount;I++){var B=4;if(b=A?Math.max(4,F)/4*Math.max(4,R)/4*C:F*R*4,P=new Uint8Array(e,E,b),A)L=P;else if(o.format===XG.RGBAFormat){L=P;for(var O=0;b>O;O+=4){var k=L[O];L[O]=L[O+2],L[O+2]=k}}else if(o.format===XG.RGBFormat){L=new Uint8Array(F*R*3),L.length%16!==0&&(B=1);for(var V=0,O=0;b>O;O+=4){var H=P[O],z=P[O+1],W=P[O+2];L[V++]=W,L[V++]=z,L[V++]=H}}var j={data:L,width:F,height:R,unpackAlignment:B};o.mipmaps.push(j),E+=b,F=Math.max(.5*F,1),R=Math.max(.5*R,1)}F=o.width,R=o.height}return o},XG.ImageUtils.parseCRN=function(e,t,a,r){void 0===a&&(a=0),void 0===r&&(r=e.byteLength);var i={mipmaps:[],width:0,height:0,format:null,mipmapCount:1},o=0,n=1,s=2,l=function(e,t,a){t.set(e,a)},h=new Uint8Array(e,a,r),d=r,c=Module._malloc(d);l(h,Module.HEAPU8,c,d);var u,f=Module._crn_get_dxt_format(c,d);switch(f){case o:u=XG.RGB_S3TC_DXT1_Format;break;case n:u=XG.RGBA_S3TC_DXT3_Format;break;case s:u=XG.RGBA_S3TC_DXT5_Format;break;default:return console.error("ImageUtils.parseCRN(): Unsupported image format"),0}var p=Module._crn_get_width(c,d),m=Module._crn_get_height(c,d),v=Module._crn_get_levels(c,d);i.format=u,i.width=p,i.height=m,i.mipmapCount=v;for(var g=4,S=Module._crn_get_uncompressed_size(c,d,0),G=Module._malloc(S),x=0;v>x;++x){x&&(S=Module._crn_get_uncompressed_size(c,d,x)),Module._crn_decompress(c,d,G,S,x);var M=Module.HEAPU8.buffer.slice(G,G+S),y=new Uint8Array(M),X={data:y,width:p,height:m,unpackAlignment:g};i.mipmaps.push(X),p=Math.max(.5*p,1),m=Math.max(.5*m,1)}return Module._free(c),Module._free(G),i},XG.ImageUtils.getNormalMap=function(e,t){var a=function(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]},r=function(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]},i=function(e){var t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);return[e[0]/t,e[1]/t,e[2]/t]};t=1|t;var o=e.width,n=e.height,s=document.createElement("canvas");s.width=o,s.height=n;var l=s.getContext("2d");l.drawImage(e,0,0);for(var h=l.getImageData(0,0,o,n).data,d=l.createImageData(o,n),c=d.data,u=0;o>u;u++)for(var f=0;n>f;f++){var p=0>f-1?0:f-1,m=f+1>n-1?n-1:f+1,v=0>u-1?0:u-1,g=u+1>o-1?o-1:u+1,S=[],G=[0,0,h[4*(f*o+u)]/255*t];S.push([-1,0,h[4*(f*o+v)]/255*t]),S.push([-1,-1,h[4*(p*o+v)]/255*t]),S.push([0,-1,h[4*(p*o+u)]/255*t]),S.push([1,-1,h[4*(p*o+g)]/255*t]),S.push([1,0,h[4*(f*o+g)]/255*t]),S.push([1,1,h[4*(m*o+g)]/255*t]),S.push([0,1,h[4*(m*o+u)]/255*t]),S.push([-1,1,h[4*(m*o+v)]/255*t]);for(var x=[],M=S.length,y=0;M>y;y++){var X=S[y],D=S[(y+1)%M];X=r(X,G),D=r(D,G),x.push(i(a(X,D)))}for(var _=[0,0,0],y=0;y<x.length;y++)_[0]+=x[y][0],_[1]+=x[y][1],_[2]+=x[y][2];_[0]/=x.length,_[1]/=x.length,_[2]/=x.length;var w=4*(f*o+u);c[w]=(_[0]+1)/2*255|0,c[w+1]=(_[1]+1)/2*255|0,c[w+2]=255*_[2]|0,c[w+3]=255}return l.putImageData(d,0,0),s},XG.ImageUtils.generateDataTexture=function(e,t,a){for(var r=e*t,i=new Uint8Array(3*r),o=Math.floor(255*a.r),n=Math.floor(255*a.g),s=Math.floor(255*a.b),l=0;r>l;l++)i[3*l]=o,i[3*l+1]=n,i[3*l+2]=s;var h=new XG.DataTexture(i,e,t,XG.RGBFormat);return h.needsUpdate=!0,h},XG.ImageUtils.generateNoiseTexture=function(e,t){for(var a=e*t,r=new Uint8Array(3*a),i=0;a>i;i++)r[3*i]=Math.floor(255*Math.random()),r[3*i+1]=Math.floor(255*Math.random()),r[3*i+2]=Math.floor(255*Math.random());var o=new XG.DataTexture(r,e,t,XG.RGBFormat);return o.needsUpdate=!0,o},XG.ImageUtils.generateDummyCompressedTexture=function(e){var t=[542327876,124,659463,4,4,8,0,3,1347242311,1396982829,131585,0,0,0,0,0,0,0,0,32,4,827611204,24,16711680,65280,255,0,4198408,0,0,0,0,38066,2863311530,38066,2863311530,38066,2863311530],a=new Uint32Array(t),r=!0,i=0,o=XG.ImageUtils.parseDDS(a.buffer,r,i);e.format=o.format,e.mipmaps=o.mipmaps,e.image.width=o.width,e.image.height=o.height,e.generateMipmaps=!1,e.needsUpdate=!0},XG.ImageUtils.generateMipTexture=function(e,t){function a(e,t,a){for(var r=e*t,i=new Uint8Array(r),o=16*a,n=0;r>n;n++)i[n]=o;var s={width:e,height:t,data:i};return s}XG.Math.isPowerOfTwo(e)&&XG.Math.isPowerOfTwo(t)||console.error("XG.ImageUtils.generateMipTexture: dimensions [",e,"x",t,"] are not power of two.");for(var r=Math.log(Math.max(e,t))/Math.LN2,i=e,o=t,n=[],s=0;r>=s;s++)n[s]=a(i,o,s),i=Math.max(Math.ceil(.5*i),1),o=Math.max(Math.ceil(.5*o),1);var l=n[0],h=new XG.DataTexture(l.data,e,t,XG.LuminanceFormat);return h.mipmaps=n,h.unpackAlignment=1,h.needsUpdate=!0,h},XG.UniformsUtils={merge:function(e){var t,a,r,i={};for(t=0;t<e.length;t++){r=this.clone(e[t]);for(a in r)i[a]=r[a]}return i},clone:function(e){var t,a,r,i={};for(t in e){i[t]={};for(a in e[t])r=e[t][a],i[t][a]=r instanceof XG.Color||r instanceof XG.Vector2||r instanceof XG.Vector3||r instanceof XG.Vector4||r instanceof XG.Quaternion||r instanceof XG.Matrix3||r instanceof XG.Matrix4||r instanceof XG.Texture?r.clone():r instanceof Array?r.slice():r}return i},cloneDefines:function(e){var t,a={};for(t in e)a[t]=e[t];return a}},XG.AtmosphericFog=function(e,t,a){this.name="",this.color=new XG.Color(e),this.start=void 0!==t?t:100,this.strength=void 0!==a?a:.1},XG.AtmosphericFog.prototype.clone=function(){return new XG.AtmosphericFog(this.color.getHex(),this.start,this.strength)},XG.LinearFog=function(e,t,a){this.name="",this.color=new XG.Color(e),this.near=void 0!==t?t:1,this.far=void 0!==a?a:1e3},XG.LinearFog.prototype.clone=function(){return new XG.LinearFog(this.color.getHex(),this.near,this.far)},XG.ExponentialFog=function(e,t){this.name="",this.color=new XG.Color(e),this.density=void 0!==t?t:25e-5},XG.ExponentialFog.prototype.clone=function(){return new XG.ExponentialFog(this.color.getHex(),this.density)},XG.HeightFog=function(e){e=e||{},this.name="",this.height=void 0!==e.height?e.height:-15,this.visibilityDistance=void 0!==e.visibilityDistance?e.visibilityDistance:50,this.fadeSpeed=void 0!==e.fadeSpeed?e.fadeSpeed:.15,this.shallowDepthColor=void 0!==e.shallowDepthColor?e.shallowDepthColor:(new XG.Color).setRGB(.0078,.5176,.7),this.deepDepthColor=void 0!==e.deepDepthColor?e.deepDepthColor:(new XG.Color).setRGB(.0039,.00196,.145),this.rgbExtinctionDistance=void 0!==e.rgbExtinctionDistance?e.rgbExtinctionDistance:new XG.Vector3(7,30,40)},XG.HeightFog.prototype.clone=function(){var e=new XG.HeightFog;return e.height=this.height,e.visibilityDistance=this.visibilityDistance,e.fadeSpeed=this.fadeSpeed,e.shallowDepthColor.copy(this.shallowDepthColor),e.deepDepthColor.copy(this.deepDepthColor),e.rgbExtinctionDistance.copy(this.rgbExtinctionDistance),e},XG.LightProbe=function(e,t,a,r,i){this.bounces=0;var o,n=void 0!==a?a:XG.FloatType,s=void 0!==r?r:XG.RGBAFormat;i?n===XG.FloatType&&s===XG.RGBAFormat?o=XG.RGBA32F:n===XG.FloatType&&s===XG.RGBFormat?o=XG.RGB32F:n===XG.HalfFloatType2&&s===XG.RGBAFormat?o=XG.RGBA16F:n===XG.HalfFloatType2&&s===XG.RGBFormat?o=XG.RGB16F:n===XG.UnsignedByteType&&(o=s):o=s;var l={format:s,internalFormat:o,type:n,magFilter:XG.LinearFilter,minFilter:XG.LinearMipMapLinearFilter,stencilBuffer:!1},h={format:s,internalFormat:o,type:n,magFilter:XG.LinearFilter,minFilter:XG.LinearFilter,stencilBuffer:!1};this.specularCube=new XG.RenderTargetCube(e,e,l),this.diffuseCube=new XG.RenderTargetCube(t,t,h);var d=XG.IBLDiffuseProbeShader,c=XG.UniformsUtils.clone(d.uniforms);c.tCube.value=this.diffuseCube;var u=new XG.ShaderMaterial({vertexShader:d.vertexShader,fragmentShader:d.fragmentShader,uniforms:c,transparent:!0}),f=XG.IBLDiffuseConvolutionShader,p=XG.UniformsUtils.clone(f.uniforms);p.tCube.value=this.specularCube,this.diffuseConvolutionMaterial=new XG.ShaderMaterial({vertexShader:f.vertexShader,fragmentShader:f.fragmentShader,uniforms:p,side:XG.BackSide,transparent:!0});var m=XG.LightProbe.sphereGeometry;XG.Mesh.call(this,m,u),this.renderDepth=1},XG.LightProbe.prototype=Object.create(XG.Mesh.prototype),XG.LightProbe.sphereGeometry=new XG.SphereGeometry(1,32,16),XG.LightProbesManager=function(e,t,a){this.renderer=e,this.scene=t,this.dynamicObjects=a,this.defaultSpecularSize=128,this.defaultDiffuseSize=16,this.defaultProbeTextureType=XG.FloatType,this.probesList=[],this.convolutionScene=new XG.Scene,this.sceneCamera=new XG.CubeCamera(1,1e3),this.convolutionCamera=new XG.CubeCamera(1,1e3),this.scene.add(this.sceneCamera),this.convolutionScene.add(this.convolutionCamera);var r=new XG.SphereGeometry(2,8,4);this.convolutionMesh=new XG.Mesh(r,null),this.convolutionScene.add(this.convolutionMesh),this.maxBounces=1,this.maxProbesPerFrame=1,this.isES3="webgl2"===e.getRenderingBackend()},XG.LightProbesManager.prototype.createProbe=function(e,t){void 0===e&&(e=this.defaultSpecularSize),void 0===t&&(t=this.defaultDiffuseSize);var a=this.renderer.renderer?this.renderer.renderer:this.renderer,r=a.supportsRGBFloatRenderTarget()?XG.RGBFormat:XG.RGBAFormat,i=this.defaultProbeTextureType,o=new XG.LightProbe(e,t,i,r,this.isES3);return this.probesList.push(o),this.dynamicObjects.push(o),o},XG.LightProbesManager.prototype.update=function(){var e,t,a,r=this.dynamicObjects;for(e=0,t=r.length;t>e;e++)a=r[e],a.properties.oldVisible=a.visible,a.visible=!1;var i=this.renderer,o=this.probesList,n=0;for(e=0,t=o.length;t>e;e++){var s=o[e];if(!(s.bounces>=this.maxBounces)){var l=s.specularCube,h=s.diffuseCube;if(this.sceneCamera.position.copy(s.position),this.convolutionMesh.materials[0]=s.diffuseConvolutionMaterial,i.renderCube(this.scene,this.sceneCamera,l),i.renderCube(this.convolutionScene,this.convolutionCamera,h),s.bounces+=1,n+=1,n>=this.maxProbesPerFrame)break
  }}for(e=0,t=r.length;t>e;e++)a=r[e],a.visible=a.properties.oldVisible},XG.LightProbesManager.prototype.refreshProbes=function(){for(var e=this.probesList,t=0,a=e.length;a>t;t++){var r=e[t];r.bounces=0}},XG.Material=function(){this.id=XG.MaterialIdCount++,this.name="",this.side=XG.FrontSide,this.opacity=1,this.transparent=!1,this.blending=XG.NormalBlending,this.blendSrcColor=XG.SrcAlphaFactor,this.blendDstColor=XG.OneMinusSrcAlphaFactor,this.blendSrcAlpha=XG.OneFactor,this.blendDstAlpha=XG.OneMinusSrcAlphaFactor,this.blendEquation=XG.AddEquation,this.depthTest=!0,this.depthWrite=!0,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.alphaTest=0,this.particle=!1,this.particleSize=1,this.instances=!1,this.visible=!0,this.enabled=!0,this.needsUpdate=!0},XG.Material.prototype.setValues=function(e){if(void 0!==e)for(var t in e){var a=e[t];if(void 0!==a){if(t in this){var r=this[t];r instanceof XG.Color&&a instanceof XG.Color?r.copy(a):r instanceof XG.Color?r.set(a):r instanceof XG.Vector2&&a instanceof XG.Vector2?r.copy(a):r instanceof XG.Vector3&&a instanceof XG.Vector3?r.copy(a):this[t]=a}}else console.warn("XG.Material: '"+t+"' parameter is undefined.")}},XG.Material.prototype.clone=function(e){return void 0===e&&(e=new XG.Material),e.name=this.name,e.side=this.side,e.opacity=this.opacity,e.transparent=this.transparent,e.blending=this.blending,e.blendSrcColor=this.blendSrcColor,e.blendDstColor=this.blendDstColor,e.blendSrcAlpha=this.blendSrcAlpha,e.blendDstAlpha=this.blendDstAlpha,e.blendEquation=this.blendEquation,e.depthTest=this.depthTest,e.depthWrite=this.depthWrite,e.polygonOffset=this.polygonOffset,e.polygonOffsetFactor=this.polygonOffsetFactor,e.polygonOffsetUnits=this.polygonOffsetUnits,e.alphaTest=this.alphaTest,e.particle=this.particle,e.particleSize=this.particleSize,e.instances=this.instances,e.visible=this.visible,e},XG.MaterialIdCount=0,XG.EmissiveMaterial=function(e){XG.Material.call(this),this.color=new XG.Color(16777215),this.intensity=1,this.map=null,this.lightMap=null,this.fog=!0,this.vertexColors=!1,this.skinning=!1,this.morphTargets=!1,this.particleSize=1,this.particleSizeAttenuation=!0,this.setValues(e)},XG.EmissiveMaterial.prototype=Object.create(XG.Material.prototype),XG.EmissiveMaterial.prototype.clone=function(){var e=new XG.EmissiveMaterial;return XG.Material.prototype.clone.call(this,e),e.color.copy(this.color),e.intensity=this.intensity,e.map=this.map,e.lightMap=this.lightMap,e.fog=this.fog,e.vertexColors=this.vertexColors,e.skinning=this.skinning,e.morphTargets=this.morphTargets,e.particleSize=this.particleSize,e.particleSizeAttenuation=this.particleSizeAttenuation,e},XG.PhongMaterial=function(e){XG.Material.call(this),this.color=new XG.Color(16777215),this.specular=new XG.Color(1118481),this.shininess=30,this.metal=!1,this.parallax=!1,this.parallaxScale=1,this.parallaxRefineSteps=3,this.wrapAround=!1,this.wrapAroundSkin=!1,this.wrapRGB=new XG.Vector3(1,1,1),this.map=null,this.lightMap=null,this.displacementMap=null,this.displacementDirection=XG.DisplaceByNormal,this.displacementScale=1,this.displacementBias=0,this.displacementNormalScale=1,this.glossMap=null,this.specularMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalGlossMap=null,this.normalScale=new XG.Vector2(1,1),this.bumpDetailMap=null,this.normalDetailMap=null,this.detailScale=1,this.detailRepeat=new XG.Vector2(1,1),this.fog=!0,this.vertexColors=!1,this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.lights=!0,this.setValues(e)},XG.PhongMaterial.prototype=Object.create(XG.Material.prototype),XG.PhongMaterial.prototype.clone=function(){var e=new XG.PhongMaterial;return XG.Material.prototype.clone.call(this,e),e.color.copy(this.color),e.specular.copy(this.specular),e.shininess=this.shininess,e.metal=this.metal,e.parallax=this.parallax,e.parallaxScale=this.parallaxScale,e.parallaxRefineSteps=this.parallaxRefineSteps,e.wrapAround=this.wrapAround,e.wrapAroundSkin=this.wrapAroundSkin,e.wrapRGB.copy(this.wrapRGB),e.map=this.map,e.lightMap=this.lightMap,e.bumpMap=this.bumpMap,e.bumpScale=this.bumpScale,e.displacementMap=this.displacementMap,e.displacementScale=this.displacementScale,e.displacementBias=this.displacementBias,e.displacementNormalScale=this.displacementNormalScale,e.normalMap=this.normalMap,e.normalGlossMap=this.normalGlossMap,e.normalScale.copy(this.normalScale),e.bumpDetailMap=this.bumpDetailMap,e.normalDetailMap=this.normalDetailMap,e.detailScale=this.detailScale,e.detailRepeat.copy(this.detailRepeat),e.glossMap=this.glossMap,e.specularMap=this.specularMap,e.fog=this.fog,e.vertexColors=this.vertexColors,e.skinning=this.skinning,e.morphTargets=this.morphTargets,e.morphNormals=this.morphNormals,e.lights=this.lights,e},XG.DynamicParticleMaterial=function(e){XG.Material.call(this),this.color=new XG.Color(16777215),this.intensity=1,this.map=null,this.fog=!0,this.vertexColors=!1,this.particle=!0,this.particleSize=1,this.particleSizeAttenuation=!0,this.time=0,this.timeRange=1,this.timeOffset=0,this.numFrames=1,this.frameDuration=1,this.interpolateFrames=!0,this.additiveFactor=0,this.lights=!1,this.setValues(e)},XG.DynamicParticleMaterial.prototype=Object.create(XG.Material.prototype),XG.DynamicParticleMaterial.prototype.clone=function(){var e=new XG.DynamicParticleMaterial;return XG.Material.prototype.clone.call(this,e),e.color.copy(this.color),e.intensity=this.intensity,e.map=this.map,e.fog=this.fog,e.vertexColors=this.vertexColors,e.particleSize=this.particleSize,e.particleSizeAttenuation=this.particleSizeAttenuation,e.time=this.time,e.timeRange=this.timeRange,e.timeOffset=this.timeOffset,e.numFrames=this.numFrames,e.frameDuration=this.frameDuration,e.interpolateFrames=this.interpolateFrames,e.additiveFactor=this.additiveFactor,e.lights=this.lights,e},XG.ShaderMaterial=function(e){XG.Material.call(this),this.fragmentShader="void main() {}",this.vertexShader="void main() {}",this.uniforms={},this.defines={},this.extensions={},this.attributes=null,this.fog=!1,this.lights=!1,this.vertexColors=!1,this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.forceShadow=!1,this.setValues(e)},XG.ShaderMaterial.prototype=Object.create(XG.Material.prototype),XG.ShaderMaterial.prototype.clone=function(){var e=new XG.ShaderMaterial;return XG.Material.prototype.clone.call(this,e),e.fragmentShader=this.fragmentShader,e.vertexShader=this.vertexShader,e.uniforms=XG.UniformsUtils.clone(this.uniforms),e.defines=this.defines,e.extensions=this.extensions,e.attributes=this.attributes,e.fog=this.fog,e.lights=this.lights,e.vertexColors=this.vertexColors,e.skinning=this.skinning,e.morphTargets=this.morphTargets,e.morphNormals=this.morphNormals,e.forceShadow=this.forceShadow,e},XG.SpriteMaterial=function(e){void 0===e&&(e={});var t=void 0!==e.billboard?e.billboard:!0,a=void 0!==e.antialias?e.antialias:!1,r=void 0!==e.sdf?e.sdf:!0,i=void 0!==e.fog?e.fog:!0,o=void 0!==e.alphaTest?e.alphaTest:a?.01:.5,n=void 0!==e.epsilon?e.epsilon:.1,s=void 0!==e.fogDensity?e.fogDensity:.015,l=void 0!==e.fogColor?e.fogColor:0,h=void 0!==e.color?e.color:16777215,d=XG.SpriteShader,c={BILLBOARD:t,ANTIALIAS:a,SDF:r,FOG:i},u=XG.UniformsUtils.clone(d.uniforms);u.map.value=e.textureAtlas,u.alphaTest.value=o,u.epsilon.value=n,u.fogDensity.value=s,u.fogColor.value.setHex(l),u.baseColor.value.setHex(h),a&&(e.transparent=!0),e.alphaTest=o,e.vertexShader=d.vertexShader,e.fragmentShader=d.fragmentShader,e.extensions=d.extensions,e.uniforms=u,XG.ShaderMaterial.call(this,e),this.defines=c,this.uniforms=u},XG.SpriteMaterial.prototype=Object.create(XG.ShaderMaterial.prototype),XG.Texture=function(e,t,a,r,i,o,n,s){this.id=XG.TextureIdCount++,this.name="",this.image=e,this.mipmaps=[],this.mipmapCount=0,this.wrapS=void 0!==t?t:XG.ClampToEdgeWrapping,this.wrapT=void 0!==a?a:XG.ClampToEdgeWrapping,this.magFilter=void 0!==r?r:XG.LinearFilter,this.minFilter=void 0!==i?i:XG.LinearMipMapLinearFilter,this.anisotropy=void 0!==s?s:1,this.format=void 0!==o?o:XG.RGBAFormat,this.type=void 0!==n?n:XG.UnsignedByteType,this.offset=new XG.Vector2(0,0),this.repeat=new XG.Vector2(1,1),this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.needsUpdate=!1,this.onUpdate=null},XG.Texture.prototype={constructor:XG.Texture,clone:function(e){return void 0===e&&(e=new XG.Texture),e.image=this.image,e.mipmaps=this.mipmaps.slice(0),e.wrapS=this.wrapS,e.wrapT=this.wrapT,e.magFilter=this.magFilter,e.minFilter=this.minFilter,e.anisotropy=this.anisotropy,e.format=this.format,e.type=this.type,e.offset.copy(this.offset),e.repeat.copy(this.repeat),e.generateMipmaps=this.generateMipmaps,e.premultiplyAlpha=this.premultiplyAlpha,e.flipY=this.flipY,e.unpackAlignment=this.unpackAlignment,e}},XG.TextureIdCount=0,XG.CompressedTexture=function(e,t,a,r,i,o,n,s,l,h){XG.Texture.call(this,null,o,n,s,l,r,i,h),this.image={width:t,height:a},this.mipmaps=e,this.generateMipmaps=!1},XG.CompressedTexture.prototype=Object.create(XG.Texture.prototype),XG.CompressedTexture.prototype.clone=function(){var e=new XG.CompressedTexture;return XG.Texture.prototype.clone.call(this,e),e},XG.DataTexture=function(e,t,a,r,i,o,n,s,l,h){XG.Texture.call(this,null,o,n,s,l,r,i,h),this.image={data:e,width:t,height:a}},XG.DataTexture.prototype=Object.create(XG.Texture.prototype),XG.DataTexture.prototype.clone=function(){var e=new XG.DataTexture;return XG.Texture.prototype.clone.call(this,e),e},XG.ShaderChunk={},XG.UniformsLib={},XG.ShaderLib={},XG.UniformsLib.common={map:{type:"t",value:null},offsetRepeat:{type:"v4",value:new XG.Vector4(0,0,1,1)},lightMap:{type:"t",value:null},brightness:{type:"f",value:1},whitePoint:{type:"f",value:1}},XG.UniformsLib.displacement={displacementMap:{type:"t",value:null},displacementScaleBias:{type:"v2",value:new XG.Vector2(1,0)},displacementNormalScale:{type:"f",value:1}},XG.UniformsLib.bump={bumpMap:{type:"t",value:null},bumpScale:{type:"f",value:1},bumpDetailMap:{type:"t",value:null}},XG.UniformsLib.normalmap={normalMap:{type:"t",value:null},normalScale:{type:"v2",value:new XG.Vector2(1,1)},normalDetailMap:{type:"t",value:null}},XG.UniformsLib.particle={particleSize:{type:"f",value:1},screenWidth:{type:"f",value:1920}},XG.UniformsLib.fogAtmo={fogColor:{type:"c",value:new XG.Color(0)},fogStrength:{type:"f",value:.1},fogStart:{type:"f",value:100}},XG.ShaderChunk.fogAtmoFragmentPars=["#ifdef FOG_ENABLED","uniform vec3 fogColor;","uniform float fogStrength;","uniform float fogStart;","vec3 addFog( vec3 color, float depth ) {","float fogFactor = depth / ( cameraNearFar.y - cameraNearFar.x );","fogFactor *= smoothstep( 0.0, fogStart, depth );","fogFactor = clamp( fogFactor, 0.0, fogStrength );","return mix( color, fogColor, fogFactor );","}","#endif"].join("\n"),XG.ShaderChunk.linearDepthFragmentPars=["float linearizeDepth( float depth, vec2 cameraNearFar ) {","return -cameraNearFar.y * cameraNearFar.x / ( depth * ( cameraNearFar.y - cameraNearFar.x ) - cameraNearFar.y );","}"].join("\n"),XG.ShaderChunk.color_pars_fragment=["#ifdef USE_COLOR","varying vec3 vColor;","#endif"].join("\n"),XG.ShaderChunk.color_fragment=["#ifdef USE_COLOR","mgl_FragColor.rgb *= vColor;","#endif"].join("\n"),XG.ShaderChunk.color_pars_vertex=["#ifdef USE_COLOR","varying vec3 vColor;","#endif"].join("\n"),XG.ShaderChunk.color_vertex=["#ifdef USE_COLOR","#ifdef GAMMA_INPUT","vColor = color * color;","#else","vColor = color;","#endif","#endif"].join("\n"),XG.ShaderChunk.map_pars_vertex=["#if !defined( PARTICLE ) && ( defined( USE_MAP ) || defined( USE_LIGHTMAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined ( USE_NORMALGLOSSMAP ) || defined ( USE_GLOSSMAP ) || defined( USE_SPECULARMAP ) || defined( USE_DISPLACEMENTMAP ) )","varying vec2 vUv;","uniform vec4 offsetRepeat;","#endif"].join("\n"),XG.ShaderChunk.map_pars_fragment=["#if !defined( PARTICLE ) && ( defined( USE_MAP ) || defined( USE_LIGHTMAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_NORMALGLOSSMAP ) || defined ( USE_GLOSSMAP ) || defined( USE_SPECULARMAP ) || defined( USE_DISPLACEMENTMAP ) )","varying vec2 vUv;","#endif","#ifdef USE_MAP","uniform sampler2D map;","#endif"].join("\n"),XG.ShaderChunk.map_vertex=["#if !defined( PARTICLE ) && ( defined( USE_MAP ) || defined( USE_LIGHTMAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_BUMPDETAILMAP ) || defined( USE_NORMALDETAILMAP ) || defined( USE_NORMALGLOSSMAP ) || defined ( USE_GLOSSMAP ) || defined( USE_SPECULARMAP ) || defined( USE_DISPLACEMENTMAP ) )","vec2 transformedUV = uv * offsetRepeat.zw + offsetRepeat.xy;","vUv = transformedUV;","#endif"].join("\n"),XG.ShaderChunk.map_fragment=["#ifdef USE_MAP","vec2 texCoord;","#ifdef PARTICLE","texCoord = vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y );","#else","texCoord = uvCoord;","#endif","vec4 texelColor = texture2D( map, texCoord );","#ifdef GAMMA_INPUT","texelColor.xyz *= texelColor.xyz;","#endif","mgl_FragColor = mgl_FragColor * texelColor;","#endif"].join("\n"),XG.ShaderChunk.specularmap_pars_fragment=["#ifdef USE_SPECULARMAP","uniform sampler2D specularMap;","#endif"].join("\n"),XG.ShaderChunk.specularmap_fragment=["vec3 specularMapColor;","#ifdef USE_SPECULARMAP","vec4 texelSpecular = texture2D( specularMap, uvCoord );","specularMapColor = texelSpecular.rgb;","#else","specularMapColor = vec3( 1.0 );","#endif"].join("\n"),XG.ShaderChunk.glossmap_pars_fragment=["#ifdef USE_GLOSSMAP","uniform sampler2D glossMap;","#endif"].join("\n"),XG.ShaderChunk.lightmap_pars_fragment=["#ifdef USE_LIGHTMAP","uniform sampler2D lightMap;","#endif"].join("\n"),XG.ShaderChunk.lightmap_fragment=["#ifdef USE_LIGHTMAP","float lightMapIntensity = texture2D( lightMap, uvCoord ).r;","#else","float lightMapIntensity = 1.0;","#endif"].join("\n"),XG.ShaderChunk.bumpmap_pars_fragment=["#ifdef USE_BUMPDETAILMAP","uniform sampler2D bumpDetailMap;","#endif","#ifdef USE_BUMPMAP","uniform sampler2D bumpMap;","uniform float bumpScale;","#endif"].join("\n"),XG.ShaderChunk.derivativemap_pars_fragment=["#if defined( USE_BUMPMAP ) || defined( USE_DISPLACEMENTMAP )","vec2 dHdxy_fwd( const in sampler2D sourceMap, const in vec2 texCoord, const in float sourceScale ) {","vec2 dSTdx = dFdx( texCoord );","vec2 dSTdy = dFdy( texCoord );","float Hll = sourceScale * texture2D( sourceMap, texCoord ).x;","float dBx = sourceScale * texture2D( sourceMap, texCoord + dSTdx ).x - Hll;","float dBy = sourceScale * texture2D( sourceMap, texCoord + dSTdy ).x - Hll;","return vec2( dBx, dBy );","}","vec3 perturbNormalArb( const in vec3 surf_pos, const in vec3 surf_norm, const in vec2 dHdxy ) {","vec3 vSigmaX = dFdx( surf_pos );","vec3 vSigmaY = dFdy( surf_pos );","vec3 vN = surf_norm;","vec3 R1 = cross( vSigmaY, vN );","vec3 R2 = cross( vN, vSigmaX );","float fDet = dot( vSigmaX, R1 );","vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );","return normalize( abs( fDet ) * surf_norm - vGrad );","}","#endif"].join("\n"),XG.ShaderChunk.normalmap_pars_fragment=["#ifdef USE_NORMALDETAILMAP","uniform sampler2D normalDetailMap;","#endif","#if defined( USE_NORMALMAP ) || defined( USE_NORMALGLOSSMAP ) || defined( USE_NORMALDETAILMAP )","uniform sampler2D normalMap;","uniform vec2 normalScale;","vec3 perturbNormal2Arb( const in vec3 eye_pos, const in vec3 surf_norm, const in vec3 normal_pixel, const in vec2 texCoord ) {","vec3 q0 = dFdx( eye_pos.xyz );","vec3 q1 = dFdy( eye_pos.xyz );","vec2 st0 = dFdx( texCoord.st );","vec2 st1 = dFdy( texCoord.st );","vec3 S = normalize(  q0 * st1.t - q1 * st0.t );","vec3 T = normalize( -q0 * st1.s + q1 * st0.s );","vec3 N = normalize( surf_norm );","vec3 mapN = normal_pixel * 2.0 - 1.0;","mapN.xy = normalScale * mapN.xy;","mat3 tsn = mat3( S, T, N );","return normalize( tsn * mapN );","}","#endif"].join("\n"),XG.ShaderChunk.parallax_pars_fragment=["#if defined( USE_PARALLAX ) && defined( USE_BUMPMAP )","uniform float parallaxScale;","vec2 computeParallaxProjection( const in vec3 surf_pos, const in vec3 surf_norm, const in vec3 surf_view, const in vec2 texCoord ) {","vec2 TexDx = dFdx( texCoord );","vec2 TexDy = dFdy( texCoord );","vec3 vSigmaX = dFdx( surf_pos );","vec3 vSigmaY = dFdy( surf_pos );","vec3 vN = surf_norm;","vec3 vR1 = cross( vSigmaY, vN );","vec3 vR2 = cross( vN, vSigmaX );","float fDet = dot( vSigmaX, vR1 );","vec3 vV = surf_view;","vec2 vProjVscr = ( 1.0 / fDet ) * vec2( dot( vR1, vV ), dot( vR2, vV ) );","vec2 vProjVtex = TexDx * vProjVscr.x + TexDy * vProjVscr.y;","return vProjVtex;","}","#endif"].join("\n"),XG.ShaderChunk.parallax_fragment=["#if defined( USE_PARALLAX ) && defined( USE_BUMPMAP )","float height = parallaxScale * ( 2.0 * texture2D( bumpMap, vUv ).x - 1.0 );","vec2 parallaxProjection = computeParallaxProjection( vViewPosition, normal, eyeVector, vUv );","vec2 uvOffset = parallaxProjection * height;","uvCoord += uvOffset;","#ifdef PARALLAX_REFINE_STEPS","for ( int i = 0; i < PARALLAX_REFINE_STEPS; i ++ ) {","height += parallaxScale * ( texture2D( bumpMap, uvCoord ).x - 1.0 );","uvOffset = parallaxProjection * height;","uvCoord = vUv + uvOffset;","}","#endif","#endif"].join("\n"),XG.ShaderChunk.instances_pars_vertex=["#if defined( USE_INSTANCES )","attribute vec3 offset;","attribute vec4 rotation;","vec3 rotateVectorByQuaternion( vec3 v, vec4 q ) {","return v + 2.0 * cross( q.xyz, cross( q.xyz, v ) + q.w * v );","}","#endif"].join("\n"),XG.ShaderChunk.begin_pos_vertex=["vec4 transformedPosition = vec4( position, 1.0 );"].join("\n"),XG.ShaderChunk.displacementmap_pars_fragment=["#ifdef USE_DISPLACEMENTMAP","uniform sampler2D displacementMap;","uniform float displacementNormalScale;","#endif"].join("\n"),XG.ShaderChunk.displacement_pars_vertex=["#ifdef USE_DISPLACEMENTMAP","uniform sampler2D displacementMap;","uniform vec2 displacementScaleBias;","#endif"].join("\n"),XG.ShaderChunk.displacement_vertex=["#ifdef USE_DISPLACEMENTMAP","vec3 displacementValue = texture2D( displacementMap, transformedUV ).xyz;","float scaledDisplacement = displacementValue.x * displacementScaleBias.x + displacementScaleBias.y;","vec3 displaced = transformedPosition.xyz;","#ifdef DISPLACE_BY_POSITION","displaced += normalize( transformedPosition.xyz ) * scaledDisplacement;","#endif","#ifdef DISPLACE_BY_NORMAL","displaced += normalize( normal ) * scaledDisplacement;","#endif","transformedPosition.xyz = displaced;","#endif"].join("\n"),XG.ShaderChunk.skinning_pars_vertex=["#ifdef USE_SKINNING","#ifdef BONE_TEXTURE","uniform sampler2D boneTexture;","mat4 getBoneMatrix( const in float i ) {","float j = i * 4.0;","float x = mod( j, N_BONE_PIXEL_X );","float y = floor( j / N_BONE_PIXEL_X );","const float dx = 1.0 / N_BONE_PIXEL_X;","const float dy = 1.0 / N_BONE_PIXEL_Y;","y = dy * ( y + 0.5 );","vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );","vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );","vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );","vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );","mat4 bone = mat4( v1, v2, v3, v4 );","return bone;","}","#else","uniform mat4 boneGlobalMatrices[ MAX_BONES ];","mat4 getBoneMatrix( const in float i ) {","mat4 bone = boneGlobalMatrices[ int(i) ];","return bone;","}","#endif","#endif"].join("\n"),XG.ShaderChunk.skinbase_vertex=["#ifdef USE_SKINNING","mat4 boneMatX = getBoneMatrix( skinIndex.x );","mat4 boneMatY = getBoneMatrix( skinIndex.y );","#endif"].join("\n"),XG.ShaderChunk.skinning_vertex=["#ifdef USE_SKINNING","vec4 skinned  = boneMatX * transformedPosition * skinWeight.x;","skinned 	  += boneMatY * transformedPosition * skinWeight.y;","transformedPosition = skinned;","#endif"].join("\n"),XG.ShaderChunk.morphtarget_pars_vertex=["#ifdef USE_MORPHTARGETS","uniform float morphTargetInfluences[ 4 ];","#endif"].join("\n"),XG.ShaderChunk.morphtarget_vertex=["#ifdef USE_MORPHTARGETS","vec3 morphed = vec3( 0.0 );","morphed += ( morphTarget0 - transformedPosition.xyz ) * morphTargetInfluences[ 0 ];","#if MAX_MORPHTARGETS > 1","morphed += ( morphTarget1 - transformedPosition.xyz ) * morphTargetInfluences[ 1 ];","#if MAX_MORPHTARGETS > 2","morphed += ( morphTarget2 - transformedPosition.xyz ) * morphTargetInfluences[ 2 ];","#if MAX_MORPHTARGETS > 3","morphed += ( morphTarget3 - transformedPosition.xyz ) * morphTargetInfluences[ 3 ];","#endif","#endif","#endif","morphed += transformedPosition.xyz;","transformedPosition.xyz = morphed;","#endif"].join("\n"),XG.ShaderChunk.end_pos_vertex=["vec4 mvPosition;","#if defined( USE_INSTANCES )","transformedPosition.xyz = rotateVectorByQuaternion( transformedPosition.xyz, rotation ) + offset;","#endif","mvPosition = modelViewMatrix * transformedPosition;","gl_Position = projectionMatrix * mvPosition;"].join("\n"),XG.ShaderChunk.begin_nor_vertex=["vec3 transformedNormal = normal;"].join("\n"),XG.ShaderChunk.morphnormal_vertex=["#ifdef USE_MORPHNORMALS","vec3 morphedNormal = vec3( 0.0 );","morphedNormal +=  ( morphNormal0 - transformedNormal ) * morphTargetInfluences[ 0 ];","#if MAX_MORPHNORMALS > 1","morphedNormal +=  ( morphNormal1 - transformedNormal ) * morphTargetInfluences[ 1 ];","#if MAX_MORPHNORMALS > 2","morphedNormal +=  ( morphNormal2 - transformedNormal ) * morphTargetInfluences[ 2 ];","#if MAX_MORPHNORMALS > 3","morphedNormal +=  ( morphNormal3 - transformedNormal ) * morphTargetInfluences[ 3 ];","#endif","#endif","#endif","morphedNormal += transformedNormal;","transformedNormal = morphedNormal;","#endif"].join("\n"),XG.ShaderChunk.skinnormal_vertex=["#ifdef USE_SKINNING","mat4 skinMatrix = skinWeight.x * boneMatX;","skinMatrix 	+= skinWeight.y * boneMatY;","vec4 skinnedNormal = skinMatrix * vec4( transformedNormal, 0.0 );","transformedNormal = skinnedNormal.xyz;","#endif"].join("\n"),XG.ShaderChunk.end_nor_vertex=["#if defined( USE_INSTANCES )","transformedNormal = rotateVectorByQuaternion( transformedNormal, rotation );","#endif","#ifdef FLIP_SIDED","transformedNormal = -transformedNormal;","#endif","transformedNormal = normalize( normalMatrix * transformedNormal );"].join("\n"),XG.ShaderChunk.particle_pars_vertex=["#ifdef PARTICLE","uniform float particleSize;","uniform float screenWidth;","#endif"].join("\n"),XG.ShaderChunk.particle_vertex=["#ifdef PARTICLE","#ifdef USE_PARTICLE_SIZEATTENUATION","vec4 projectedCorner = projectionMatrix * vec4( 0.5 * particleSize, 0.5 * particleSize, mvPosition.z, mvPosition.w );","gl_PointSize = screenWidth * projectedCorner.x / projectedCorner.w;","#else","gl_PointSize = particleSize;","#endif","#endif"].join("\n"),XG.ShaderChunk.utils_pars_fragment=["float saturate( float x ) {","return clamp( x, 0.0, 1.0 );","}","vec3 saturate( vec3 x ) {","return clamp( x, vec3( 0.0 ), vec3( 1.0 ) );","}"].join("\n"),XG.ShaderChunk.skin_pars_fragment=["vec3 PSSFitFunction( in float NdotL, in float r ) {","const vec3 a0 = vec3( 0.0605, 0.2076, 0.2243 );","const vec3 a1 = vec3( 0.0903, 0.1687, 0.2436 );","const vec3 a2 = vec3( -0.0210, -0.0942, -0.1116 );","const vec3 a3 = vec3( 0.6896, 0.6762, 0.6480 );","const vec3 a4 = vec3( -0.1110, -0.5023, -0.6703 );","const vec3 a5 = vec3( 0.8177, 0.9119, 0.9209 );","vec3 t = vec3( NdotL ) * ( a0 * r + a1 ) + ( a2 * r + a3 );","vec3 fade = saturate( a4 * r + a5 );","return t * t * t * fade + saturate( NdotL ) * ( 1.0 - fade );","}"].join("\n"),XG.ShaderChunk.tonemappingFragmentPars=["#ifdef TONEMAPPING","const vec3 GAMMA = vec3( 1.0 / 2.2 );","const vec3 LUMA = vec3( 0.2126, 0.7152, 0.0722 );","uniform float brightness;","uniform float whitePoint;","#ifdef TONEMAP_UNCHARTED","const float A = 0.15;","const float B = 0.50;","const float C = 0.10;","const float D = 0.20;","const float E = 0.02;","const float F = 0.30;","const float W = 11.2;","vec3 Uncharted2Tonemap( vec3 x ) {","return ( ( x * ( A * x + C * B ) + D * E ) / ( x * ( A * x + B ) + D * F ) ) - E / F;","}","#endif","vec3 applyTonemapping( vec3 inColor, float inBrightness, float inWhitePoint ) {","vec3 outColor = inColor * inBrightness;","#if defined( TONEMAP_SIMPLE )","outColor = sqrt( outColor );","#elif defined( TONEMAP_LINEAR )","outColor = pow( outColor, GAMMA );","#elif defined( TONEMAP_REINHARD )","outColor = outColor / ( 1.0 + outColor );","outColor = pow( outColor, GAMMA );","#elif defined( TONEMAP_REINHARD_LUMA )","float luma = dot( outColor, LUMA );","float toneMappedLuma = luma / ( 1.0 + luma );","outColor *= toneMappedLuma / luma;","outColor = pow( outColor, GAMMA );","#elif defined( TONEMAP_REINHARD_WHITE )","float white = 2.0 * inWhitePoint;","float luma = dot( outColor, LUMA );","float toneMappedLuma = luma * ( 1.0 + luma / ( white * white ) ) / ( 1.0 + luma );","outColor *= toneMappedLuma / luma;","outColor = pow( outColor, GAMMA );","#elif defined( TONEMAP_FILMIC )","vec3 x = max( vec3( 0.0 ), outColor - 0.004 );","outColor = ( x * ( 6.2 * x + 0.5 ) ) / ( x * ( 6.2 * x + 1.7 ) + 0.06 );","#elif defined( TONEMAP_FILMIC_2015 )","vec4 vh = vec4( outColor, inWhitePoint );","vec4 va = ( 1.425 * vh ) + 0.05;","vec4 vf = ( ( vh * va + 0.004 ) / ( ( vh * ( va + 0.55 ) + 0.0491 ) ) ) - 0.0821;","outColor = vf.rgb / vf.www;","outColor = pow( outColor, GAMMA );","#elif defined( TONEMAP_PHOTOGRAPHIC )","const float exposureBias = 3.0;","const float saturationBias = 1.3;","outColor = 1.0 - exp2( -exposureBias * outColor );","outColor = pow( outColor, vec3( saturationBias / 2.2 ) );","#elif defined( TONEMAP_UNCHARTED )","float exposureBias = 2.0;","vec3 curr = Uncharted2Tonemap( exposureBias * outColor );","float white = W * inWhitePoint;","vec3 whiteScale = vec3( 1.0 ) / Uncharted2Tonemap( vec3( white ) );","vec3 color = curr * whiteScale;","outColor = pow( color, GAMMA );","#endif","return outColor;","}","#endif"].join("\n"),XG.ShaderChunk.ditheringFragmentPars=["#ifdef DITHERING_ENABLED","float nrand( vec2 n ) {","return fract( sin( dot( n.xy, vec2( 12.9898, 78.233 ) ) ) * 43758.5453 );","}","vec3 applyDithering( vec3 inColor, vec2 rndSeed ) {","float rnd = nrand( rndSeed ) - 0.5;","inColor.rgb += rnd/255.0;","return inColor;","}","#endif"].join("\n"),XG.ShaderChunk.vertexShaderFullscreenTriangle=["void main() {","gl_Position = vec4( position.xyz, 1.0 );","}"].join("\n"),XG.ShaderChunk.vertexShaderFullscreenTriangleUV=["varying vec2 vUv;","void main() {","vUv = uv;","gl_Position = vec4( position.xyz, 1.0 );","}"].join("\n"),XG.ShaderChunk.vertexShaderGeometry=["void main() { ","vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );","gl_Position = projectionMatrix * mvPosition;","}"].join("\n"),XG.ShaderChunk.fog_pars_fragment=["#ifdef USE_FOG","uniform vec3 fogColor;","#if defined( EXPONENTIAL_FOG )","uniform float fogDensity;","#elif defined( LINEAR_FOG )","uniform vec2 fogNearFar;","#elif defined( ATMOSPHERIC_FOG )","uniform vec2 fogStartStrength;","#endif","#endif"].join("\n"),XG.ShaderChunk.fog_fragment=["#ifdef USE_FOG","float depth = gl_FragCoord.z / gl_FragCoord.w;","float fogFactor = 0.0;","#if defined( EXPONENTIAL_FOG )","const float LOG2 = 1.442695;","fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );","fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );","#elif defined( LINEAR_FOG )","fogFactor = smoothstep( fogNearFar.x, fogNearFar.y, depth );","#elif defined( ATMOSPHERIC_FOG )","float linearDepth = linearizeDepth( vClipPosition.z / vClipPosition.w, cameraNearFar );","fogFactor = linearDepth / ( cameraNearFar.y - cameraNearFar.x );","fogFactor *= smoothstep( 0.0, fogStartStrength.x, linearDepth );","fogFactor = clamp( fogFactor, 0.0, fogStartStrength.y );","#endif","mgl_FragColor = mix( mgl_FragColor, vec4( fogColor, mgl_FragColor.w ), fogFactor );","#endif"].join("\n"),XG.ShaderChunk.height_fog_pars_fragment=["#ifdef USE_HEIGHT_FOG","uniform float fogHeight;","uniform float fogVisibilityDistance;","uniform float fogFadeSpeed;","uniform vec3 fogShallowDepthColor;","uniform vec3 fogDeepDepthColor;","uniform vec3 fogRgbExtinctionDistance;","#endif"].join("\n"),XG.ShaderChunk.height_fog_fragment=["#ifdef USE_HEIGHT_FOG","vec3 u = vertexPositionWS.xyz - cameraPosition;","vec3 w = cameraPosition - vec3( 0.0, fogHeight, 0.0 );","vec3 n = vec3( 0.0, 1.0, 0.0 );","float D = dot( n, u );","float N = -dot( n, w );","float sI = N / D;","vec3 intersectionPosition = cameraPosition + sI * u;","float fogThickness = length( intersectionPosition - vertexPositionWS.xyz );","if ( vertexPositionWS.y > fogHeight ) {","fogThickness = 0.0;","}","float fogThickness2 = intersectionPosition.y - vertexPositionWS.y;","if ( cameraPosition.y < fogHeight ) {","}","float r1 = clamp( fogFadeSpeed * fogThickness / fogVisibilityDistance, 0.0, 1.0 );","vec3 r2 = clamp( fogThickness2 / fogRgbExtinctionDistance, 0.0, 1.0 );","mgl_FragColor.xyz = mix( mix( mgl_FragColor.xyz, fogShallowDepthColor * globalLightFactor, r1 ), fogDeepDepthColor * globalLightFactor, r2 );","#endif"].join("\n"),XG.ShaderChunk.worldpos_vertex=["#if defined( USE_SHADOWMAP )","vec4 worldPosition = modelMatrix * transformedPosition;","#endif"].join("\n"),XG.ShaderChunk.area_lights_utils=["#if MAX_AREA_LIGHTS > 0","vec3 projectOnPlane( vec3 point, vec3 planeCenter, vec3 planeNorm ) {","return point - dot( point - planeCenter, planeNorm ) * planeNorm;","}","bool sideOfPlane( vec3 point, vec3 planeCenter, vec3 planeNorm ) {","return ( dot( point - planeCenter, planeNorm ) >= 0.0 );","}","vec3 linePlaneIntersect( vec3 lp, vec3 lv, vec3 pc, vec3 pn ) {","return lp + lv * ( dot( pn, pc - lp ) / dot( pn, lv ) );","}","float calculateAttenuation( float dist, float constantAttenuation, float linearAttenuation, float quadraticAttenuation ) {","return ( 1.0 / ( constantAttenuation + linearAttenuation * dist + quadraticAttenuation * dist * dist ) );","}","#endif"].join("\n"),XG.ShaderChunk.lights_phong_pars_fragment=["#if MAX_DIR_LIGHTS > 0","uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];","uniform vec3 directionalLightDirectionVS[ MAX_DIR_LIGHTS ];","uniform int directionalLightPars[ MAX_DIR_LIGHTS ];","#endif","#if MAX_HEMI_LIGHTS > 0","uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];","uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];","uniform vec3 hemisphereLightDirectionVS[ MAX_HEMI_LIGHTS ];","#endif","#if MAX_POINT_LIGHTS > 0","uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];","uniform vec3 pointLightPositionVS[ MAX_POINT_LIGHTS ];","uniform float pointLightDistance[ MAX_POINT_LIGHTS ];","#endif","#if MAX_SPHERE_LIGHTS > 0","uniform vec3 sphereLightColor[ MAX_SPHERE_LIGHTS ];","uniform vec3 sphereLightPositionVS[ MAX_SPHERE_LIGHTS ];","uniform vec3 sphereLightPars[ MAX_SPHERE_LIGHTS ];","#endif","#if MAX_TUBE_LIGHTS > 0","uniform vec3 tubeLightColor[ MAX_TUBE_LIGHTS ];","uniform vec3 tubeLightPosition0VS[ MAX_TUBE_LIGHTS ];","uniform vec3 tubeLightPosition1VS[ MAX_TUBE_LIGHTS ];","uniform vec2 tubeLightPars[ MAX_TUBE_LIGHTS ];","#endif","#if MAX_SPOT_LIGHTS > 0","uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];","uniform vec3 spotLightPositionVS[ MAX_SPOT_LIGHTS ];","uniform vec3 spotLightDirectionVS[ MAX_SPOT_LIGHTS ];","uniform vec4 spotLightPars[ MAX_SPOT_LIGHTS ];","#endif","#if MAX_AREA_LIGHTS > 0","uniform vec3 areaLightColor[ MAX_AREA_LIGHTS ];","uniform vec3 areaLightPosition[ MAX_AREA_LIGHTS ];","uniform vec3 areaLightNormal[ MAX_AREA_LIGHTS ];","uniform vec3 areaLightRight[ MAX_AREA_LIGHTS ];","uniform vec3 areaLightUp[ MAX_AREA_LIGHTS ];","uniform vec4 areaLightPars[ MAX_AREA_LIGHTS ];","uniform vec3 areaLightAttenuation[ MAX_AREA_LIGHTS ];","#ifdef AREA_TEXTURE","uniform sampler2D areaLightTexture[ MAX_AREA_LIGHTS ];","#endif","#endif","#if MAX_IMAGE_LIGHTS > 0","#if !defined( SUPPORTS_TEXTURE_LOD )","uniform samplerCube imageLightTextureMip[ MAX_IMAGE_LIGHTS ];","#endif","uniform samplerCube imageLightTextureDiffuse[ MAX_IMAGE_LIGHTS ];","uniform samplerCube imageLightTextureSpecular[ MAX_IMAGE_LIGHTS ];","uniform vec3 imageLightPars[ MAX_IMAGE_LIGHTS ];","uniform vec3 imageLightPositionWS[ MAX_IMAGE_LIGHTS ];","uniform vec3 imageLightSize[ MAX_IMAGE_LIGHTS ];","#endif","#if MAX_IMAGE_LIGHTS > 0 || defined( USE_HEIGHT_FOG )","uniform mat4 viewInverseMatrix;","#endif","#if MAX_IMAGE_LIGHTS > 0 || MAX_HEMI_LIGHTS > 0","vec3 EnvironmentBRDF( float gloss, float dotNV, vec3 rf0 ) {","vec4 t = vec4( 1.0 / 0.96, 0.475, ( 0.0275 - 0.25 * 0.04 ) / 0.96, 0.25 );","t *= vec4( gloss );","t += vec4( 0.0, 0.0, ( 0.015 - 0.75 * 0.04 ) / 0.96, 0.75 );","float a0 = t.x * min( t.y, exp2( -9.28 * dotNV ) ) + t.z;","float a1 = t.w;","return clamp( a0 + rf0 * ( a1 - a0 ), 0.0, 1.0 );","}","#endif","#ifdef WRAP_AROUND","uniform vec3 wrapRGB;","#endif","float SmithGeometryFactor1( vec3 L, vec3 V, vec3 N, float shininess ) {","vec3 H = L + V;","float dotVN = dot( V, N );","float dotVH = dot( V, H );","if ( ( dotVH / dotVN ) <= 0.0 ) return 0.0;","float f = acos( dotVN );","float a = sqrt( 0.5 * shininess + 1.0 ) / tan( f );","float G = 1.0;","if ( a < 1.6 )","G = ( 3.535 * a + 2.181 * a * a ) / ( 1.0 + 2.276 * a + 2.577 * a * a );","return G;","}","float SmithGeometryFactor2( float dotLN, vec3 V, vec3 N, float shininess ) {","float dotNV = max( dot( N, V ), 0.0 );","float a = 1.0 / ( sqrt( 0.7854 * shininess + 1.571 ) );","return 1.0 / ( ( dotLN * ( 1.0 - a ) + a ) * ( dotNV * ( 1.0 - a ) + a ) );","}","float KelemenGeometryFactor( float dotLH ) {","return 1.0 / ( dotLH * dotLH );","}","float GGX_SchlickGeometryFactor_V1( in float k, in float dotNX ) {","return dotNX / ( dotNX * ( 1.0 - k ) + k );","}","float GGX_SchlickGeometryFactor_V2( in float k, in float dotNX ) {","return 1.0 / ( dotNX + sqrt( k + ( 1.0 - k ) * dotNX * dotNX ) );","}","float GGX_Specular( in float m, in vec3 n, in vec3 h, in vec3 v, in vec3 l ) {","float nDotH = saturate( dot( n, h ) );","float nDotL = saturate( dot( n, l ) );","float nDotV = saturate( dot( n, v ) );","float nDotH2 = nDotH * nDotH;","float m2 = pow( m, 4.0 );","float d = m2 / ( pow( nDotH * nDotH * ( m2 - 1.0 ) + 1.0, 2.0 ) );","float v1i = GGX_SchlickGeometryFactor_V2( m2, nDotL );","float v1o = GGX_SchlickGeometryFactor_V2( m2, nDotV );","float vis = v1i * v1o;","return d * vis;","}","float BlinnPhong_Specular( in float shininess, in float dotLN, in float dotNormalHalf, in vec3 eyeVector, in vec3 normal ) {","float geo = SmithGeometryFactor2( dotLN, eyeVector, normal, shininess );","return geo * max( pow( dotNormalHalf, shininess ), 0.0 );","}","varying vec3 vViewPosition;","varying vec3 vNormal;"].join("\n"),XG.ShaderChunk.lights_phong_fragment=["#ifdef DOUBLE_SIDED","normal *= ( 2.0 * float( gl_FrontFacing ) - 1.0 );","#endif","#if defined( USE_DISPLACEMENTMAP )","normal = perturbNormalArb( vViewPosition, normal, dHdxy_fwd( displacementMap, uvCoord, displacementNormalScale ) );","#endif","#if defined( USE_NORMALMAP ) || defined( USE_NORMALGLOSSMAP )","vec4 normalGlossMap = texture2D( normalMap, uvCoord );","#endif","#if defined( USE_NORMALMAP ) || defined( USE_NORMALGLOSSMAP )","normal = perturbNormal2Arb( vViewPosition, normal, normalGlossMap.xyz, uvCoord );","#elif defined( USE_BUMPMAP )","normal = perturbNormalArb( vViewPosition, normal, dHdxy_fwd( bumpMap, uvCoord, bumpScale ) );","#endif","#ifdef USE_BUMPDETAILMAP","normal = perturbNormalArb( vViewPosition, normal, dHdxy_fwd( bumpDetailMap, uvCoord * detailRepeatScale.xy, detailRepeatScale.z ) );","#endif","#if defined( USE_GLOSSMAP )","vec4 glossMap = texture2D( glossMap, uvCoord );","float glossMapValue = exp2( 13.0 * glossMap.x + 1.0 );","#elif defined( USE_NORMALGLOSSMAP )","float glossMapValue = exp2( 13.0 * normalGlossMap.a + 1.0 );","#else","float glossMapValue = 1.0;","#endif","vec3 globalLightFactor = vec3( 0.0 );","#if MAX_IMAGE_LIGHTS > 0 || defined( USE_HEIGHT_FOG )","vec4 vertexPositionWS = viewInverseMatrix * vec4( vertexPosition, 1.0 );","#endif","float shininess = glossMapValue * specular.a;","float specularNormalization = shininess * 0.125 + 0.25;","vec3 specularColor = specular.rgb * specularMapColor;","const float maxShininess = 8192.0;","float gloss = clamp( shininess / maxShininess, 0.0, 1.0 );","float roughness = saturate( sqrt( 8.0 / ( shininess + 7.0 ) ) );","#if defined( WRAP_AROUND ) && defined( WRAP_AROUND_SKIN )","float curvature = length( fwidth( vNormal.xyz ) ) / length( fwidth( vertexPosition.xyz ) );","#endif","#if MAX_POINT_LIGHTS > 0","vec3 pointDiffuse  = vec3( 0.0 );","vec3 pointSpecular = vec3( 0.0 );","for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {","vec3 lightPosition = pointLightPositionVS[ i ];","vec3 lightVector = lightPosition - vViewPosition;","float lightDistance = length( lightVector );","float attenuation = 1.0;","if ( pointLightDistance[ i ] > 0.0 ) {","float cutoff = 0.3;","float denom = lightDistance / pointLightDistance[ i ] + 1.0;","attenuation = 1.0 / ( denom * denom );","attenuation = ( attenuation - cutoff ) / ( 1.0 - cutoff );","attenuation = max( attenuation, 0.0 );","attenuation *= attenuation;","}","lightVector = lightVector / lightDistance;","float dotLNUnclamped = dot( normal, lightVector );","float dotLN = max( dotLNUnclamped, 0.0 );","#ifdef WRAP_AROUND","#ifdef WRAP_AROUND_SKIN","vec3 pointDiffuseWeight = PSSFitFunction( dot( vNormal, lightVector ), curvature );","#else","float pointDiffuseWeightFull = dotLN;","float pointDiffuseWeightHalf = max( 0.25 * dotLNUnclamped + 0.25, 0.0 );","vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );","#endif","#else","float pointDiffuseWeight = dotLN;","#endif","pointDiffuseWeight *= attenuation;","vec3 diffuseTerm = ( diffuse.rgb * pointLightColor[ i ] ) * pointDiffuseWeight;","vec3 pointHalfVector = normalize( lightVector + eyeVector );","float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );","#ifdef PHYSICALLY_BASED_SHADING","float dotLH = max( dot( lightVector, pointHalfVector ), 0.0 );","vec3 fresnel = specularColor + ( 1.0 - specularColor ) * pow( 1.0 - dotLH, 5.0 );","#if defined( BRDF_BLINN_PHONG )","pointSpecular += attenuation * specularNormalization * BlinnPhong_Specular( shininess, dotLN, pointDotNormalHalf, eyeVector, normal ) * ( fresnel * dotLN ) * pointLightColor[ i ];","#elif defined( BRDF_GGX )","pointSpecular += attenuation * GGX_Specular( roughness, normal, pointHalfVector, eyeVector, lightVector ) * ( fresnel * dotLN ) * pointLightColor[ i ];","#endif","#else","float pointSpecularWeight = max( pow( pointDotNormalHalf, shininess ), 0.0 );","pointSpecular += attenuation * ( pointSpecularWeight * dotLN ) * ( specularColor * pointLightColor[ i ] );","#endif","#ifdef PHYSICALLY_BASED_SHADING","pointDiffuse  += ( 1.0 - fresnel ) * diffuseTerm;","#else","pointDiffuse  += diffuseTerm;","#endif","globalLightFactor += pointLightColor[ i ] * attenuation;","}","#endif","#if MAX_SPHERE_LIGHTS > 0","vec3 sphereDiffuse  = vec3( 0.0 );","vec3 sphereSpecular = vec3( 0.0 );","for ( int i = 0; i < MAX_SPHERE_LIGHTS; i ++ ) {","vec3 lightPosition = sphereLightPositionVS[ i ];","vec3 lightVectorFull = lightPosition - vViewPosition;","float lightDistance = length( lightVectorFull );","float attenuation = 1.0;","float maxDistance = sphereLightPars[ i ].x;","float lightRadius = sphereLightPars[ i ].y;","if ( maxDistance > 0.0 ) {","float cutoff = 0.3;","float denom = lightDistance / maxDistance + 1.0;","attenuation = 1.0 / ( denom * denom );","attenuation = ( attenuation - cutoff ) / ( 1.0 - cutoff );","attenuation = max( attenuation, 0.0 );","attenuation *= attenuation;","}","vec3 lightVector = lightVectorFull / lightDistance;","float dotLNUnclamped = dot( normal, lightVector );","float dotLN = max( dotLNUnclamped, 0.0 );","#ifdef WRAP_AROUND","#ifdef WRAP_AROUND_SKIN","vec3 sphereDiffuseWeight = PSSFitFunction( dot( vNormal, lightVector ), curvature );","#else","float sphereDiffuseWeightFull = dotLN;","float sphereDiffuseWeightHalf = max( 0.25 * dotLNUnclamped + 0.25, 0.0 );","vec3 sphereDiffuseWeight = mix( vec3( sphereDiffuseWeightFull ), vec3( sphereDiffuseWeightHalf ), wrapRGB );","#endif","#else","float sphereDiffuseWeight = dotLN;","#endif","sphereDiffuseWeight *= attenuation;","vec3 diffuseTerm = ( diffuse.rgb * sphereLightColor[ i ] ) * sphereDiffuseWeight;","vec3 specularTerm;","vec3 reflectVS1 = reflect( eyeVector, normal );","vec3 centerToRay = lightVectorFull - dot( lightVectorFull, reflectVS1 ) * reflectVS1;","vec3 closestPoint = lightVectorFull - centerToRay * saturate( lightRadius / length( centerToRay ) );","lightVector = normalize( closestPoint );","dotLN = max( dot( lightVector, normal ), 0.0 );","float alpha = roughness * roughness;","float alphaPrime = saturate( alpha + 0.5 * saturate( lightRadius / lightDistance ) );","float sphereNormalization = alpha / alphaPrime;","sphereNormalization *= sphereNormalization;","vec3 sphereHalfVector = normalize( lightVector + eyeVector );","float sphereDotNormalHalf = max( dot( normal, sphereHalfVector ), 0.0 );","#ifdef PHYSICALLY_BASED_SHADING","float dotLH = max( dot( lightVector, sphereHalfVector ), 0.0 );","vec3 fresnel = specularColor + ( 1.0 - specularColor ) * pow( 1.0 - dotLH, 5.0 );","#if defined( BRDF_BLINN_PHONG )","specularTerm = sphereNormalization * attenuation * BlinnPhong_Specular( shininess, dotLN, sphereDotNormalHalf, eyeVector, normal ) * ( fresnel * dotLN ) * sphereLightColor[ i ];","#elif defined( BRDF_GGX )","specularTerm = sphereNormalization * attenuation * GGX_Specular( roughness, normal, sphereHalfVector, eyeVector, lightVector ) * ( fresnel * dotLN ) * sphereLightColor[ i ];","#endif","#else","float sphereSpecularWeight = max( pow( sphereDotNormalHalf, shininess ), 0.0 );","specularTerm = attenuation * ( sphereSpecularWeight * dotLN ) * ( specularColor * sphereLightColor[ i ] );","#endif","#ifdef USE_SHADOWMAP","int shadowIndex = int( sphereLightPars[ i ].z );","if ( ( i + SPHERE_INDEX_OFFSET ) == shadowIndex ) {","diffuseTerm  *= occlusion[ i ];","specularTerm *= occlusion[ i ];","}","#endif","sphereSpecular += specularTerm;","#ifdef PHYSICALLY_BASED_SHADING","sphereDiffuse  += ( 1.0 - fresnel ) * diffuseTerm;","#else","sphereDiffuse  += diffuseTerm;","#endif","globalLightFactor += sphereLightColor[ i ] * attenuation;","}","#endif","#if MAX_TUBE_LIGHTS > 0","vec3 tubeDiffuse  = vec3( 0.0 );","vec3 tubeSpecular = vec3( 0.0 );","for ( int i = 0; i < MAX_TUBE_LIGHTS; i ++ ) {","vec3 lightPosition0 = tubeLightPosition0VS[ i ];","vec3 lightPosition1 = tubeLightPosition1VS[ i ];","float attenuation = 1.0;","float maxDistance = tubeLightPars[ i ].x;","float lightRadius = tubeLightPars[ i ].y;","vec3 lightVector0 = lightPosition0 - vertexPosition;","vec3 lightVector1 = lightPosition1 - vertexPosition;","float length0 = length( lightVector0 );","float length1 = length( lightVector1 );","float a = saturate( 0.5 * ( dot( normal, lightVector0 ) / length0 + dot( normal, lightVector1 ) / length1 ) );","float b = ( length0 * length1 + dot( lightVector0, lightVector1 ) ) * 0.5 + 1.0;","float dotLN = a;","vec3 tubeDiffuseWeight = vec3( dotLN );","vec3 diffuseTerm = ( diffuse.rgb * tubeLightColor[ i ] ) * tubeDiffuseWeight;","vec3 reflectVS1 = reflect( eyeVector, normal );","vec3 lightVectorD = lightVector1 - lightVector0;","float lengthD = length( lightVectorD );","float dotRD = dot( reflectVS1, lightVectorD );","float ta = dot( reflectVS1, lightVector0 ) * dotRD - dot( lightVector0, lightVectorD );","float tb = lengthD * lengthD - dotRD * dotRD;","float t = ta / tb;","vec3 closestPoint = lightVector0 + saturate( t ) * lightVectorD;","vec3 lightVectorClosest = closestPoint;","vec3 centerToRay = lightVectorClosest - dot( lightVectorClosest, reflectVS1 ) * reflectVS1;","closestPoint = lightVectorClosest - centerToRay * saturate( lightRadius / length( centerToRay ) );","vec3 lightVector = normalize( closestPoint );","vec3 lightVectorFull = ( lightPosition0 + lightPosition1 ) * 0.5 - vertexPosition.xyz;","float distance = length( lightVectorFull );","float alpha = roughness * roughness;","float alphaPrime = saturate( alpha + 0.5 * saturate( lightRadius / distance ) );","float sphereNormalization = alpha / alphaPrime;","sphereNormalization *= sphereNormalization;","float alphaPrimeLine = saturate( alpha + 0.5 * saturate( lengthD / distance ) );","float lineNormalization = alpha / alphaPrimeLine;","float tubeNormalization = sphereNormalization * lineNormalization;","if ( maxDistance > 0.0 ) {","attenuation = 1.0 / b;","}","vec3 sphereHalfVector = normalize( lightVector + eyeVector );","float sphereDotNormalHalf = max( dot( normal, sphereHalfVector ), 0.0 );","#ifdef PHYSICALLY_BASED_SHADING","float dotLH = max( dot( lightVector, sphereHalfVector ), 0.0 );","vec3 fresnel = specularColor + ( 1.0 - specularColor ) * pow( 1.0 - dotLH, 5.0 );","#if defined( BRDF_BLINN_PHONG )","tubeSpecular += tubeNormalization * attenuation * BlinnPhong_Specular( shininess, dotLN, sphereDotNormalHalf, eyeVector, normal ) * ( fresnel * dotLN ) * tubeLightColor[ i ];","#elif defined( BRDF_GGX )","tubeSpecular += tubeNormalization * attenuation * GGX_Specular( roughness, normal, sphereHalfVector, eyeVector, lightVector ) * ( fresnel * dotLN ) * tubeLightColor[ i ];","#endif","#else","float sphereSpecularWeight = max( pow( sphereDotNormalHalf, shininess ), 0.0 );","sphereSpecular += attenuation * ( sphereSpecularWeight * dotLN ) * ( specularColor * sphereLightColor[ i ] );","#endif","#ifdef PHYSICALLY_BASED_SHADING","tubeDiffuse  += ( 1.0 - fresnel ) * diffuseTerm * attenuation;","#else","tubeDiffuse  += diffuseTerm * attenuation;","#endif","globalLightFactor += tubeLightColor[ i ] * attenuation;","}","#endif","#if MAX_SPOT_LIGHTS > 0","vec3 spotDiffuse  = vec3( 0.0 );","vec3 spotSpecular = vec3( 0.0 );","for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {","vec3 lightPosition = spotLightPositionVS[ i ];","vec3 lightVector = lightPosition - vViewPosition;","float lightDistance = length( lightVector );","float spotLightAngleCos = spotLightPars[ i ].x;","float spotLightExponent = spotLightPars[ i ].y;","float spotLightDistance = spotLightPars[ i ].z;","float attenuation = 1.0;","if ( spotLightDistance > 0.0 )","attenuation = 1.0 - min( lightDistance / spotLightDistance, 1.0 );","lightVector = lightVector / lightDistance;","float rho = dot( spotLightDirectionVS[ i ], lightVector );","if ( rho > spotLightAngleCos ) {;","float theta = spotLightAngleCos + 0.0001;","float phi = spotLightAngleCos + 0.05;","const float falloff = 4.0;","float spotEffect = 0.0;","if ( rho >= phi ) {","spotEffect = 1.0;","} else if ( rho <= theta ) {","spotEffect = 0.0;","} else { ","spotEffect = pow( ( rho - theta ) / ( phi - theta ), falloff );","}","attenuation *= spotEffect;","float dotLNUnclamped = dot( normal, lightVector );","float dotLN = max( dotLNUnclamped, 0.0 );","#ifdef WRAP_AROUND","#ifdef WRAP_AROUND_SKIN","vec3 spotDiffuseWeight = PSSFitFunction( dot( vNormal, lightVector ), curvature );","#else","float spotDiffuseWeightFull = dotLN;","float spotDiffuseWeightHalf = max( 0.25 * dotLNUnclamped + 0.25, 0.0 );","vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );","#endif","#else","float spotDiffuseWeight = dotLN;","#endif","spotDiffuseWeight *= attenuation;","vec3 diffuseTerm = spotDiffuseWeight * ( diffuse.rgb * spotLightColor[ i ] );","vec3 spotHalfVector = normalize( lightVector + eyeVector );","float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );","#ifdef PHYSICALLY_BASED_SHADING","float dotLH = max( dot( lightVector, spotHalfVector ), 0.0 );","vec3 fresnel = specularColor + ( 1.0 - specularColor ) * pow( 1.0 - dotLH, 5.0 );","#if defined( BRDF_BLINN_PHONG )","vec3 specularTerm = attenuation * specularNormalization * BlinnPhong_Specular( shininess, dotLN, spotDotNormalHalf, eyeVector, normal ) * ( fresnel * dotLN ) * spotLightColor[ i ];","#elif defined( BRDF_GGX )","vec3 specularTerm = attenuation * GGX_Specular( roughness, normal, spotHalfVector, eyeVector, lightVector ) * ( fresnel * dotLN ) * spotLightColor[ i ];","#endif","#else","float spotSpecularWeight = max( pow( spotDotNormalHalf, shininess ), 0.0 );","vec3 specularTerm = attenuation * ( spotSpecularWeight * dotLN ) * ( specularColor * spotLightColor[ i ] );","#endif","#ifdef USE_SHADOWMAP","int shadowIndex = int( spotLightPars[ i ].w );","if ( ( i + SPOT_INDEX_OFFSET ) == shadowIndex ) {","diffuseTerm  *= occlusion[ i ];","specularTerm *= occlusion[ i ];","}","#endif","#ifdef PHYSICALLY_BASED_SHADING","spotDiffuse  += ( 1.0 - fresnel ) * diffuseTerm;","#else","spotDiffuse  += diffuseTerm;","#endif","spotSpecular += specularTerm;","globalLightFactor += spotLightColor[ i ] * attenuation;","}","}","#endif","#if MAX_DIR_LIGHTS > 0","vec3 dirDiffuse  = vec3( 0.0 );","vec3 dirSpecular = vec3( 0.0 );","for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {","vec3 lightDirection = directionalLightDirectionVS[ i ];","vec3 lightVector = normalize( lightDirection );","float dotLNUnclamped = dot( normal, lightVector );","float dotLN = max( dotLNUnclamped, 0.0 );","#ifdef WRAP_AROUND","#ifdef WRAP_AROUND_SKIN","vec3 dirDiffuseWeight = PSSFitFunction( dot( vNormal, lightVector ), curvature );","#else","float dirDiffuseWeightFull = dotLN;","float dirDiffuseWeightHalf = max( 0.25 * dotLNUnclamped + 0.25, 0.0 );","vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );","#endif","#else","float dirDiffuseWeight = dotLN;","#endif","vec3 diffuseTerm = diffuse.rgb * directionalLightColor[ i ] * dirDiffuseWeight;","vec3 dirHalfVector = normalize( lightVector + eyeVector );","float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );","#ifdef PHYSICALLY_BASED_SHADING","float dotLH = max( dot( lightVector, dirHalfVector ), 0.0 );","vec3 fresnel = specularColor + ( 1.0 - specularColor ) * pow( 1.0 - dotLH, 5.0 );","#if defined( BRDF_BLINN_PHONG )","vec3 specularTerm = specularNormalization * BlinnPhong_Specular( shininess, dotLN, dirDotNormalHalf, eyeVector, normal ) * ( fresnel * dotLN ) * directionalLightColor[ i ];","#elif defined( BRDF_GGX )","vec3 specularTerm = GGX_Specular( roughness, normal, dirHalfVector, eyeVector, lightVector ) * ( fresnel * dotLN ) * directionalLightColor[ i ];","#endif","#else","float dirSpecularWeight = max( pow( dirDotNormalHalf, shininess ), 0.0 );","vec3 specularTerm = ( dirSpecularWeight * dotLN ) * ( specularColor * directionalLightColor[ i ] );","#endif","#ifdef USE_SHADOWMAP","int shadowIndex = directionalLightPars[ i ];","if ( ( i + DIR_INDEX_OFFSET ) == shadowIndex ) {","diffuseTerm  *= occlusion[ i ];","specularTerm *= occlusion[ i ];","}","#endif","#ifdef PHYSICALLY_BASED_SHADING","dirDiffuse  += ( 1.0 - fresnel ) * diffuseTerm;","#else","dirDiffuse  += diffuseTerm;","#endif","dirSpecular += specularTerm;","globalLightFactor += directionalLightColor[ i ];","}","#endif","#if MAX_HEMI_LIGHTS > 0","vec3 hemiDiffuse  = vec3( 0.0 );","vec3 hemiSpecular = vec3( 0.0 );","for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {","vec3 lightDirection = hemisphereLightDirectionVS[ i ];","vec3 lightVector = normalize( lightDirection.xyz );","vec3 halfVector = normalize( lightVector + eyeVector );","vec3 fresnelHemi = EnvironmentBRDF( gloss, dot( eyeVector, halfVector ), specularColor );","float dotProductHemi = dot( normal, lightVector );","float hemiDiffuseWeightUnclamped = 0.5 * dotProductHemi;","float hemiDiffuseWeight = clamp( hemiDiffuseWeightUnclamped, 0.0, 1.0 );","#ifdef WRAP_AROUND","float hemiDiffuseWeightUnclamped2 = -0.5 * dotProductHemi + 0.5;","float hemiDiffuseWeight2 = clamp( hemiDiffuseWeightUnclamped2, 0.0, 1.0 );","vec3 diffuseHemi = 0.75 * mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight ) + 0.25 * mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight2 );","#else","vec3 diffuseHemi = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );","#endif","diffuseHemi *= ( 1.0 - fresnelHemi );","vec3 R = reflect( -eyeVector, normal );","R = normalize( R );","float hemiSpecularWeight = clamp( dot( R, lightVector ) * 0.5 + 0.5, 0.0, 1.0 );","vec3 specularHemi = fresnelHemi * mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiSpecularWeight );","hemiDiffuse += diffuse.rgb * diffuseHemi;","hemiSpecular += specularHemi;","globalLightFactor += hemisphereLightSkyColor[ i ];","}","#endif","#if MAX_AREA_LIGHTS > 0","vec3 areaDiffuse  = vec3( 0.0 );","vec3 areaSpecular = vec3( 0.0 );","for( int i = 0; i < MAX_AREA_LIGHTS; i ++ ) {","float w = areaLightPars[ i ].x;","float h = areaLightPars[ i ].y;","vec3 proj = projectOnPlane( vertexPosition, areaLightPosition[ i ], areaLightNormal[ i ] );","vec3 dir = proj - areaLightPosition[ i ];","vec2 diagonal = vec2( dot( dir, areaLightRight[ i ] ), dot( dir, areaLightUp[ i ] ) );","vec2 nearest2D = vec2( clamp( diagonal.x, -w, w ), clamp( diagonal.y, -h, h ) );","vec3 nearestPointInside = areaLightPosition[ i ] + ( areaLightRight[ i ] * nearest2D.x + areaLightUp[ i ] * nearest2D.y );","vec3 lightDir = normalize( nearestPointInside - vertexPosition );","float NdotL = max( dot( areaLightNormal[ i ], -lightDir ), 0.0 );","float NdotL2 = max( dot( normal, lightDir ), 0.0 );","float dotLN = sqrt( NdotL * NdotL2 );","vec3 areaDiffuseWeight = vec3( dotLN );","#ifdef WRAP_AROUND","if ( NdotL > 0.0 ) {","#ifdef WRAP_AROUND_SKIN","areaDiffuseWeight = PSSFitFunction( sqrt( NdotL * dot( vNormal, lightDir ) ), curvature );","#else","float dotLNHalf = max( 0.25 * dotLN + 0.25, 0.0 );","areaDiffuseWeight = mix( areaDiffuseWeight, vec3( dotLNHalf ), wrapRGB );","#endif","}","#endif","float dist = distance( vertexPosition, nearestPointInside );","float attenuation = calculateAttenuation( dist, areaLightAttenuation[ i ].x, areaLightAttenuation[ i ].y, areaLightAttenuation[ i ].z );","areaDiffuseWeight *= attenuation;","vec3 areaDiffuseTerm = areaDiffuseWeight * ( diffuse.rgb * areaLightColor[ i ] );","#ifdef AREA_TEXTURE","if ( areaLightPars[ i ].z > 0.0 ) {","float d = distance( vertexPosition, nearestPointInside );","vec2 co = ( diagonal.xy + vec2( w, h ) ) / ( 2.0 * vec2( w, h ) );","co.y = 1.0 - co.y;","vec3 ve = vertexPosition - areaLightPosition[ i ];","vec4 diff = vec4( 0.0 );","if ( dot( ve, areaLightNormal[ i ] ) < 0.0 ) {","diff = vec4( 0.0 );","} else {","float lod = max( pow( d, 0.1 ), 0.0 ) * 5.0;","vec4 t00 = texture2D( areaLightTexture[ i ], co, lod );","vec4 t01 = texture2D( areaLightTexture[ i ], co, lod + 1.0 );","diff = mix( t00, t01, 0.5 );","}","areaDiffuseTerm *= diff.xyz;","}","#endif","vec3 areaSpecularTerm = vec3( 0.0 );","vec3 fresnel = vec3( 0.0 );","vec3 R = reflect( eyeVector, normal );","vec3 E = linePlaneIntersect( vertexPosition, R, areaLightPosition[ i ], areaLightNormal[ i ] );","float specAngle = dot( R, areaLightNormal[ i ] );","if ( dot( vertexPosition - areaLightPosition[ i ], areaLightNormal[ i ] ) >= 0.0 && specAngle > 0.0 ) {","vec3 dirSpec = E - areaLightPosition[ i ];","vec2 dirSpec2D = vec2( dot( dirSpec, areaLightRight[ i ] ), dot( dirSpec, areaLightUp[ i ] ) );","vec2 nearestSpec2D = vec2( clamp( dirSpec2D.x, -w, w ), clamp( dirSpec2D.y, -h, h ) );","vec3 nearestPointInsideSpec = areaLightPosition[ i ] + ( areaLightRight[ i ] * nearestSpec2D.x + areaLightUp[ i ] * nearestSpec2D.y );","vec3 lightDirSpec = normalize( nearestPointInsideSpec - vertexPosition );","vec3 halfVectorSpec = normalize( lightDirSpec + eyeVector );","float dotNormalHalf = max( dot( normal, halfVectorSpec ), 0.0 );","float dotLH = max( dot( lightDirSpec, halfVectorSpec ), 0.0 );","fresnel = specularColor + ( 1.0 - specularColor ) * pow( 1.0 - dotLH, 5.0 );","#if defined( BRDF_BLINN_PHONG )","areaSpecularTerm = specularNormalization * BlinnPhong_Specular( shininess, dotLN, dotNormalHalf, eyeVector, normal ) * ( fresnel * areaDiffuseWeight ) * specAngle * areaLightColor[ i ];","#elif defined( BRDF_GGX )","areaSpecularTerm = GGX_Specular( roughness, normal, halfVectorSpec, eyeVector, lightDirSpec ) * ( fresnel * areaDiffuseWeight ) * specAngle * areaLightColor[ i ];","#endif","#ifdef AREA_TEXTURE","if ( areaLightPars[ i ].z > 0.0 ) {","float areaHard = 16.0;","float areaGloss = 16.0;","vec3 specPlane = areaLightPosition[ i ] + ( areaLightRight[ i ] * dirSpec2D.x + areaLightUp[ i ] * dirSpec2D.y );","float dist = max( distance( vertexPosition, specPlane ), 0.0 );","float d = ( ( 1.0 / areaHard ) / 2.0 ) * ( dist / areaGloss );","w = max( w, 0.0 );","h = max( h, 0.0 );","vec2 co = dirSpec2D / ( d + 1.0 );","co /= 2.0 * vec2( w, h );","co = co + vec2( 0.5 );","co.y = 1.0 - co.y;","float lod = ( 2.0 / areaHard * max( dist, 0.0 ) );","vec4 t00 = texture2D( areaLightTexture[ i ], co, lod );","vec4 t01 = texture2D( areaLightTexture[ i ], co, lod + 1.0 );","vec4 spec = mix( t00, t01, 0.5 );","areaSpecularTerm *= spec.xyz;","}","#endif","}","#ifdef USE_SHADOWMAP","int shadowIndex = int( areaLightPars[ i ].w );","if ( ( i + AREA_INDEX_OFFSET ) == shadowIndex ) {","areaDiffuseTerm  *= occlusion[ i ];","areaSpecularTerm *= occlusion[ i ];","}","#endif","areaDiffuse  += ( 1.0 - fresnel * specAngle ) * areaDiffuseTerm;","areaSpecular += areaSpecularTerm;","globalLightFactor += areaLightColor[ i ] * attenuation;","}","#endif","#if MAX_IMAGE_LIGHTS > 0","vec3 imageDiffuse  = vec3( 0.0 );","vec3 imageSpecular = vec3( 0.0 );","vec3 reflectVS = reflect( -eyeVector, normal );","vec4 reflectWS = viewInverseMatrix * vec4( reflectVS, 0.0 );","vec3 fresnelEnv = EnvironmentBRDF( gloss, dot( eyeVector, normal ), specularColor );","for( int i = 0; i < MAX_IMAGE_LIGHTS; i ++ ) {","float maxMipSpecular = imageLightPars[ i ].x;","float lightIntensity = imageLightPars[ i ].y;","float lightLocal 	  = imageLightPars[ i ].z;","float localFade = 1.0;","if ( lightLocal > 0.0 ) {","vec3 lightPositionWS = imageLightPositionWS[ i ];","vec3 lightSize = imageLightSize[ i ];","vec3 BoxMin = lightPositionWS - lightSize;","vec3 BoxMax = lightPositionWS + lightSize;","vec3 FirstPlaneIntersect = ( BoxMax - vertexPositionWS.xyz ) / reflectWS.xyz;","vec3 SecondPlaneIntersect = ( BoxMin - vertexPositionWS.xyz ) / reflectWS.xyz;","vec3 FurthestPlane = max( FirstPlaneIntersect, SecondPlaneIntersect );","float Distance = min( min( FurthestPlane.x, FurthestPlane.y ), FurthestPlane.z );","vec3 IntersectPositionWS = vertexPositionWS.xyz + reflectWS.xyz * Distance;","reflectWS.xyz = IntersectPositionWS - lightPositionWS;","vec3 lightVectorWS = abs( lightPositionWS.xyz - vertexPositionWS.xyz );","if ( lightVectorWS.x > lightSize.x || lightVectorWS.y > lightSize.y || lightVectorWS.z > lightSize.z ) {","localFade = 0.0;","} else {","vec3 normLength = lightVectorWS / lightSize;","float maxLength = max( normLength.x, max( normLength.y, normLength.z ) );","localFade = max( 1.0 - maxLength, 0.0 );","}","}","vec3 cubeCoord = reflectWS.xyz;","float maxMipLevel = maxMipSpecular - 2.0;","#ifdef SUPPORTS_TEXTURE_LOD","float mipLod = max( ( maxMipLevel * ( 1.0 - gloss ) ), 1.5 );","vec3 cubeColorSpecular = textureCubeLodEXT( imageLightTextureSpecular[ i ], cubeCoord, mipLod ).rgb;","#ifdef GAMMA_INPUT","cubeColorSpecular *= cubeColorSpecular;","#endif","#else","const float mipUnit = 255.0 / 16.0;","float mipLevelMinification = mipUnit * textureCube( imageLightTextureMip[ i ], cubeCoord ).a;","float mipLevelMagnification = mipUnit * textureCube( imageLightTextureMip[ i ], cubeCoord, maxMipSpecular - 1.0 ).a;","float mipLevel;","if ( mipLevelMinification == 0.0 ) {","mipLevel = mipLevelMagnification - ( maxMipSpecular - 1.0 );","} else {","mipLevel = mipLevelMinification;","}","float mipBias = max( ( maxMipLevel * ( 1.0 - gloss ) ) - mipLevel, 0.0 );","vec3 cubeColorSpecular = textureCube( imageLightTextureSpecular[ i ], cubeCoord, mipBias ).rgb;","#ifdef GAMMA_INPUT","cubeColorSpecular *= cubeColorSpecular;","#endif","#endif","vec4 normalWS = viewInverseMatrix * vec4( normal, 0.0 );","vec3 cubeColorDiffuse = textureCube( imageLightTextureDiffuse[ i ], normalWS.xyz ).rgb;","#ifdef GAMMA_INPUT","cubeColorDiffuse *= cubeColorDiffuse;","#endif","imageSpecular += localFade * lightIntensity * cubeColorSpecular * fresnelEnv;","imageDiffuse += localFade * lightIntensity * cubeColorDiffuse * ( 1.0 - fresnelEnv ) * diffuse.rgb;","globalLightFactor += cubeColorDiffuse[ i ] * lightIntensity;","}","#endif","vec3 totalDiffuse = vec3( 0.0 );","vec3 totalSpecular = vec3( 0.0 );","#if MAX_DIR_LIGHTS > 0","totalDiffuse += dirDiffuse;","totalSpecular += dirSpecular;","#endif","#if MAX_HEMI_LIGHTS > 0","totalDiffuse += hemiDiffuse * lightMapIntensity;","totalSpecular += hemiSpecular * lightMapIntensity;","#endif","#if MAX_POINT_LIGHTS > 0","totalDiffuse += pointDiffuse;","totalSpecular += pointSpecular;","#endif","#if MAX_SPHERE_LIGHTS > 0","totalDiffuse += sphereDiffuse;","totalSpecular += sphereSpecular;","#endif","#if MAX_TUBE_LIGHTS > 0","totalDiffuse += tubeDiffuse;","totalSpecular += tubeSpecular;","#endif","#if MAX_SPOT_LIGHTS > 0","totalDiffuse += spotDiffuse;","totalSpecular += spotSpecular;","#endif","#if MAX_AREA_LIGHTS > 0","totalDiffuse += areaDiffuse;","totalSpecular += areaSpecular;","#endif","#if MAX_IMAGE_LIGHTS > 0","totalDiffuse += imageDiffuse * lightMapIntensity;","totalSpecular += imageSpecular * lightMapIntensity;","#endif","totalDiffuse *= mgl_FragColor.a;","#ifdef METAL","mgl_FragColor.xyz = mgl_FragColor.xyz * ( totalDiffuse + totalSpecular );","#else","mgl_FragColor.xyz = mgl_FragColor.xyz * ( totalDiffuse ) + totalSpecular;","#endif"].join("\n"),XG.ShaderChunk.shadowmap_pars_fragment=["#ifdef USE_SHADOWMAP","#ifdef USE_SHADOWSAMPLER","uniform sampler2DShadow shadowMap[ MAX_SHADOWS ];","#else","uniform sampler2D shadowMap[ MAX_SHADOWS ];","#endif","uniform vec4 shadowMapPars[ MAX_SHADOWS ];","varying vec4 vShadowCoord[ MAX_SHADOWS ];","#ifdef DEPTH_TEXTURES","float unpackDepth( const in vec4 depth ) {","return depth.x;","}","#else","float unpackDepth( const in vec4 rgba_depth ) {","const vec4 bit_shift = vec4( 1.0 / 16777216.0, 1.0 / 65536.0, 1.0 / 256.0, 1.0 );","float depth = dot( rgba_depth, bit_shift );","return depth;","}","#endif","#ifdef USE_SHADOWSAMPLER","float sampleShadowPCFSoft( sampler2DShadow shadowMap, vec2 shadowMapSize, vec2 shadowCoord, float vertexDepth ) {","vec2 pixelOffset = vec2( 1.0 ) / shadowMapSize;","float dx0 = -pixelOffset.x;","float dy0 = -pixelOffset.y;","float dx1 =  pixelOffset.x;","float dy1 =  pixelOffset.y;","float shadowValue = 0.0;","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( dx0, dy0 ), vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( 0.0, dy0 ), vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( dx1, dy0 ), vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( dx0, 0.0 ), vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord, 				      vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( dx1, 0.0 ), vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( dx0, dy1 ), vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( 0.0, dy1 ), vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( dx1, dy1 ), vertexDepth ) );","shadowValue /= 9.0;","return 1.0 - shadowValue;","}","#else","float sampleShadowPCFSoft( sampler2D shadowMap, vec2 shadowMapSize, vec2 shadowCoord, float vertexDepth ) {","vec2 pixelOffset = vec2( 1.0 ) / shadowMapSize;","float dx0 = -pixelOffset.x;","float dy0 = -pixelOffset.y;","float dx1 =  pixelOffset.x;","float dy1 =  pixelOffset.y;","float shadowDepth;","mat3 shadowKernel;","shadowDepth = unpackDepth( texture2D( shadowMap, shadowCoord + vec2( dx0, dy0 ) ) );","shadowKernel[0][0] = float( vertexDepth > shadowDepth );","shadowDepth = unpackDepth( texture2D( shadowMap, shadowCoord + vec2( dx0, 0.0 ) ) );","shadowKernel[0][1] = float( vertexDepth > shadowDepth );","shadowDepth = unpackDepth( texture2D( shadowMap, shadowCoord + vec2( dx0, dy1 ) ) );","shadowKernel[0][2] = float( vertexDepth > shadowDepth );","shadowDepth = unpackDepth( texture2D( shadowMap, shadowCoord + vec2( 0.0, dy0 ) ) );","shadowKernel[1][0] = float( vertexDepth > shadowDepth );","shadowDepth = unpackDepth( texture2D( shadowMap, shadowCoord ) );","shadowKernel[1][1] = float( vertexDepth > shadowDepth );","shadowDepth = unpackDepth( texture2D( shadowMap, shadowCoord + vec2( 0.0, dy1 ) ) );","shadowKernel[1][2] = float( vertexDepth > shadowDepth );","shadowDepth = unpackDepth( texture2D( shadowMap, shadowCoord + vec2( dx1, dy0 ) ) );","shadowKernel[2][0] = float( vertexDepth > shadowDepth );","shadowDepth = unpackDepth( texture2D( shadowMap, shadowCoord + vec2( dx1, 0.0 ) ) );","shadowKernel[2][1] = float( vertexDepth > shadowDepth );","shadowDepth = unpackDepth( texture2D( shadowMap, shadowCoord + vec2( dx1, dy1 ) ) );","shadowKernel[2][2] = float( vertexDepth > shadowDepth );","shadowKernel *= 0.25;","vec2 fractionalCoord = 1.0 - fract( shadowCoord * shadowMapSize );","shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );","shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );","vec4 shadowValues;","shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );","shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );","shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );","shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );","float shadowValue = dot( shadowValues, vec4( 1.0 ) );","return shadowValue;","}","#endif","#endif"].join("\n"),XG.ShaderChunk.shadowmap_fragment=["#ifdef USE_SHADOWMAP","float occlusion[ MAX_SHADOWS ];","#ifdef SHADOWMAP_DEBUG","vec3 frustumColors[4];","frustumColors[0] = vec3( 1.0, 0.5, 0.0 );","frustumColors[1] = vec3( 0.0, 1.0, 0.8 );","frustumColors[2] = vec3( 0.0, 0.5, 1.0 );","frustumColors[3] = vec3( 1.0, 0.5, 1.0 );","#endif","#ifdef SHADOWMAP_CASCADE","int inFrustumCount = 0;","float combinedOcclusion = 1.0;","#endif","float shadowDepth;","vec3 shadowColor = vec3( 1.0 );","for( int i = 0; i < MAX_SHADOWS; i ++ ) {","occlusion[ i ] = 1.0;","vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;","vec2 shadowMapSize = shadowMapPars[ i ].xy;","float shadowDarkness = shadowMapPars[ i ].z;","float shadowBias = shadowMapPars[ i ].w;","float vertexDepth = shadowCoord.z;","bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );","bool inFrustum = all( inFrustumVec );","#ifdef SHADOWMAP_CASCADE","inFrustumCount += int( inFrustum );","bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, vertexDepth <= 1.0 );","#else","bvec2 frustumTestVec = bvec2( inFrustum, vertexDepth <= 1.0 );","#endif","bool frustumTest = all( frustumTestVec );","if ( frustumTest ) {","shadowCoord.z += shadowBias;","#if defined( SHADOWMAP_TYPE_PCF_SOFT )","float shadowValue = sampleShadowPCFSoft( shadowMap[ i ], shadowMapSize, shadowCoord.xy, vertexDepth );","#elif defined( SHADOWMAP_TYPE_PCF_SOFT_HQ )","vec2 pixelOffset = vec2( 2.0 ) / shadowMapSize;","float shadowValue0 = sampleShadowPCFSoft( shadowMap[ i ], shadowMapSize, shadowCoord.xy + vec2( -pixelOffset.x, 0.0 ), vertexDepth );","float shadowValue1 = sampleShadowPCFSoft( shadowMap[ i ], shadowMapSize, shadowCoord.xy + vec2(  pixelOffset.x, 0.0 ), vertexDepth );","float shadowValue2 = sampleShadowPCFSoft( shadowMap[ i ], shadowMapSize, shadowCoord.xy + vec2( 0.0, -pixelOffset.y ), vertexDepth );","float shadowValue3 = sampleShadowPCFSoft( shadowMap[ i ], shadowMapSize, shadowCoord.xy + vec2( 0.0,  pixelOffset.y ), vertexDepth );","float shadowValue = ( shadowValue0 + shadowValue1 + shadowValue2 + shadowValue3 ) * 0.25;","#else","#ifdef USE_SHADOWSAMPLER","float shadowValue = 1.0 - texture( shadowMap[ i ], vec3( shadowCoord.xz, vertexDepth ) );","#else","vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );","float shadowDepth = unpackDepth( rgbaDepth );","float shadowValue = float( vertexDepth > shadowDepth );","#endif","#endif","occlusion[ i ] = 1.0 - shadowDarkness * shadowValue;","#ifdef SHADOWMAP_CASCADE","combinedOcclusion *= occlusion[ i ];","#endif","}","#ifdef SHADOWMAP_DEBUG","#ifdef SHADOWMAP_CASCADE","if ( inFrustum && inFrustumCount == 1 ) mgl_FragColor.xyz *= frustumColors[ i ];","#else","if ( inFrustum ) mgl_FragColor.xyz *= frustumColors[ i ];","#endif","#endif","}","#ifdef SHADOWMAP_CASCADE","occlusion[ DIR_INDEX_OFFSET ] = combinedOcclusion;","#endif","#endif"].join("\n"),XG.ShaderChunk.shadowmap_pars_vertex=["#ifdef USE_SHADOWMAP","varying vec4 vShadowCoord[ MAX_SHADOWS ];","uniform mat4 shadowMatrix[ MAX_SHADOWS ];","#endif"].join("\n"),XG.ShaderChunk.shadowmap_vertex=["#ifdef USE_SHADOWMAP","for( int i = 0; i < MAX_SHADOWS; i ++ ) {","vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;","}","#endif"].join("\n"),XG.ShaderChunk.alphatest_fragment=["#ifdef ALPHATEST","if ( mgl_FragColor.a < ALPHATEST ) discard;","#endif"].join("\n"),XG.ShaderChunk.linear_to_gamma_fragment=["#ifdef GAMMA_OUTPUT","mgl_FragColor.xyz = sqrt( mgl_FragColor.xyz );","#endif"].join("\n"),XG.ShaderChunk.tonemapping_fragment=["#ifdef TONEMAPPING","mgl_FragColor.rgb = applyTonemapping( mgl_FragColor.rgb, brightness, whitePoint );","#endif"].join("\n"),XG.ShaderChunk.dithering_fragment=["#ifdef DITHERING_ENABLED","mgl_FragColor.rgb = applyDithering( mgl_FragColor.rgb, gl_FragCoord.xy );","#endif"].join("\n"),XG.UniformsLib.fog={fogDensity:{type:"f",value:25e-5,shared:!0},fogNearFar:{type:"v2",value:new XG.Vector2(1,2e3),shared:!0},fogStartStrength:{type:"v2",value:new XG.Vector2(100,.1),shared:!0},fogColor:{type:"c",value:new XG.Color(16777215),shared:!0}},XG.UniformsLib.heightFog={fogHeight:{type:"f",value:-15,shared:!0},fogVisibilityDistance:{type:"f",value:50,shared:!0},fogFadeSpeed:{type:"f",value:.15,shared:!0},fogShallowDepthColor:{type:"c",value:(new XG.Color).setRGB(.0078,.5176,.7),shared:!0},fogDeepDepthColor:{type:"c",value:(new XG.Color).setRGB(.0039,.00196,.145),shared:!0},fogRgbExtinctionDistance:{type:"v3",value:new XG.Vector3(7,30,40),shared:!0}},XG.UniformsLib.lights={directionalLightDirectionVS:{type:"fv3",value:[],shared:!0},directionalLightColor:{type:"fv3",value:[],shared:!0},directionalLightPars:{type:"iv1",value:[],shared:!0},hemisphereLightDirectionVS:{type:"fv3",value:[],shared:!0},hemisphereLightSkyColor:{type:"fv3",value:[],shared:!0},hemisphereLightGroundColor:{type:"fv3",value:[],shared:!0},pointLightColor:{type:"fv3",value:[],shared:!0},pointLightPositionVS:{type:"fv3",value:[],shared:!0},pointLightDistance:{type:"fv1",value:[],shared:!0},sphereLightColor:{type:"fv3",value:[],shared:!0},sphereLightPositionVS:{type:"fv3",value:[],shared:!0},sphereLightPars:{type:"fv3",value:[],shared:!0},tubeLightColor:{type:"fv3",value:[],shared:!0},tubeLightPosition0VS:{type:"fv3",value:[],shared:!0},tubeLightPosition1VS:{type:"fv3",value:[],shared:!0},tubeLightPars:{type:"fv2",value:[],shared:!0},spotLightColor:{type:"fv3",value:[],shared:!0},spotLightPositionVS:{type:"fv3",value:[],shared:!0},spotLightDirectionVS:{type:"fv3",value:[],shared:!0},spotLightPars:{type:"fv4",value:[],shared:!0},areaLightColor:{type:"fv3",value:[],shared:!0},areaLightPosition:{type:"fv3",value:[],shared:!0},areaLightNormal:{type:"fv3",value:[],shared:!0},areaLightRight:{type:"fv3",value:[],shared:!0},areaLightUp:{type:"fv3",value:[],shared:!0},areaLightPars:{type:"fv4",value:[],shared:!0},areaLightAttenuation:{type:"fv3",value:[],shared:!0},areaLightTexture:{type:"tv",value:[],shared:!0},imageLightTextureDiffuse:{type:"tv",value:[],shared:!0},imageLightTextureSpecular:{type:"tv",value:[],shared:!0},imageLightTextureMip:{type:"tv",value:[],shared:!0},imageLightPars:{type:"fv3",value:[],shared:!0},imageLightPositionWS:{type:"fv3",value:[],shared:!0},imageLightSize:{type:"fv3",value:[],shared:!0}},XG.UniformsLib.dynamicParticle={time:{type:"f",value:0},timeRange:{type:"f",value:1.25},timeOffset:{type:"f",value:0},numFrames:{type:"f",value:1},frameDuration:{type:"f",value:1},tDepth:{type:"t",value:null,shared:!0},viewSize:{type:"v2",value:new XG.Vector2(800,600),shared:!0}},XG.UniformsLib.shadowmap={shadowMap:{type:"tv",value:[],shared:!0},shadowMapPars:{type:"v4v",value:[],shared:!0},shadowMatrix:{type:"m4v",value:[],shared:!0}},XG.ShaderLib.emissive={uniforms:XG.UniformsUtils.merge([{diffuse:{type:"v4",value:new XG.Vector4(.9,.9,.9,1)}},XG.UniformsLib.common,XG.UniformsLib.fog,XG.UniformsLib.particle,XG.UniformsLib.displacement]),vertexShader:[XG.ShaderChunk.instances_pars_vertex,XG.ShaderChunk.map_pars_vertex,XG.ShaderChunk.color_pars_vertex,XG.ShaderChunk.morphtarget_pars_vertex,XG.ShaderChunk.skinning_pars_vertex,XG.ShaderChunk.particle_pars_vertex,XG.ShaderChunk.displacement_pars_vertex,"void main() {",XG.ShaderChunk.map_vertex,XG.ShaderChunk.color_vertex,XG.ShaderChunk.skinbase_vertex,XG.ShaderChunk.begin_pos_vertex,XG.ShaderChunk.displacement_vertex,XG.ShaderChunk.morphtarget_vertex,XG.ShaderChunk.skinning_vertex,XG.ShaderChunk.end_pos_vertex,XG.ShaderChunk.worldpos_vertex,XG.ShaderChunk.particle_vertex,"}"].join("\n"),fragmentShader:["uniform vec4 diffuse;",XG.ShaderChunk.color_pars_fragment,XG.ShaderChunk.map_pars_fragment,XG.ShaderChunk.lightmap_pars_fragment,XG.ShaderChunk.fog_pars_fragment,XG.ShaderChunk.tonemappingFragmentPars,XG.ShaderChunk.ditheringFragmentPars,XG.ShaderChunk.linearDepthFragmentPars,"void main() {","mgl_FragColor = diffuse;","#if !defined( PARTICLE ) && ( defined( USE_MAP ) || defined( USE_LIGHTMAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined ( USE_NORMALGLOSSMAP ) || defined ( USE_GLOSSMAP ) || defined( USE_SPECULARMAP ) )","vec2 uvCoord = vUv;","#endif",XG.ShaderChunk.map_fragment,XG.ShaderChunk.alphatest_fragment,XG.ShaderChunk.lightmap_fragment,XG.ShaderChunk.color_fragment,"mgl_FragColor.xyz *= lightMapIntensity;",XG.ShaderChunk.fog_fragment,XG.ShaderChunk.linear_to_gamma_fragment,XG.ShaderChunk.tonemapping_fragment,XG.ShaderChunk.dithering_fragment,"}"].join("\n")},XG.ShaderLib.phong={uniforms:XG.UniformsUtils.merge([XG.UniformsLib.common,XG.UniformsLib.bump,XG.UniformsLib.normalmap,XG.UniformsLib.fog,XG.UniformsLib.heightFog,XG.UniformsLib.lights,XG.UniformsLib.shadowmap,XG.UniformsLib.displacement,{diffuse:{type:"v4",value:new XG.Vector4(.9,.9,.9,1)},specular:{type:"v4",value:new XG.Vector4(.1,.1,.1,30)},wrapRGB:{type:"v3",value:new XG.Vector3(1,1,1)},glossMap:{type:"t",value:null},specularMap:{type:"t",value:null},parallaxScale:{type:"f",value:1},detailRepeatScale:{type:"v3",value:new XG.Vector3(1,1,1)},cameraNearFar:{type:"v2",value:new XG.Vector2(1,500)}}]),vertexShader:["varying vec3 vViewPosition;","varying vec3 vNormal;","#if defined( ATMOSPHERIC_FOG )","varying vec4 vClipPosition;","#endif",XG.ShaderChunk.instances_pars_vertex,XG.ShaderChunk.map_pars_vertex,XG.ShaderChunk.color_pars_vertex,XG.ShaderChunk.morphtarget_pars_vertex,XG.ShaderChunk.skinning_pars_vertex,XG.ShaderChunk.shadowmap_pars_vertex,XG.ShaderChunk.displacement_pars_vertex,"void main() {",XG.ShaderChunk.map_vertex,XG.ShaderChunk.color_vertex,XG.ShaderChunk.begin_nor_vertex,XG.ShaderChunk.morphnormal_vertex,XG.ShaderChunk.skinbase_vertex,XG.ShaderChunk.skinnormal_vertex,XG.ShaderChunk.end_nor_vertex,"vNormal = transformedNormal;",XG.ShaderChunk.begin_pos_vertex,XG.ShaderChunk.displacement_vertex,XG.ShaderChunk.morphtarget_vertex,XG.ShaderChunk.skinning_vertex,XG.ShaderChunk.end_pos_vertex,"vViewPosition = mvPosition.xyz;",XG.ShaderChunk.worldpos_vertex,XG.ShaderChunk.shadowmap_vertex,"#if defined( ATMOSPHERIC_FOG )","vClipPosition = gl_Position;","#endif","}"].join("\n"),fragmentShader:["uniform vec4 diffuse;","uniform vec4 specular;",XG.ShaderChunk.color_pars_fragment,XG.ShaderChunk.map_pars_fragment,XG.ShaderChunk.lightmap_pars_fragment,XG.ShaderChunk.fog_pars_fragment,XG.ShaderChunk.height_fog_pars_fragment,XG.ShaderChunk.area_lights_utils,XG.ShaderChunk.utils_pars_fragment,XG.ShaderChunk.lights_phong_pars_fragment,XG.ShaderChunk.skin_pars_fragment,XG.ShaderChunk.shadowmap_pars_fragment,XG.ShaderChunk.bumpmap_pars_fragment,XG.ShaderChunk.derivativemap_pars_fragment,XG.ShaderChunk.normalmap_pars_fragment,XG.ShaderChunk.parallax_pars_fragment,XG.ShaderChunk.displacementmap_pars_fragment,XG.ShaderChunk.specularmap_pars_fragment,XG.ShaderChunk.glossmap_pars_fragment,XG.ShaderChunk.tonemappingFragmentPars,XG.ShaderChunk.ditheringFragmentPars,XG.ShaderChunk.linearDepthFragmentPars,"#if defined( USE_BUMPDETAILMAP ) || defined( USE_NORMALDETAILMAP )","uniform vec3 detailRepeatScale;","#endif","#if defined( ATMOSPHERIC_FOG )","uniform vec2 cameraNearFar;","varying vec4 vClipPosition;","#endif","void main() {","mgl_FragColor = vec4( vec3 ( 1.0 ), diffuse.a );","#if !defined( PARTICLE ) && ( defined( USE_MAP ) || defined( USE_LIGHTMAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_BUMPDETAILMAP ) || defined( USE_NORMALDETAILMAP ) || defined ( USE_NORMALGLOSSMAP ) || defined ( USE_GLOSSMAP ) || defined( USE_SPECULARMAP ) || defined( USE_DISPLACEMENTMAP ) )","vec2 uvCoord = vUv;","#endif","vec3 normal = normalize( vNormal );","vec3 vertexPosition = vViewPosition;","vec3 eyeVector = normalize( -vertexPosition );",XG.ShaderChunk.parallax_fragment,XG.ShaderChunk.map_fragment,XG.ShaderChunk.alphatest_fragment,XG.ShaderChunk.color_fragment,XG.ShaderChunk.specularmap_fragment,XG.ShaderChunk.shadowmap_fragment,XG.ShaderChunk.lightmap_fragment,XG.ShaderChunk.lights_phong_fragment,XG.ShaderChunk.height_fog_fragment,XG.ShaderChunk.fog_fragment,XG.ShaderChunk.linear_to_gamma_fragment,XG.ShaderChunk.tonemapping_fragment,XG.ShaderChunk.dithering_fragment,"vec4 pixelColor = mgl_FragColor;","#if defined( TRANSLUCENT_PASS )","mgl_FragColor = vec4( pixelColor.a );","#endif","}"].join("\n")},XG.ShaderLib.dynamicParticle={uniforms:XG.UniformsUtils.merge([{diffuse:{type:"v4",value:new XG.Vector4(.9,.9,.9,1)},cameraNearFar:{type:"v2",value:new XG.Vector2(1,500)},additiveFactor:{type:"f",value:0},directionalLightPositionVS:{type:"fv4",value:[],shared:!0}},XG.UniformsLib.common,XG.UniformsLib.fog,XG.UniformsLib.particle,XG.UniformsLib.dynamicParticle,XG.UniformsLib.lights,XG.UniformsLib.fogAtmo]),vertexShader:[XG.ShaderChunk.particle_pars_vertex,"uniform float time;","uniform float timeRange;","uniform float timeOffset;","#ifdef OFFSCREEN_PARTICLES","varying vec4 vClipPosition;","#endif","#ifdef USE_LIGHTS","varying vec3 vViewPosition;","#endif","varying vec4 vSpinLifeTime;","attribute vec4 velocitySpinStart;","attribute vec4 accelerationSpinSpeed;","attribute vec4 startSizeEndSizeStartTimeLifeTime;","void main() {","float startSize = startSizeEndSizeStartTimeLifeTime.x;","float endSize = startSizeEndSizeStartTimeLifeTime.y;","float startTime = startSizeEndSizeStartTimeLifeTime.z;","float lifeTime = startSizeEndSizeStartTimeLifeTime.w;","vec3 velocity = velocitySpinStart.xyz;","float spinStart = velocitySpinStart.w;","vec3 acceleration = accelerationSpinSpeed.xyz;","float spinSpeed = accelerationSpinSpeed.w;","float localTime = mod( ( time - timeOffset - startTime ), timeRange );","float percentLife = localTime / lifeTime;","vec3 newPosition = position + velocity * localTime + acceleration * localTime * localTime;","vec4 mvPosition = modelViewMatrix * vec4( newPosition, 1.0 );","gl_Position = projectionMatrix * mvPosition;","float currentSize = 0.5 * particleSize * mix( startSize, endSize, percentLife );","currentSize *= step( 0.0, percentLife );","currentSize *= step( -1.0, -percentLife );","if ( currentSize == 0.0 ) gl_Position = vec4( -100000000.0 );","#ifdef OFFSCREEN_PARTICLES","vClipPosition = gl_Position;","#endif","#ifdef USE_LIGHTS","vViewPosition = mvPosition.xyz;","#endif","vec4 projectedCorner = projectionMatrix * vec4( currentSize, currentSize, mvPosition.z, mvPosition.w );","gl_PointSize = screenWidth * projectedCorner.x / projectedCorner.w;","percentLife *= step( 0.0, percentLife );","percentLife *= step( -1.0, -percentLife );","vSpinLifeTime = vec4( spinStart, spinSpeed, percentLife, localTime );","}"].join("\n"),fragmentShader:[XG.ShaderChunk.fog_pars_fragment,XG.ShaderChunk.tonemappingFragmentPars,XG.ShaderChunk.ditheringFragmentPars,"uniform sampler2D map;","uniform vec4 diffuse;","uniform float time;","uniform float numFrames;","uniform float frameDuration;","uniform vec2 cameraNearFar;","uniform float additiveFactor;","#ifdef OFFSCREEN_PARTICLES","uniform sampler2D tDepth;","uniform vec2 viewSize;","varying vec4 vClipPosition;","#ifdef RGBA_DEPTH","float unpackDepth( vec4 rgba ) {","return dot( rgba, vec4( 1.0, 1.0/255.0, 1.0/65025.0, 1.0/16581375.0 ) );","}","#endif","#if defined( OIT_PARTICLES )","float alphaWeight( float a, float z ) {","return a * max( 1e-2, min( 3.0 * 1e3, 0.03 / ( 1e-5 + pow( abs(z) / 200.0, 4.0 ) ) ) );","}","#endif",XG.ShaderChunk.fogAtmoFragmentPars,XG.ShaderChunk.linearDepthFragmentPars,"#endif","#ifdef USE_LIGHTS","#if MAX_DIR_LIGHTS > 0","uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];","uniform vec4 directionalLightPositionVS[ MAX_DIR_LIGHTS ];","uniform int directionalLightPars[ MAX_DIR_LIGHTS ];","#endif","#if MAX_POINT_LIGHTS > 0","uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];","uniform vec3 pointLightPositionVS[ MAX_POINT_LIGHTS ];","uniform float pointLightDistance[ MAX_POINT_LIGHTS ];","#endif","#if MAX_SPOT_LIGHTS > 0","uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];","uniform vec3 spotLightPositionVS[ MAX_SPOT_LIGHTS ];","uniform vec3 spotLightDirectionVS[ MAX_SPOT_LIGHTS ];","uniform vec4 spotLightPars[ MAX_SPOT_LIGHTS ];","#endif","varying vec3 vViewPosition;","float computeAttenuation( float distanceToLight, float lightRange ) {","const float cutoff = 0.3;","float denom = distanceToLight / lightRange + 1.0;","float attenuation = 1.0 / ( denom * denom );","attenuation = ( attenuation - cutoff ) / ( 1.0 - cutoff );","attenuation = max( attenuation, 0.0 );","attenuation *= attenuation;","return attenuation;","}","#endif","varying vec4 vSpinLifeTime;","void main() {","#if defined( OFFSCREEN_PARTICLES )","vec2 screenCoord = gl_FragCoord.xy / viewSize;","#if defined( RGBA_DEPTH )","float sceneDepth = unpackDepth( texture2D( tDepth, screenCoord ) );","#elif defined( FLOAT_DEPTH )","float sceneDepth = texture2D( tDepth, screenCoord ).w;","#elif defined( TEXTURE_DEPTH )","float sceneDepth = texture2D( tDepth, screenCoord ).x * 2.0 - 1.0;","#endif","float myDepth = vClipPosition.z / vClipPosition.w;","float myLinearDepth = linearizeDepth( myDepth, cameraNearFar );","float sceneLinearDepth = linearizeDepth( sceneDepth, cameraNearFar );","const float scale = 0.1;","float zFade = clamp( scale * abs( myLinearDepth - sceneLinearDepth ), 0.0, 1.0 );","if ( myDepth > sceneDepth ) discard;","#endif","float spinStart = vSpinLifeTime.x;","float spinSpeed = vSpinLifeTime.y;","float percentLife = vSpinLifeTime.z;","float localTime = vSpinLifeTime.w;","const float frameStart = 0.0;","vec2 texCoord = vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) - 0.5;","float s = sin( spinStart + spinSpeed * time );","float c = cos( spinStart + spinSpeed * time );","vec2 rotatedCoord1 = vec2( texCoord.x * c + texCoord.y * s, -texCoord.x * s + texCoord.y * c ) + 0.5;","rotatedCoord1 = clamp( rotatedCoord1, 0.0, 1.0 );","vec2 rotatedCoord2 = rotatedCoord1;","float frame1 = mod( floor( localTime / frameDuration + frameStart ), numFrames );","float uOffset1 = frame1 / numFrames;","rotatedCoord1.x = uOffset1 + ( rotatedCoord1.x ) * ( 1.0 / numFrames );","vec4 pixel1 = texture2D( map, rotatedCoord1 );","pixel1.xyz *= pixel1.xyz;","#ifdef INTERPOLATE_PARTICLE_FRAMES","float frame2 = mod( floor( localTime / frameDuration + frameStart + 1.0 ), numFrames );","float uOffset2 = frame2 / numFrames;","float frameTime = fract( localTime / frameDuration + frameStart );","rotatedCoord2.x = uOffset2 + ( rotatedCoord2.x ) * ( 1.0 / numFrames );","vec4 pixel2 = texture2D( map, rotatedCoord2 );","pixel2.xyz *= pixel2.xyz;","pixel1 = mix( pixel1, pixel2, frameTime );","#endif","if ( pixel1.a < 0.001 ) discard;","vec4 particleColor = pixel1 * diffuse;","#ifdef USE_LIGHTS","vec3 vertexPosition = vViewPosition;","vec3 pColor = particleColor.rgb;","vec3 accumulatedColor = vec3( 0.0 );","#if MAX_DIR_LIGHTS > 0","for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {","vec3 lightColor = directionalLightColor[ i ];","vec4 lightPositionDistance = directionalLightPositionVS[ i ];","vec3 lightPosition = lightPositionDistance.xyz;","float lightDistance = lightPositionDistance.w;","float d = distance( lightPosition, vertexPosition );","float attenuation = computeAttenuation( d, lightDistance );","accumulatedColor += attenuation * lightColor * pColor;","}","#endif","#if MAX_POINT_LIGHTS > 0","for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {","vec3 lightColor = pointLightColor[ i ];","vec3 lightPosition = pointLightPositionVS[ i ];","float lightDistance = pointLightDistance[ i ];","float d = distance( lightPosition, vertexPosition );","float attenuation = computeAttenuation( d, lightDistance );","accumulatedColor += attenuation * lightColor * pColor;","}","#endif","#if MAX_SPOT_LIGHTS > 0","for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {","vec3 lightColor = spotLightColor[ i ];","vec3 lightPosition = spotLightPositionVS[ i ];","vec3 lightVector = lightPosition - vertexPosition;","float lightDistance = length( lightVector );","float spotLightAngleCos = spotLightPars[ i ].x;","float spotLightExponent = spotLightPars[ i ].y;","float spotLightDistance = spotLightPars[ i ].z;","float attenuation = 1.0;","if ( spotLightDistance > 0.0 )","attenuation = 1.0 - min( lightDistance / spotLightDistance, 1.0 );","lightVector = lightVector / lightDistance;","float rho = dot( spotLightDirectionVS[ i ], lightVector );","if ( rho > spotLightAngleCos ) {;","float theta = spotLightAngleCos + 0.0001;","float phi = spotLightAngleCos + 0.05;","const float falloff = 4.0;","float spotEffect = 0.0;","if ( rho >= phi ) {","spotEffect = 1.0;","} else if ( rho <= theta ) {","spotEffect = 0.0;","} else { ","spotEffect = pow( ( rho - theta ) / ( phi - theta ), falloff );","}","attenuation *= spotEffect;","accumulatedColor += attenuation * lightColor * pColor;","}","}","#endif","particleColor.rgb = accumulatedColor;","#endif","#if defined( OFFSCREEN_PARTICLES )","#ifdef FOG_ENABLED","particleColor.rgb = addFog( particleColor.rgb, myLinearDepth );","#endif","particleColor.a *= zFade;","#endif","#if defined( OIT_PARTICLES ) && defined( OFFSCREEN_PARTICLES )","float ai = particleColor.a;","vec3 Ci = particleColor.rgb * particleColor.a;","float wzi = alphaWeight( ai, myLinearDepth );","#endif","#if defined( OIT_MRT_PASS )","mgl_FragData[ 0 ] = vec4( Ci * wzi, ai );","mgl_FragData[ 1 ] = vec4( ai * wzi );","if ( additiveFactor > 0.0 ) mgl_FragData[ 1 ] = vec4( additiveFactor );","#elif defined( OIT_ACCUMULATION_PASS )","mgl_FragColor = vec4( Ci * wzi, ai );","#elif defined( OIT_REVEALAGE_PASS )","mgl_FragColor = vec4( ai * wzi );","if ( additiveFactor > 0.0 ) mgl_FragColor = vec4( additiveFactor );","#elif defined( TRANSLUCENT_PASS )","mgl_FragColor = vec4( particleColor.a );","#else","mgl_FragColor = particleColor;","#endif","}"].join("\n")},XG.ShaderLib.depthRGBA={uniforms:XG.UniformsUtils.merge([{slopeScale:{type:"f",value:2,shared:!0},slopeBias:{type:"f",value:0,shared:!0},slopeMax:{type:"f",value:.001,shared:!0},epsilon:{type:"f",value:.1},alphaTest:{type:"f",value:.5},map:{type:"t",value:null}},{offsetRepeat:{type:"v4",value:new XG.Vector4(0,0,1,1)}},XG.UniformsLib.displacement]),vertexShader:[XG.ShaderChunk.instances_pars_vertex,XG.ShaderChunk.morphtarget_pars_vertex,XG.ShaderChunk.skinning_pars_vertex,XG.ShaderChunk.displacement_pars_vertex,"#ifdef USE_DISPLACEMENTMAP","uniform vec4 offsetRepeat;","#endif","#ifdef SPRITE","attribute vec3 offset;","attribute vec2 scale;","varying vec2 vUv;","#endif","void main() {","#ifdef SPRITE","#ifdef BILLBOARD","vec4 tmpPosition = modelViewMatrix * vec4( offset, 1.0 ) + vec4( position * vec3( scale, 1.0 ), 0.0 );","gl_Position = projectionMatrix * tmpPosition;","#else","vec3 spritePosition = position * vec3( scale, 1.0 ) + offset;","vec4 mvPosition = modelViewMatrix * vec4( spritePosition, 1.0 );","gl_Position = projectionMatrix * mvPosition;","#endif","vUv = uv;","#else","#ifdef USE_DISPLACEMENTMAP","vec2 transformedUV = uv * offsetRepeat.zw + offsetRepeat.xy;","#endif",XG.ShaderChunk.skinbase_vertex,XG.ShaderChunk.begin_pos_vertex,XG.ShaderChunk.displacement_vertex,XG.ShaderChunk.morphtarget_vertex,XG.ShaderChunk.skinning_vertex,XG.ShaderChunk.end_pos_vertex,"#endif","}"].join("\n"),fragmentShader:["#ifdef SPRITE","uniform float epsilon;","uniform float alphaTest;","uniform sampler2D map;","varying vec2 vUv;","#endif","#if !defined( DEPTH_TEXTURES )","#ifdef SLOPE_DEPTH_BIAS","uniform float slopeScale;","uniform float slopeBias;","uniform float slopeMax;","#endif","vec4 pack_depth( const in float depth ) {","const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );","const vec4 bit_mask  = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );","vec4 res = fract( depth * bit_shift );","res -= res.xxyz * bit_mask;","return res;","}","#endif","void main() {","#ifdef SPRITE","vec4 texture = texture2D( map, vUv );","#ifdef SDF","#if defined( GL_OES_standard_derivatives ) || __VERSION__ >= 300","float w = clamp( 200.0 * epsilon * ( abs( dFdx( vUv.x ) ) + abs( dFdy( vUv.y ) ) ), 0.0, 0.5 );","#else","float w = epsilon;","#endif","float alpha = smoothstep( 0.5 - w, 0.5 + w, texture.r );","alpha = pow( alpha, 1.0/2.2 );","#else","float alpha = texture.a;","#endif","if ( alpha < alphaTest ) discard;","#endif","#ifndef DEPTH_TEXTURES","float depth = gl_FragCoord.z;","#ifdef SLOPE_DEPTH_BIAS","float dx = dFdx( depth );","float dy = dFdy( depth );","float m = max( abs(dx), abs(dy) );","m = min( m, slopeMax );","depth += m * slopeScale + slopeBias;","#endif","mgl_FragColor = pack_depth( depth );","#endif","}"].join("\n")},XG.DeferredUniformsLib={},XG.DeferredShaderChunk={},XG.DeferredShaders={},XG.DeferredUniformsLib.gbuffers={samplerColor:{type:"t",value:null,shared:!0},samplerNormalDepth:{type:"t",value:null,shared:!0},samplerDiffuseRGB:{type:"t",value:null,shared:!0},samplerSpecularRGB:{type:"t",value:null,shared:!0},samplerWrapRGB:{type:"t",value:null,shared:!0},samplerNormal:{type:"t",value:null,shared:!0},samplerDepth:{type:"t",value:null,shared:!0},viewSize:{type:"v2",value:new XG.Vector2(800,600),shared:!0}},XG.DeferredUniformsLib.multiShadowMaps={samplerShadowMap:{type:"tv",value:[]},shadowMapSize:{type:"v2",value:new XG.Vector2(512,512)},shadowDarkness:{type:"f",value:.5},shadowBias:{type:"f",value:0},matShadow:{type:"m4v",value:[]}},XG.DeferredUniformsLib.projectedTexture={samplerTexture:{type:"t",value:null},textureBias:{type:"f",value:0},matTexture:{type:"m4",value:new XG.Matrix4}},XG.DeferredShaderChunk.gbuffersUniforms=["#ifdef USE_MRT","uniform sampler2D samplerDiffuseRGB;","uniform sampler2D samplerSpecularRGB;","uniform sampler2D samplerWrapRGB;","uniform sampler2D samplerNormal;","uniform sampler2D samplerDepth;","#else","uniform sampler2D samplerColor;","uniform sampler2D samplerNormalDepth;","#endif","uniform vec2 viewSize;"].join("\n"),XG.DeferredShaderChunk.multiShadowMapsUniforms=["#ifdef USE_SHADOWMAP","#ifdef USE_SHADOWSAMPLER","uniform sampler2DShadow samplerShadowMap[ SHADOWMAP_COUNT ];","#else","uniform sampler2D samplerShadowMap[ SHADOWMAP_COUNT ];","#endif","uniform mat4 matShadow[ SHADOWMAP_COUNT ];","uniform float shadowBias;","uniform float shadowDarkness;","uniform vec2 shadowMapSize;","#endif"].join("\n"),XG.DeferredShaderChunk.projectedTextureUniforms=["#ifdef PROJECTED_TEXTURE","uniform sampler2D samplerTexture;","uniform float textureBias;","uniform mat4 matTexture;","#endif"].join("\n"),XG.DeferredShaderChunk.packFloat=["const float unit = 255.0/256.0;","float vec3_to_float( vec3 data ) {","highp float compressed = dot( floor( data * 255.0 + 0.5 ), vec3( 1.0, 256.0, 65536.0 ) );","return compressed;","}","float vec21_to_float( float dataHi, float dataLo ) {","highp float compressed = floor( dataHi ) + unit * dataLo;","return compressed;","}","vec3 packWrapAroundShininess( float wrapAround, float shininess ) {","vec3 tmp;","tmp.r = wrapAround + 0.5;","tmp.b = fract( shininess / 256.0 );","tmp.g = floor( shininess / 256.0 ) / 256.0;","return tmp;","}","vec4 packDepth( const in float depth ) {","vec4 enc = vec4( 1.0, 255.0, 65025.0, 16581375.0 ) * depth;","enc = fract( enc );","enc -= enc.yzww * vec4( 1.0/255.0, 1.0/255.0, 1.0/255.0, 0.0 );","return enc;","}"].join("\n"),XG.DeferredShaderChunk.unpackFloat=["const float unitInverse = 256.0/255.0;","vec3 float_to_vec3( float data ) {","vec3 uncompressed;","uncompressed.z = data / 65536.0;","uncompressed.y = 256.0 * fract( uncompressed.z );","uncompressed.x = 256.0 * fract( uncompressed.y );","return floor( uncompressed ) / 255.0;","}","vec2 float_to_vec21( float data ) {","vec2 uncompressed;","uncompressed.x = floor( data );","uncompressed.y = fract( data ) * unitInverse;","return uncompressed;","}","float unpackDepth( const in vec4 rgba ) {","return clamp( dot( rgba, vec4( 1.0, 1.0/255.0, 1.0/65025.0, 1.0/16581375.0 ) ), 0.0, 1.0 );","}"].join("\n"),XG.DeferredShaderChunk.computeVertexPositionVS=["vec2 texCoord = gl_FragCoord.xy / viewSize;","#ifdef USE_MRT","#ifdef TEXTURE_DEPTH","vec4 texDepth = texture2D( samplerDepth, texCoord );","float z = texDepth.x * 2.0 - 1.0;","#else","vec4 packedDepth = texture2D( samplerDepth, texCoord );","float z = unpackDepth( packedDepth );","#endif","#else","vec4 normalDepth = texture2D( samplerNormalDepth, texCoord );","float z = normalDepth.w;","#endif","if ( z <= 0.0 || z >= 1.0 ) discard;","vec2 xy = texCoord * 2.0 - 1.0;","vec4 vertexPositionProjected = vec4( xy, z, 1.0 );","vec4 vertexPositionVS = matProjInverse * vertexPositionProjected;","vertexPositionVS.xyz /= vertexPositionVS.w;","vertexPositionVS.w = 1.0;"].join("\n"),XG.DeferredShaderChunk.computeNormal=["#ifdef USE_MRT","vec4 normalTex = texture2D( samplerNormal, texCoord );","vec3 normal = normalTex.xyz * 2.0 - 1.0;","#else","vec3 normal = normalDepth.xyz * 2.0 - 1.0;","#endif","normal = normalize( normal );"].join("\n"),XG.DeferredShaderChunk.unpackColorMap=["#ifdef USE_MRT","vec4 albedoShininessLo = texture2D( samplerDiffuseRGB, texCoord );","vec3 albedo = albedoShininessLo.rgb * albedoShininessLo.rgb;","vec4 specularColorShininessHi = texture2D( samplerSpecularRGB, texCoord );","vec3 specularColor = specularColorShininessHi.rgb * specularColorShininessHi.rgb;","float shininess = specularColorShininessHi.a * 256.0 * 256.0 + albedoShininessLo.a * 256.0;","vec4 wrapRGBWrapAround = texture2D( samplerWrapRGB, texCoord );","vec3 wrapRGB = wrapRGBWrapAround.rgb;","float wrapAround = sign( wrapRGBWrapAround.a - 0.5 );","float lightMapIntensity = normalTex.a;","#else","vec4 colorMap = texture2D( samplerColor, texCoord );","vec3 albedo = float_to_vec3( abs( colorMap.x ) );","albedo *= albedo;","vec3 specularColor = float_to_vec3( abs( colorMap.y ) );","specularColor *= specularColor;","vec3 wrapRGB = float_to_vec3( abs( colorMap.w ) );","vec2 shininessLightmap = float_to_vec21( abs( colorMap.z ) );","float shininess = shininessLightmap.x;","float lightMapIntensity = shininessLightmap.y;","float wrapAround = sign( colorMap.z );","#endif"].join("\n"),XG.DeferredShaderChunk.computeDiffuse=["float dotLNUnclamped = dot( lightVector, normal );","float dotLN = max( dotLNUnclamped, 0.0 );","vec3 diffuse = vec3( dotLN );","if ( wrapAround < 0.0 ) {","#ifdef SKIN_HQ","float curvature = length( fwidth( normal ) ) / length( fwidth( vertexPositionVS.xyz ) );","diffuse = PSSFitFunction( dotLNUnclamped, curvature );","#else","float dotLNHalf = max( 0.25 * dotLNUnclamped + 0.25, 0.0 );","diffuse = mix( diffuse, vec3( dotLNHalf ), wrapRGB );","#endif","}"].join("\n"),XG.DeferredShaderChunk.geometryFactor=["float SmithGeometryFactor1( vec3 H, vec3 V, vec3 N, float shininess ) {","float dotVN = dot( V, N );","float dotVH = dot( V, H );","if ( ( dotVH / dotVN ) <= 0.0 ) return 0.0;","float f = acos( dotVN );","float a = sqrt( 0.5 * shininess + 1.0 ) / tan( f );","float G = 1.0;","if ( a < 1.6 )","G = ( 3.535 * a + 2.181 * a * a ) / ( 1.0 + 2.276 * a + 2.577 * a * a );","return G;","}","float SmithGeometryFactor2( float dotLN, vec3 V, vec3 N, float shininess ) {","float dotNV = max( dot( N, V ), 0.0 );","float a = 1.0 / ( sqrt( 0.7854 * shininess + 1.571 ) );","return 1.0 / ( ( dotLN * ( 1.0 - a ) + a ) * ( dotNV * ( 1.0 - a ) + a ) );","}","float KelemenGeometryFactor( float dotLH ) {","return 1.0 / ( dotLH * dotLH );","}","float GGX_SchlickGeometryFactor_V1( in float k, in float dotNX ) {","return dotNX / ( dotNX * ( 1.0 - k ) + k );","}","float GGX_SchlickGeometryFactor_V2( in float k, in float dotNX ) {","return 1.0 / ( dotNX + sqrt( k + ( 1.0 - k ) * dotNX * dotNX ) );","}"].join("\n"),XG.DeferredShaderChunk.environmentBRDF=["vec3 EnvironmentBRDF( float gloss, float dotNV, vec3 rf0 ) {","vec4 t = vec4( 1.0 / 0.96, 0.475, ( 0.0275 - 0.25 * 0.04 ) / 0.96, 0.25 );","t *= vec4( gloss );","t += vec4( 0.0, 0.0, ( 0.015 - 0.75 * 0.04 ) / 0.96, 0.75 );","float a0 = t.x * min( t.y, exp2( -9.28 * dotNV ) ) + t.z;","float a1 = t.w;","return clamp( a0 + rf0 * ( a1 - a0 ), 0.0, 1.0 );","}"].join("\n"),XG.DeferredShaderChunk.specularBRDF=["float GGX_Specular( in float m, in vec3 n, in vec3 h, in vec3 v, in vec3 l ) {","float nDotH = saturate( dot( n, h ) );","float nDotL = saturate( dot( n, l ) );","float nDotV = saturate( dot( n, v ) );","float nDotH2 = nDotH * nDotH;","float m2 = pow( m, 4.0 );","float d = m2 / ( pow( nDotH * nDotH * ( m2 - 1.0 ) + 1.0, 2.0 ) );","float v1i = GGX_SchlickGeometryFactor_V2( m2, nDotL );","float v1o = GGX_SchlickGeometryFactor_V2( m2, nDotV );","float vis = v1i * v1o;","return d * vis;","}","float BlinnPhong_Specular( in float shininess, in float dotLN, in float dotNormalHalf, in vec3 eyeVector, in vec3 normal ) {","float specularNormalization = shininess * 0.125 + 0.25;","float geo = SmithGeometryFactor2( dotLN, eyeVector, normal, shininess );","return ( specularNormalization * geo ) * max( pow( dotNormalHalf, shininess ), 0.0 );","}"].join("\n"),XG.DeferredShaderChunk.computeSpecular=["vec3 eyeVector = normalize( -vertexPositionVS.xyz );","vec3 halfVector = normalize( lightVector + eyeVector );","float dotNormalHalf = max( dot( normal, halfVector ), 0.0 );","float dotLightHalf = max( dot( lightVector, halfVector ), 0.0 );","vec3 fresnel = specularColor + ( 1.0 - specularColor ) * pow( 1.0 - dotLightHalf, 5.0 );","fresnel *= float( dot( specularColor, vec3( 1.0 ) ) > 0.0 );","#if defined( BRDF_BLINN_PHONG )","vec3 specular = BlinnPhong_Specular( shininess, dotLN, dotNormalHalf, eyeVector, normal ) * ( fresnel * dotLN );","#elif defined( BRDF_GGX )","float roughness = saturate( sqrt( 8.0 / ( shininess + 7.0 ) ) );","vec3 specular = GGX_Specular( roughness, normal, halfVector, eyeVector, lightVector ) * ( fresnel * dotLN );","#else","vec3 specular = specularColor * max( pow( dotNormalHalf, shininess ), 0.0 ) * dotLN;","#endif"].join("\n"),XG.DeferredShaderChunk.combine=["vec3 light = lightIntensity * lightColor;","mgl_FragColor = vec4( light * ( albedo * diffuse + specular ), attenuation );"].join("\n"),XG.DeferredShaderChunk.directionalOcclusion=["#ifdef OCCLUSION_ENABLED","uniform mat4 matProj;","float checkOcclusion( in vec3 pointVS ) {","vec4 pointCS = matProj * vec4( pointVS, 1.0 );","pointCS.xyz /= pointCS.w;","vec2 pointUV = pointCS.xy * 0.5 + 0.5;","#ifdef USE_MRT","#ifdef TEXTURE_DEPTH","vec4 depthSample = texture2D( samplerDepth, pointUV );","float sampleZ = depthSample.x * 2.0 - 1.0;","#else","vec4 depthSample = texture2D( samplerDepth, pointUV );","float sampleZ = unpackDepth( depthSample );","#endif","#else","vec4 normalDepthSample = texture2D( samplerNormalDepth, pointUV );","float sampleZ = normalDepthSample.w;","#endif","float occlusion = 1.0;","if ( pointCS.z > sampleZ ) occlusion = 0.0;","return occlusion;","}","vec2 rand( const in vec2 coord ) {","float nx = dot ( coord, vec2( 12.9898, 78.233 ) );","float ny = dot ( coord, vec2( 25.9796, 156.466 ) );","vec2 noise = clamp( fract ( 43758.5453 * sin( vec2( nx, ny ) ) ), 0.0, 1.0 );","return noise;","}","#endif"].join("\n"),XG.DeferredShaderChunk.shadowMapPCFSoft=["#ifdef USE_SHADOWSAMPLER","float sampleShadowPCFSoft( sampler2DShadow shadowMap, vec2 shadowMapSize, vec2 shadowCoord, float vertexDepth ) {","vec2 pixelOffset = vec2( 1.0 ) / shadowMapSize;","float dx0 = -pixelOffset.x;","float dy0 = -pixelOffset.y;","float dx1 =  pixelOffset.x;","float dy1 =  pixelOffset.y;","float shadowValue = 0.0;","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( dx0, dy0 ), vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( 0.0, dy0 ), vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( dx1, dy0 ), vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( dx0, 0.0 ), vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord, 				      vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( dx1, 0.0 ), vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( dx0, dy1 ), vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( 0.0, dy1 ), vertexDepth ) );","shadowValue += texture( shadowMap, vec3( shadowCoord + vec2( dx1, dy1 ), vertexDepth ) );","shadowValue /= 9.0;","return 1.0 - shadowValue;","}","#else","float sampleShadowPCFSoft( sampler2D shadowMap, vec2 shadowMapSize, vec2 shadowCoord, float vertexDepth ) {","vec2 pixelOffset = vec2( 1.0 ) / shadowMapSize;","float dx0 = -pixelOffset.x;","float dy0 = -pixelOffset.y;","float dx1 =  pixelOffset.x;","float dy1 =  pixelOffset.y;","float shadowDepth;","mat3 shadowKernel;","shadowDepth = texture2D( shadowMap, shadowCoord + vec2( dx0, dy0 ) ).x;","shadowKernel[0][0] = float( vertexDepth > shadowDepth );","shadowDepth = texture2D( shadowMap, shadowCoord + vec2( dx0, 0.0 ) ).x;","shadowKernel[0][1] = float( vertexDepth > shadowDepth );","shadowDepth = texture2D( shadowMap, shadowCoord + vec2( dx0, dy1 ) ).x;","shadowKernel[0][2] = float( vertexDepth > shadowDepth );","shadowDepth = texture2D( shadowMap, shadowCoord + vec2( 0.0, dy0 ) ).x;","shadowKernel[1][0] = float( vertexDepth > shadowDepth );","shadowDepth = texture2D( shadowMap, shadowCoord ).x;","shadowKernel[1][1] = float( vertexDepth > shadowDepth );","shadowDepth = texture2D( shadowMap, shadowCoord + vec2( 0.0, dy1 ) ).x;","shadowKernel[1][2] = float( vertexDepth > shadowDepth );","shadowDepth = texture2D( shadowMap, shadowCoord + vec2( dx1, dy0 ) ).x;","shadowKernel[2][0] = float( vertexDepth > shadowDepth );","shadowDepth = texture2D( shadowMap, shadowCoord + vec2( dx1, 0.0 ) ).x;","shadowKernel[2][1] = float( vertexDepth > shadowDepth );","shadowDepth = texture2D( shadowMap, shadowCoord + vec2( dx1, dy1 ) ).x;","shadowKernel[2][2] = float( vertexDepth > shadowDepth );","shadowKernel *= 0.25;","vec2 fractionalCoord = 1.0 - fract( shadowCoord * shadowMapSize );","shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );","shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );","vec4 shadowValues;","shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );","shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );","shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );","shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );","float shadowValue = dot( shadowValues, vec4( 1.0 ) );","return shadowValue;","}","#endif"].join("\n"),XG.DeferredShaderChunk.normalsParsFragment=["#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_NORMALGLOSSMAP ) || defined( USE_DISPLACEMENTMAP )","varying vec3 vViewPosition;","#endif",XG.ShaderChunk.bumpmap_pars_fragment,XG.ShaderChunk.derivativemap_pars_fragment,XG.ShaderChunk.normalmap_pars_fragment,"#if defined( USE_BUMPDETAILMAP ) || defined( USE_NORMALDETAILMAP )","uniform vec3 detailRepeatScale;","#endif","varying vec3 normalView;"].join("\n"),XG.DeferredShaderChunk.normalsFragment=["#if defined( USE_DISPLACEMENTMAP )","normal = perturbNormalArb( vViewPosition, normal, dHdxy_fwd( displacementMap, uvCoord, displacementNormalScale ) );","#endif","#if defined( USE_NORMALMAP ) || defined( USE_NORMALGLOSSMAP )","#ifdef USE_NORMALDETAILMAP","vec4 normalDetail = texture2D( normalDetailMap, uvCoord *  detailRepeatScale.xy ) * 2.0 - 1.0;","normalDetail.rgb = normalize( normalDetail.rgb * vec3( detailRepeatScale.zz, 1.0 ) ) * 0.5 + 0.5;","vec3 n1 = normalGloss.xyz  * vec3(  2.0,  2.0, 2.0 ) + vec3( -1.0, -1.0,  0.0 );","vec3 n2 = normalDetail.xyz * vec3( -2.0, -2.0, 2.0 ) + vec3(  1.0,  1.0, -1.0 );","normalGloss.xyz  = normalize( n1 * dot( n1, n2 ) / n1.z - n2 ) * 0.5 + 0.5;","#endif","normal = perturbNormal2Arb( vViewPosition, normal, normalGloss.xyz, uvCoord );","#elif defined( USE_BUMPMAP )","normal = perturbNormalArb( vViewPosition, normal, dHdxy_fwd( bumpMap, uvCoord, bumpScale ) );","#endif","#ifdef USE_BUMPDETAILMAP","normal = perturbNormalArb( vViewPosition, normal, dHdxy_fwd( bumpDetailMap, uvCoord * detailRepeatScale.xy, detailRepeatScale.z ) );","#endif","#if defined ( USE_NORMALDETAILMAP ) && ! ( defined( USE_NORMALMAP ) || defined( USE_NORMALGLOSSMAP ) )","vec4 normalDetail = texture2D( normalDetailMap, uvCoord * detailRepeatScale.xy ) * 2.0 - 1.0;","normalDetail.rgb = normalize( normalDetail.rgb * vec3( detailRepeatScale.zz, 1.0 ) ) * 0.5 + 0.5;","normal = perturbNormal2Arb( vViewPosition, normal, normalDetail.xyz, uvCoord * detailRepeatScale.xy );","#endif","#ifdef DOUBLE_SIDED","float flipNormal = 2.0 * float( gl_FrontFacing ) - 1.0;","normal = flipNormal * normal;","#endif","normal = normal * 0.5 + 0.5;"].join("\n"),XG.DeferredShaderChunk.colorsFragment=["float shininess = specular.a;","float wrapAround = diffuse.a;","vec4 diffuseColor  = vec4( diffuse.rgb, 1.0 );","vec4 specularColor = vec4( specular.rgb, 1.0 );","#ifdef USE_MAP","#ifdef PARTICLE","vec2 texCoord = vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y );","#else","vec2 texCoord = uvCoord;","#endif","vec4 diffuseMapColor = texture2D( map, texCoord );","diffuseColor *= diffuseMapColor;","#endif","#ifdef ALPHATEST","if ( diffuseColor.a < ALPHATEST ) discard;","#endif","#ifdef USE_COLOR","diffuseColor.rgb *= vColor;","#endif",XG.ShaderChunk.specularmap_fragment,"specularColor.rgb *= specularMapColor;","#ifdef USE_LIGHTMAP","float lightMapIntensity = texture2D( lightMap, uvCoord ).r;","#else","float lightMapIntensity = 1.0;","#endif","#if defined( USE_GLOSSMAP )","vec4 glossMapVal = texture2D( glossMap, uvCoord );","float gloss = exp2( 13.0 * glossMapVal.r + 1.0 );","#elif defined( USE_NORMALGLOSSMAP )","float gloss = exp2( 13.0 * normalGloss.a + 1.0 );","#else","float gloss = 1.0;","#endif","shininess = clamp( shininess * gloss, 0.0, 8192.0 );"].join("\n"),XG.DeferredShaderChunk.hemiTerm=["const float maxShininess = 8192.0;","float gloss = min( shininess / maxShininess, 1.0 );","vec3 fresnelHemi = EnvironmentBRDF( gloss, dot( eyeVector, halfVector ), specularColor );","float dotProductHemi = dot( normal, lightVectorHemi );","float hemiDiffuseWeightUnclamped = 0.5 * dotProductHemi + 0.5;","float hemiDiffuseWeight = clamp( hemiDiffuseWeightUnclamped, 0.0, 1.0 );","vec3 diffuseHemi;","if ( wrapAround < 0.0 ) {","float hemiDiffuseWeightUnclamped2 = -0.5 * dotProductHemi + 0.5;","float hemiDiffuseWeight2 = clamp( hemiDiffuseWeightUnclamped2, 0.0, 1.0 );","diffuseHemi = 0.75 * mix( lightColorGround, lightColorSky, hemiDiffuseWeight ) + 0.25 * mix( lightColorGround, lightColorSky, hemiDiffuseWeight2 );","} else {","diffuseHemi = mix( lightColorGround, lightColorSky, hemiDiffuseWeight );","}","diffuseHemi *= ( 1.0 - fresnelHemi );","vec3 R = reflect( -eyeVector, normal );","R = normalize( R );","float hemiSpecularWeight = clamp( dot( R, lightVectorHemi ) * 0.5 + 0.5, 0.0, 1.0 );","vec3 specularHemi = fresnelHemi * mix( lightColorGround, lightColorSky, hemiSpecularWeight );","vec3 hemiTerm = lightIntensityHemi * ( albedo * diffuseHemi + specularHemi );","hemiTerm *= lightMapIntensity;","#ifdef USE_SSAO","float hemiOcclusion = texture2D( samplerSSAO, texCoord ).x;","hemiTerm *= hemiOcclusion * hemiOcclusion;","#endif"].join("\n"),XG.DeferredShaderChunk.shadowPrep=["float sectorOcclusion = 1.0;","vec4 posLightCS = matShadow[ i ] * vertexPositionVS;","vec2 shadowCoord = ( posLightCS.xy / posLightCS.w ) * 0.5 + 0.5;","bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );","bool inFrustum = all( inFrustumVec );"].join("\n"),XG.DeferredShaderChunk.shadowCheck=["float vertexDepth = posLightCS.z / posLightCS.w;","#if defined( DEPTH_TEXTURES )","vertexDepth = vertexDepth * 0.5 + 0.5;","#endif","#if !defined( SLOPE_DEPTH_BIAS )","vertexDepth -= shadowBias;","#endif","#if defined( SHADOWMAP_TYPE_PCF_SOFT )","float shadowValue = sampleShadowPCFSoft( samplerShadowMap[ i ], shadowMapSize, shadowCoord, vertexDepth );","#elif defined( SHADOWMAP_TYPE_PCF_SOFT_HQ )","vec2 pixelOffset = vec2( 2.0 ) / shadowMapSize;","float shadowValue0 = sampleShadowPCFSoft( samplerShadowMap[ i ], shadowMapSize, shadowCoord + vec2( -pixelOffset.x, 0.0 ), vertexDepth );","float shadowValue1 = sampleShadowPCFSoft( samplerShadowMap[ i ], shadowMapSize, shadowCoord + vec2(  pixelOffset.x, 0.0 ), vertexDepth );","float shadowValue2 = sampleShadowPCFSoft( samplerShadowMap[ i ], shadowMapSize, shadowCoord + vec2( 0.0, -pixelOffset.y ), vertexDepth );","float shadowValue3 = sampleShadowPCFSoft( samplerShadowMap[ i ], shadowMapSize, shadowCoord + vec2( 0.0,  pixelOffset.y ), vertexDepth );","float shadowValue = ( shadowValue0 + shadowValue1 + shadowValue2 + shadowValue3 ) * 0.25;","#else","#ifdef USE_SHADOWSAMPLER","float shadowValue = 1.0 - texture( samplerShadowMap[ i ], vec3( shadowCoord, vertexDepth ) );","#else","float shadowDepth = texture2D( samplerShadowMap[ i ], shadowCoord ).x;","float shadowValue = float( vertexDepth > shadowDepth );","#endif","#endif","sectorOcclusion = 1.0 - shadowDarkness * shadowValue;","occlusion *= sectorOcclusion;"].join("\n"),XG.DeferredShaderChunk.directionalShadows=["float occlusion = 1.0;","#ifdef USE_SHADOWMAP","#ifdef SHADOWMAP_DEBUG","vec3 frustumColors[5];","frustumColors[0] = vec3( 1.0, 0.0, 0.0 );","frustumColors[1] = vec3( 0.0, 1.0, 0.0 );","frustumColors[2] = vec3( 0.0, 0.0, 1.0 );","frustumColors[3] = vec3( 0.0, 0.5, 1.0 );","frustumColors[4] = vec3( 0.2, 0.5, 1.0 );","vec3 debugColor = vec3( 1.0 );","#endif","#ifdef OSX_HACK","bool found = false;","#endif","for ( int i = 0; i < SHADOWMAP_COUNT; i ++ ) {",XG.DeferredShaderChunk.shadowPrep,"#ifdef OSX_HACK","if ( inFrustum && !found ) {","#else","if ( inFrustum ) {","#endif",XG.DeferredShaderChunk.shadowCheck,"#ifdef SHADOWMAP_DEBUG","debugColor *= frustumColors[ i ];","#endif","#if SHADOWMAP_COUNT > 1","#ifdef OSX_HACK","found = true;","#else","break;","#endif","#endif","}","}","#endif"].join("\n"),XG.DeferredShaderChunk.directionalProjectedTexture=["#ifdef PROJECTED_TEXTURE","vec4 posTextureCS = matTexture * vertexPositionVS;","#ifdef PROJECTED_SHADOW","vec2 textureCoord = ( posTextureCS.xy / posTextureCS.w ) * 0.5 + 0.5;","bvec4 inTexFrustumVec = bvec4 ( textureCoord.x >= 0.0, textureCoord.x <= 1.0, textureCoord.y >= 0.0, textureCoord.y <= 1.0 );","bool inTexFrustum = all( inTexFrustumVec );","if ( inTexFrustum ) {","vec4 textureColor = texture2DProj( samplerTexture, posTextureCS, textureBias );","float translucency = 1.0 - textureColor.r * shadowDarkness;","occlusion = min( occlusion, translucency );","}","#else","vec4 textureColor = texture2DProj( samplerTexture, posTextureCS, textureBias );","textureColor.rgb *= textureColor.rgb;","diffuse *= textureColor.rgb;","specular *= textureColor.rgb;","#endif","#endif"].join("\n"),XG.DeferredShaders.combined={uniforms:XG.UniformsUtils.merge([XG.UniformsLib.common,XG.UniformsLib.particle,XG.UniformsLib.bump,XG.UniformsLib.normalmap,XG.UniformsLib.displacement,{diffuse:{type:"v4",value:new XG.Vector4(1,1,1,1)},specular:{type:"v4",value:new XG.Vector4(.1,.1,.1,30)},wrapRGB:{type:"v3",value:new XG.Vector3(1,1,1)},detailRepeatScale:{type:"v3",value:new XG.Vector3(1,1,1)},glossMap:{type:"t",value:null},specularMap:{type:"t",value:null},parallaxScale:{type:"f",value:1}}]),fragmentShader:["uniform vec4 diffuse;","uniform vec4 specular;","uniform vec3 wrapRGB;","#ifndef TEXTURE_DEPTH","varying vec4 clipPos;","#endif",XG.DeferredShaderChunk.normalsParsFragment,XG.DeferredShaderChunk.packFloat,XG.ShaderChunk.color_pars_fragment,XG.ShaderChunk.map_pars_fragment,XG.ShaderChunk.lightmap_pars_fragment,XG.ShaderChunk.specularmap_pars_fragment,XG.ShaderChunk.glossmap_pars_fragment,XG.ShaderChunk.parallax_pars_fragment,XG.ShaderChunk.displacementmap_pars_fragment,"void main() {","#if !defined( PARTICLE ) && ( defined( USE_MAP ) || defined( USE_LIGHTMAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined ( USE_NORMALGLOSSMAP ) || defined ( USE_GLOSSMAP ) || defined( USE_SPECULARMAP ) || defined( USE_DISPLACEMENTMAP ) )","vec2 uvCoord = vUv;","#endif","vec3 normal = normalize( normalView );","#if defined( USE_BUMPMAP ) && defined( USE_PARALLAX )","vec3 eyeVector = normalize( -vViewPosition );","#endif",XG.ShaderChunk.parallax_fragment,"#if defined( USE_NORMALGLOSSMAP ) || defined( USE_NORMALMAP )","vec4 normalGloss = texture2D( normalMap, uvCoord );","#endif",XG.DeferredShaderChunk.normalsFragment,XG.DeferredShaderChunk.colorsFragment,"float shininessLo = fract( shininess / 256.0 );","float shininessHi = floor( shininess / 256.0 ) / 256.0;","mgl_FragData[ 0 ] = vec4( diffuseColor.rgb, shininessLo );","mgl_FragData[ 1 ] = vec4( specularColor.rgb, shininessHi );","mgl_FragData[ 2 ] = vec4( wrapRGB.rgb, wrapAround + 0.5 );","mgl_FragData[ 3 ] = vec4( normal.xyz, lightMapIntensity );","#ifndef TEXTURE_DEPTH","mgl_FragData[ 4 ] = vec4( packDepth( clipPos.z / clipPos.w ) );","#endif","}"].join("\n"),vertexShader:[XG.ShaderChunk.instances_pars_vertex,XG.ShaderChunk.map_pars_vertex,XG.ShaderChunk.color_pars_vertex,XG.ShaderChunk.morphtarget_pars_vertex,XG.ShaderChunk.skinning_pars_vertex,XG.ShaderChunk.particle_pars_vertex,XG.ShaderChunk.displacement_pars_vertex,"#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_NORMALGLOSSMAP ) || defined( USE_DISPLACEMENTMAP )","varying vec3 vViewPosition;","#endif","varying vec3 normalView;","#ifndef TEXTURE_DEPTH","varying vec4 clipPos;","#endif","void main() {",XG.ShaderChunk.map_vertex,XG.ShaderChunk.begin_nor_vertex,XG.ShaderChunk.morphnormal_vertex,XG.ShaderChunk.skinbase_vertex,XG.ShaderChunk.skinnormal_vertex,XG.ShaderChunk.end_nor_vertex,XG.ShaderChunk.begin_pos_vertex,XG.ShaderChunk.displacement_vertex,XG.ShaderChunk.morphtarget_vertex,XG.ShaderChunk.skinning_vertex,XG.ShaderChunk.default_vertex,XG.ShaderChunk.end_pos_vertex,XG.ShaderChunk.particle_vertex,"normalView = transformedNormal;","#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_NORMALGLOSSMAP ) || defined( USE_DISPLACEMENTMAP )","vViewPosition = mvPosition.xyz;","#endif","#ifdef USE_COLOR","vColor = color;","#endif","#ifndef TEXTURE_DEPTH","clipPos = gl_Position;","#endif","}"].join("\n")},XG.DeferredShaders.color={uniforms:XG.UniformsUtils.merge([XG.UniformsLib.common,XG.UniformsLib.particle,XG.UniformsLib.displacement,{diffuse:{type:"v4",value:new XG.Vector4(1,1,1,1)},specular:{type:"v4",value:new XG.Vector4(.1,.1,.1,30)},wrapRGB:{type:"v3",value:new XG.Vector3(1,1,1)},glossMap:{type:"t",value:null},specularMap:{type:"t",value:null},normalMap:{type:"t",value:null},bumpMap:{type:"t",value:null},samplerNormalDepth:{type:"t",value:null,shared:!0},viewSize:{type:"v2",value:new XG.Vector2(800,600),shared:!0},parallaxScale:{type:"f",value:1}}]),fragmentShader:["uniform vec4 diffuse;","uniform vec4 specular;","uniform vec3 wrapRGB;",XG.ShaderChunk.color_pars_fragment,XG.ShaderChunk.map_pars_fragment,XG.ShaderChunk.lightmap_pars_fragment,"#ifdef USE_NORMALGLOSSMAP","uniform sampler2D normalMap;","#endif","#if defined( USE_PARALLAX ) && defined( USE_BUMPMAP )","uniform sampler2D bumpMap;","varying vec3 normalView;","varying vec3 vViewPosition;","#endif",XG.ShaderChunk.glossmap_pars_fragment,XG.ShaderChunk.specularmap_pars_fragment,XG.ShaderChunk.parallax_pars_fragment,XG.DeferredShaderChunk.packFloat,"void main() {","#if !defined( PARTICLE ) && ( defined( USE_MAP ) || defined( USE_LIGHTMAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined ( USE_NORMALGLOSSMAP ) || defined ( USE_GLOSSMAP ) || defined( USE_SPECULARMAP ) )","vec2 uvCoord = vUv;","#endif","#if defined( USE_PARALLAX ) && defined( USE_BUMPMAP )","vec3 normal = normalize( normalView );","vec3 eyeVector = normalize( -vViewPosition );","#endif",XG.ShaderChunk.parallax_fragment,"#ifdef USE_NORMALGLOSSMAP","vec4 normalGloss = texture2D( normalMap, uvCoord );","#endif",XG.DeferredShaderChunk.colorsFragment,"float compressedDiffuse = vec3_to_float( diffuseColor.rgb );","float compressedSpecular = vec3_to_float( specularColor.rgb );","float compressedWrapRGB = vec3_to_float( wrapRGB.rgb );","float wrapAroundShininessOcclusion = wrapAround * vec21_to_float( shininess, lightMapIntensity );","mgl_FragColor = vec4( compressedDiffuse, compressedSpecular, wrapAroundShininessOcclusion, compressedWrapRGB );","}"].join("\n"),vertexShader:[XG.ShaderChunk.instances_pars_vertex,XG.ShaderChunk.map_pars_vertex,XG.ShaderChunk.color_pars_vertex,XG.ShaderChunk.morphtarget_pars_vertex,XG.ShaderChunk.skinning_pars_vertex,XG.ShaderChunk.particle_pars_vertex,XG.ShaderChunk.displacement_pars_vertex,"#if defined( USE_PARALLAX ) && defined( USE_BUMPMAP )","varying vec3 normalView;","varying vec3 vViewPosition;","#endif","void main() {",XG.ShaderChunk.map_vertex,XG.ShaderChunk.begin_nor_vertex,XG.ShaderChunk.morphnormal_vertex,XG.ShaderChunk.skinbase_vertex,XG.ShaderChunk.skinnormal_vertex,XG.ShaderChunk.end_nor_vertex,XG.ShaderChunk.begin_pos_vertex,XG.ShaderChunk.displacement_vertex,XG.ShaderChunk.morphtarget_vertex,XG.ShaderChunk.skinning_vertex,XG.ShaderChunk.end_pos_vertex,XG.ShaderChunk.particle_vertex,"#if defined( USE_PARALLAX ) && defined( USE_BUMPMAP )","normalView = transformedNormal;","vViewPosition = mvPosition.xyz;","#endif","#ifdef USE_COLOR","vColor = color;","#endif","}"].join("\n")},XG.DeferredShaders.normalDepth={uniforms:XG.UniformsUtils.merge([XG.UniformsLib.particle,XG.UniformsLib.bump,XG.UniformsLib.normalmap,XG.UniformsLib.displacement,{alphaMap:{type:"t",value:null},detailRepeatScale:{type:"v3",value:new XG.Vector3(1,1,1)},offsetRepeat:{type:"v4",value:new XG.Vector4(0,0,1,1)},parallaxScale:{type:"f",value:1}}]),fragmentShader:["#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_NORMALGLOSSMAP ) || defined( ALPHATEST ) || defined( USE_DISPLACEMENTMAP )","varying vec2 vUv;","#endif","#ifdef ALPHATEST","uniform sampler2D alphaMap;","#endif",XG.DeferredShaderChunk.normalsParsFragment,XG.ShaderChunk.parallax_pars_fragment,XG.ShaderChunk.displacementmap_pars_fragment,"varying vec4 clipPos;","void main() {","#if !defined( PARTICLE ) && ( defined( USE_MAP ) || defined( USE_LIGHTMAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined ( USE_NORMALGLOSSMAP ) || defined ( USE_GLOSSMAP ) || defined( USE_SPECULARMAP ) || defined( ALPHATEST ) || defined( USE_DISPLACEMENTMAP ) )","vec2 uvCoord = vUv;","#endif","vec3 normal = normalize( normalView );","#if defined( USE_BUMPMAP ) && defined( USE_PARALLAX )","vec3 eyeVector = normalize( -vViewPosition );","#endif",XG.ShaderChunk.parallax_fragment,"#ifdef ALPHATEST","vec2 textureCoord;","#ifdef PARTICLE","textureCoord = vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y );","#else","textureCoord = uvCoord;","#endif","float alphaValue = texture2D( alphaMap, textureCoord ).a;","if ( alphaValue < ALPHATEST ) discard;","#endif","#if defined( USE_NORMALMAP ) || defined( USE_NORMALGLOSSMAP )","vec4 normalGloss = texture2D( normalMap, uvCoord );","#endif",XG.DeferredShaderChunk.normalsFragment,"mgl_FragColor = vec4( normal, clipPos.z / clipPos.w );","}"].join("\n"),vertexShader:["varying vec3 normalView;","varying vec4 clipPos;","#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_NORMALGLOSSMAP ) || defined( ALPHATEST )","varying vec2 vUv;","uniform vec4 offsetRepeat;","#endif","#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_NORMALGLOSSMAP )","varying vec3 vViewPosition;","#endif",XG.ShaderChunk.instances_pars_vertex,XG.ShaderChunk.morphtarget_pars_vertex,XG.ShaderChunk.skinning_pars_vertex,XG.ShaderChunk.particle_pars_vertex,XG.ShaderChunk.displacement_pars_vertex,"void main() {",XG.ShaderChunk.map_vertex,XG.ShaderChunk.begin_nor_vertex,XG.ShaderChunk.morphnormal_vertex,XG.ShaderChunk.skinbase_vertex,XG.ShaderChunk.skinnormal_vertex,XG.ShaderChunk.end_nor_vertex,XG.ShaderChunk.begin_pos_vertex,XG.ShaderChunk.displacement_vertex,XG.ShaderChunk.morphtarget_vertex,XG.ShaderChunk.skinning_vertex,XG.ShaderChunk.end_pos_vertex,XG.ShaderChunk.particle_vertex,"normalView = transformedNormal;","#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_NORMALGLOSSMAP ) || defined( USE_DISPLACEMENTMAP )","vViewPosition = mvPosition.xyz;","#endif","clipPos = gl_Position;","}"].join("\n")},XG.DeferredShaders.depth={uniforms:XG.UniformsUtils.merge([XG.UniformsLib.particle,XG.UniformsLib.displacement,{slopeScale:{type:"f",value:2,shared:!0},slopeBias:{type:"f",value:0,shared:!0},slopeMax:{type:"f",value:.001,shared:!0},depthTextureBias:{type:"f",value:5e-4,shared:!0},alphaMap:{type:"t",value:null},offsetRepeat:{type:"v4",value:new XG.Vector4(0,0,1,1)}}]),fragmentShader:["#ifdef ALPHATEST","uniform sampler2D alphaMap;","varying vec2 vUv;","#endif","#ifndef DEPTH_TEXTURES","#ifdef SLOPE_DEPTH_BIAS","uniform float slopeScale;","uniform float slopeBias;","uniform float slopeMax;","#endif","varying vec4 clipPos;","#endif","void main() {","#ifdef ALPHATEST","float alphaValue = texture2D( alphaMap, vUv ).a;","if ( alphaValue < ALPHATEST ) discard;","#endif","#ifndef DEPTH_TEXTURES","float depth = clipPos.z / clipPos.w;","#ifdef SLOPE_DEPTH_BIAS","float dx = dFdx( depth );","float dy = dFdy( depth );","float m = max( abs(dx), abs(dy) );","m = min( m, slopeMax );","mgl_FragColor.x = depth + m * slopeScale + slopeBias;","#else","mgl_FragColor.x = depth;","#endif","#endif","}"].join("\n"),vertexShader:["#ifdef ALPHATEST","varying vec2 vUv;","#endif","#if defined( ALPHATEST ) || defined( USE_DISPLACEMENTMAP )","uniform vec4 offsetRepeat;","#endif","#ifdef DEPTH_TEXTURES","uniform float depthTextureBias;","#else","varying vec4 clipPos;","#endif",XG.ShaderChunk.instances_pars_vertex,XG.ShaderChunk.morphtarget_pars_vertex,XG.ShaderChunk.skinning_pars_vertex,XG.ShaderChunk.particle_pars_vertex,XG.ShaderChunk.displacement_pars_vertex,"void main() {","#if defined( ALPHATEST ) || defined( USE_DISPLACEMENTMAP )","vec2 transformedUV = uv * offsetRepeat.zw + offsetRepeat.xy;","#endif",XG.ShaderChunk.skinbase_vertex,XG.ShaderChunk.begin_pos_vertex,XG.ShaderChunk.displacement_vertex,XG.ShaderChunk.morphtarget_vertex,XG.ShaderChunk.skinning_vertex,XG.ShaderChunk.end_pos_vertex,XG.ShaderChunk.particle_vertex,"#ifndef DEPTH_TEXTURES","clipPos = gl_Position;","#else","gl_Position.z += depthTextureBias;","#endif","#ifdef ALPHATEST","vUv = transformedUV;","#endif","}"].join("\n")},XG.DeferredShaders.pointLight={uniforms:XG.UniformsUtils.merge([XG.DeferredUniformsLib.gbuffers,XG.DeferredUniformsLib.multiShadowMaps,{matProjInverse:{type:"m4",value:new XG.Matrix4,shared:!0},lightPositionVS:{type:"v3",value:new XG.Vector3(0,0,0)},lightColor:{type:"c",value:new XG.Color(0)},lightIntensity:{type:"f",value:1},lightDistance:{type:"f",value:1}}]),fragmentShader:["uniform float lightDistance;","uniform float lightIntensity;","uniform vec3 lightColor;","uniform vec3 lightPositionVS;","uniform mat4 matProjInverse;",XG.ShaderChunk.utils_pars_fragment,XG.ShaderChunk.skin_pars_fragment,XG.DeferredShaderChunk.multiShadowMapsUniforms,XG.DeferredShaderChunk.gbuffersUniforms,XG.DeferredShaderChunk.unpackFloat,XG.DeferredShaderChunk.shadowMapPCFSoft,XG.DeferredShaderChunk.geometryFactor,XG.DeferredShaderChunk.specularBRDF,"void main() {",XG.DeferredShaderChunk.computeVertexPositionVS,"vec3 lightVector = lightPositionVS - vertexPositionVS.xyz;","float distance = length( lightVector );","if ( distance > lightDistance ) discard;",XG.DeferredShaderChunk.computeNormal,XG.DeferredShaderChunk.unpackColorMap,"lightVector = lightVector / distance;",XG.DeferredShaderChunk.computeDiffuse,XG.DeferredShaderChunk.computeSpecular,"diffuse -= diffuse * fresnel;","const float cutoff = 0.3;","float denom = distance / lightDistance + 1.0;","float attenuation = 1.0 / ( denom * denom );","attenuation = ( attenuation - cutoff ) / ( 1.0 - cutoff );","attenuation = max( attenuation, 0.0 );","attenuation *= attenuation;","float occlusion = 1.0;","#ifdef USE_SHADOWMAP","for ( int i = 0; i < SHADOWMAP_COUNT; i ++ ) {",XG.DeferredShaderChunk.shadowPrep,"if ( inFrustum && posLightCS.z >= 0.0 ) {",XG.DeferredShaderChunk.shadowCheck,"#ifndef OSX_HACK","break;","#endif","}","}","#endif","attenuation *= occlusion;",XG.DeferredShaderChunk.combine,"}"].join("\n"),vertexShader:XG.ShaderChunk.vertexShaderGeometry},XG.DeferredShaders.sphereLight={uniforms:XG.UniformsUtils.merge([XG.DeferredUniformsLib.gbuffers,XG.DeferredUniformsLib.multiShadowMaps,{matProjInverse:{type:"m4",value:new XG.Matrix4,shared:!0},lightPositionVS:{type:"v3",value:new XG.Vector3(0,0,0)},lightColor:{type:"c",value:new XG.Color(0)},lightIntensity:{type:"f",value:1},lightDistance:{type:"f",value:1},lightRadius:{type:"f",value:1}}]),fragmentShader:["uniform float lightRadius;","uniform float lightDistance;","uniform float lightIntensity;","uniform vec3 lightColor;","uniform vec3 lightPositionVS;","uniform mat4 matProjInverse;",XG.ShaderChunk.utils_pars_fragment,XG.ShaderChunk.skin_pars_fragment,XG.DeferredShaderChunk.multiShadowMapsUniforms,XG.DeferredShaderChunk.gbuffersUniforms,XG.DeferredShaderChunk.unpackFloat,XG.DeferredShaderChunk.shadowMapPCFSoft,XG.DeferredShaderChunk.geometryFactor,XG.DeferredShaderChunk.specularBRDF,"void main() {",XG.DeferredShaderChunk.computeVertexPositionVS,"vec3 lightVectorFull = lightPositionVS - vertexPositionVS.xyz;","float distance = length( lightVectorFull );","if ( distance > lightDistance ) discard;",XG.DeferredShaderChunk.computeNormal,XG.DeferredShaderChunk.unpackColorMap,"vec3 lightVector = lightVectorFull / distance;",XG.DeferredShaderChunk.computeDiffuse,"vec3 eye = normalize( -vertexPositionVS.xyz );","vec3 reflectVS = reflect( eye, normal );","vec3 centerToRay = lightVectorFull - dot( lightVectorFull, reflectVS ) * reflectVS;","vec3 closestPoint = lightVectorFull - centerToRay * saturate( lightRadius / length( centerToRay ) );","lightVector = normalize( closestPoint );","dotLN = max( dot( lightVector, normal ), 0.0 );",XG.DeferredShaderChunk.computeSpecular,"float alpha = roughness * roughness;","float alphaPrime = saturate( alpha + 0.5 * saturate( lightRadius / distance ) );","float sphereNormalization = alpha / alphaPrime;","sphereNormalization *= sphereNormalization;","specular *= sphereNormalization;","diffuse -= diffuse * fresnel;","const float cutoff = 0.3;","float denom = distance / lightDistance + 1.0;","float attenuation = 1.0 / ( denom * denom );","attenuation = ( attenuation - cutoff ) / ( 1.0 - cutoff );","attenuation = max( attenuation, 0.0 );","attenuation *= attenuation;","float occlusion = 1.0;","#ifdef USE_SHADOWMAP","for ( int i = 0; i < SHADOWMAP_COUNT; i ++ ) {",XG.DeferredShaderChunk.shadowPrep,"if ( inFrustum && posLightCS.z >= 0.0 ) {",XG.DeferredShaderChunk.shadowCheck,"#ifndef OSX_HACK","break;","#endif","}","}","#endif","attenuation *= occlusion;",XG.DeferredShaderChunk.combine,"}"].join("\n"),vertexShader:XG.ShaderChunk.vertexShaderGeometry},XG.DeferredShaders.tubeLight={uniforms:XG.UniformsUtils.merge([XG.DeferredUniformsLib.gbuffers,{matProj:{type:"m4",value:new XG.Matrix4,shared:!0},matProjInverse:{type:"m4",value:new XG.Matrix4,shared:!0},lightPosition0VS:{type:"v3",value:new XG.Vector3(0,-1,0)},lightPosition1VS:{type:"v3",value:new XG.Vector3(0,1,0)},lightColor:{type:"c",value:new XG.Color(0)},lightIntensity:{type:"f",value:1},lightDistance:{type:"f",value:1},lightRadius:{type:"f",value:1}}]),fragmentShader:["uniform float lightRadius;","uniform float lightDistance;","uniform float lightIntensity;","uniform vec3 lightColor;","uniform vec3 lightPosition0VS;","uniform vec3 lightPosition1VS;","uniform mat4 matProjInverse;",XG.ShaderChunk.utils_pars_fragment,XG.DeferredShaderChunk.multiShadowMapsUniforms,XG.DeferredShaderChunk.gbuffersUniforms,XG.DeferredShaderChunk.unpackFloat,XG.DeferredShaderChunk.geometryFactor,XG.DeferredShaderChunk.specularBRDF,XG.DeferredShaderChunk.directionalOcclusion,"void main() {",XG.DeferredShaderChunk.computeVertexPositionVS,XG.DeferredShaderChunk.computeNormal,XG.DeferredShaderChunk.unpackColorMap,"vec3 lightVector0 = lightPosition0VS - vertexPositionVS.xyz;","vec3 lightVector1 = lightPosition1VS - vertexPositionVS.xyz;","float length0 = length( lightVector0 );","float length1 = length( lightVector1 );","float a = saturate( 0.5 * ( dot( normal, lightVector0 ) / length0 + dot( normal, lightVector1 ) / length1 ) );","float b = ( length0 * length1 + dot( lightVector0, lightVector1 ) ) * 0.5 + 1.0;","float dotLN = a;","vec3 diffuse = vec3( dotLN );","vec3 eye = normalize( -vertexPositionVS.xyz );","vec3 reflectVS = reflect( eye, normal );","vec3 lightVectorD = lightVector1 - lightVector0;","float lengthD = length( lightVectorD );","float dotRD = dot( reflectVS, lightVectorD );","float ta = dot( reflectVS, lightVector0 ) * dotRD - dot( lightVector0, lightVectorD );","float tb = lengthD * lengthD - dotRD * dotRD;","float t = ta / tb;","vec3 closestPoint = lightVector0 + saturate( t ) * lightVectorD;","vec3 lightVectorClosest = closestPoint;","vec3 centerToRay = lightVectorClosest - dot( lightVectorClosest, reflectVS ) * reflectVS;","closestPoint = lightVectorClosest - centerToRay * saturate( lightRadius / length( centerToRay ) );","vec3 lightVector = normalize( closestPoint );",XG.DeferredShaderChunk.computeSpecular,"vec3 lightVectorFull = ( lightPosition0VS + lightPosition1VS ) * 0.5 - vertexPositionVS.xyz;","float distance = length( lightVectorFull );","float alpha = roughness * roughness;","float alphaPrime = saturate( alpha + 0.5 * saturate( lightRadius / distance ) );","float sphereNormalization = alpha / alphaPrime;","sphereNormalization *= sphereNormalization;","float alphaPrimeLine = saturate( alpha + 0.5 * saturate( lengthD / distance ) );","float lineNormalization = alpha / alphaPrimeLine;","specular *= sphereNormalization;","specular *= lineNormalization;","diffuse -= diffuse * fresnel;","#ifdef OCCLUSION_ENABLED","const float occlusionScale = 0.9;","vec2 r = rand( texCoord ) + 0.1;","float occlusionDistanceC = occlusionScale * r.x;","float occlusionDistance0 = occlusionScale * r.y;","float occlusionDistance1 = occlusionScale * rand( texCoord + 0.01 ).y + 0.1;","float occlusionC = checkOcclusion( vertexPositionVS.xyz + occlusionDistanceC * lightVector );","float occlusion0 = checkOcclusion( vertexPositionVS.xyz + occlusionDistance0 * lightVector0 / length0 );","float occlusion1 = checkOcclusion( vertexPositionVS.xyz + occlusionDistance1 * lightVector1 / length1 );","float occlusion = ( 0.5 * occlusionC + 0.25 * occlusion0 + 0.25 * occlusion1 );","#else","float occlusion = 1.0;","#endif","float attenuation = 1.0 / b;","attenuation *= occlusion;",XG.DeferredShaderChunk.combine,"}"].join("\n"),vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangle},XG.DeferredShaders.spotLight={uniforms:XG.UniformsUtils.merge([XG.DeferredUniformsLib.gbuffers,XG.DeferredUniformsLib.projectedTexture,{matProjInverse:{type:"m4",value:new XG.Matrix4,shared:!0},lightPositionVS:{type:"v3",value:new XG.Vector3(0,1,0)},lightDirectionVS:{type:"v3",value:new XG.Vector3(0,1,0)},lightColor:{type:"c",value:new XG.Color(0)},lightIntensity:{type:"f",value:1},lightDistance:{type:"f",value:1},lightAngleCos:{type:"f",value:1},matShadow:{type:"m4",value:new XG.Matrix4},samplerShadowMap:{type:"t",value:null},shadowMapSize:{type:"v2",value:new XG.Vector2(512,512)},shadowDarkness:{type:"f",value:.5},shadowBias:{type:"f",value:0}}]),fragmentShader:["uniform vec3 lightPositionVS;","uniform vec3 lightDirectionVS;","uniform vec3 lightColor;","uniform float lightIntensity;","uniform float lightAngleCos;","uniform mat4 matProjInverse;","#ifdef USE_SHADOWMAP","uniform mat4 matShadow;","#ifdef USE_SHADOWSAMPLER","uniform sampler2DShadow samplerShadowMap;","#else","uniform sampler2D samplerShadowMap;","#endif","uniform float shadowBias;","uniform float shadowDarkness;","uniform vec2 shadowMapSize;","#endif",XG.ShaderChunk.utils_pars_fragment,XG.ShaderChunk.skin_pars_fragment,XG.DeferredShaderChunk.gbuffersUniforms,XG.DeferredShaderChunk.projectedTextureUniforms,XG.DeferredShaderChunk.unpackFloat,XG.DeferredShaderChunk.shadowMapPCFSoft,XG.DeferredShaderChunk.geometryFactor,XG.DeferredShaderChunk.specularBRDF,"void main() {",XG.DeferredShaderChunk.computeVertexPositionVS,XG.DeferredShaderChunk.computeNormal,XG.DeferredShaderChunk.unpackColorMap,"vec3 lightVector = normalize( lightPositionVS.xyz - vertexPositionVS.xyz );","float rho = dot( lightDirectionVS, lightVector );","if ( rho <= lightAngleCos ) discard;","float theta = lightAngleCos + 0.0001;","float phi = lightAngleCos + 0.05;","const float falloff = 4.0;","float spot = 0.0;","if ( rho >= phi ) {","spot = 1.0;","} else if ( rho <= theta ) {","spot = 0.0;","} else { ","spot = pow( ( rho - theta ) / ( phi - theta ), falloff );","}",XG.DeferredShaderChunk.computeDiffuse,XG.DeferredShaderChunk.computeSpecular,"diffuse *= spot;","specular *= spot;","diffuse -= diffuse * fresnel;","float occlusion = 1.0;","#ifdef USE_SHADOWMAP","vec4 posLightCS = matShadow * vertexPositionVS;","vec2 shadowCoord = ( posLightCS.xy / posLightCS.w ) * 0.5 + 0.5;","float vertexDepth = posLightCS.z / posLightCS.w;","#if defined( DEPTH_TEXTURES )","vertexDepth = vertexDepth * 0.5 + 0.5;","#endif","#if !defined( SLOPE_DEPTH_BIAS )","vertexDepth -= shadowBias;","#endif","#if defined( SHADOWMAP_TYPE_PCF_SOFT )","float shadowValue = sampleShadowPCFSoft( samplerShadowMap, shadowMapSize, shadowCoord, vertexDepth );","#elif defined( SHADOWMAP_TYPE_PCF_SOFT_HQ )","vec2 pixelOffset = vec2( 2.0 ) / shadowMapSize;","float shadowValue0 = sampleShadowPCFSoft( samplerShadowMap, shadowMapSize, shadowCoord + vec2( -pixelOffset.x, 0.0 ), vertexDepth );","float shadowValue1 = sampleShadowPCFSoft( samplerShadowMap, shadowMapSize, shadowCoord + vec2(  pixelOffset.x, 0.0 ), vertexDepth );","float shadowValue2 = sampleShadowPCFSoft( samplerShadowMap, shadowMapSize, shadowCoord + vec2( 0.0, -pixelOffset.y ), vertexDepth );","float shadowValue3 = sampleShadowPCFSoft( samplerShadowMap, shadowMapSize, shadowCoord + vec2( 0.0,  pixelOffset.y ), vertexDepth );","float shadowValue = ( shadowValue0 + shadowValue1 + shadowValue2 + shadowValue3 ) * 0.25;","#else","#ifdef USE_SHADOWSAMPLER","float shadowValue = 1.0 - texture( samplerShadowMap, vec3( shadowCoord, vertexDepth ) );","#else","float shadowDepth = texture2D( samplerShadowMap, shadowCoord ).x;","float shadowValue = float( vertexDepth > shadowDepth );","#endif","#endif","occlusion = 1.0 - shadowDarkness * shadowValue;","#endif","#ifdef PROJECTED_TEXTURE","vec4 posTextureCS = matTexture * vertexPositionVS;","#ifdef PROJECTED_SHADOW","vec2 textureCoord = ( posTextureCS.xy / posTextureCS.w ) * 0.5 + 0.5;","bvec4 inTexFrustumVec = bvec4 ( textureCoord.x >= 0.0, textureCoord.x <= 1.0, textureCoord.y >= 0.0, textureCoord.y <= 1.0 );","bool inTexFrustum = all( inTexFrustumVec );","if ( inTexFrustum ) {","vec4 textureColor = texture2DProj( samplerTexture, posTextureCS, textureBias );","float translucency = 1.0 - textureColor.r * shadowDarkness;","occlusion = min( occlusion, translucency );","}","#else","vec4 textureColor = texture2DProj( samplerTexture, posTextureCS );","textureColor.xyz *= textureColor.xyz;","diffuse *= textureColor.xyz;","specular *= textureColor.xyz;","#endif","#endif","float attenuation = occlusion;",XG.DeferredShaderChunk.combine,"}"].join("\n"),vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangle},XG.DeferredShaders.directionalLight={uniforms:XG.UniformsUtils.merge([XG.DeferredUniformsLib.gbuffers,XG.DeferredUniformsLib.multiShadowMaps,XG.DeferredUniformsLib.projectedTexture,{matProjInverse:{type:"m4",value:new XG.Matrix4,shared:!0},lightDirectionVS:{type:"v3",value:new XG.Vector3(0,1,0)},lightColor:{type:"c",value:new XG.Color(0)},lightIntensity:{type:"f",value:1}}]),fragmentShader:["uniform float lightIntensity;","uniform vec3 lightColor;","uniform vec3 lightDirectionVS;","uniform mat4 matProjInverse;",XG.ShaderChunk.utils_pars_fragment,XG.ShaderChunk.skin_pars_fragment,XG.DeferredShaderChunk.multiShadowMapsUniforms,XG.DeferredShaderChunk.gbuffersUniforms,XG.DeferredShaderChunk.projectedTextureUniforms,XG.DeferredShaderChunk.unpackFloat,XG.DeferredShaderChunk.shadowMapPCFSoft,XG.DeferredShaderChunk.geometryFactor,XG.DeferredShaderChunk.specularBRDF,"void main() {",XG.DeferredShaderChunk.computeVertexPositionVS,XG.DeferredShaderChunk.computeNormal,XG.DeferredShaderChunk.unpackColorMap,"vec3 lightVector = lightDirectionVS;",XG.DeferredShaderChunk.computeDiffuse,XG.DeferredShaderChunk.computeSpecular,XG.DeferredShaderChunk.directionalShadows,XG.DeferredShaderChunk.directionalProjectedTexture,"diffuse -= diffuse * fresnel;","float attenuation = occlusion;",XG.DeferredShaderChunk.combine,"#ifdef SHADOWMAP_DEBUG","mgl_FragColor.xyz *= debugColor;","#endif","}"].join("\n"),vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangle},XG.DeferredShaders.hemisphereLight={uniforms:XG.UniformsUtils.merge([XG.DeferredUniformsLib.gbuffers,{matProjInverse:{type:"m4",value:new XG.Matrix4,shared:!0},lightDirectionVS:{type:"v3",value:new XG.Vector3(0,1,0)},lightColorSky:{type:"c",value:new XG.Color(0)},lightColorGround:{type:"c",value:new XG.Color(0)},lightIntensity:{type:"f",value:1},samplerSSAO:{type:"t",value:null}}]),fragmentShader:["uniform float lightIntensity;","uniform vec3 lightColorSky;","uniform vec3 lightColorGround;","uniform vec3 lightDirectionVS;","uniform mat4 matProjInverse;","#ifdef USE_SSAO","uniform sampler2D samplerSSAO;","#endif",XG.ShaderChunk.utils_pars_fragment,XG.ShaderChunk.skin_pars_fragment,XG.DeferredShaderChunk.gbuffersUniforms,XG.DeferredShaderChunk.unpackFloat,XG.DeferredShaderChunk.environmentBRDF,"void main() {",XG.DeferredShaderChunk.computeVertexPositionVS,XG.DeferredShaderChunk.computeNormal,XG.DeferredShaderChunk.unpackColorMap,"vec3 lightVectorHemi = lightDirectionVS;","float lightIntensityHemi = lightIntensity;","vec3 eyeVector = normalize( -vertexPositionVS.xyz );","vec3 halfVector = normalize( lightVectorHemi + eyeVector );",XG.DeferredShaderChunk.hemiTerm,"mgl_FragColor = vec4( hemiTerm, 1.0 );","}"].join("\n"),vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangle},XG.DeferredShaders.dayLight={uniforms:XG.UniformsUtils.merge([XG.DeferredUniformsLib.gbuffers,XG.DeferredUniformsLib.multiShadowMaps,XG.DeferredUniformsLib.projectedTexture,{matProjInverse:{type:"m4",value:new XG.Matrix4,shared:!0},lightDirectionVSSun:{type:"v3",value:new XG.Vector3(0,1,0)},lightDirectionVSHemi:{type:"v3",value:new XG.Vector3(0,1,0)},lightColorSun:{type:"c",value:new XG.Color(0)},lightColorSky:{type:"c",value:new XG.Color(0)},lightColorGround:{type:"c",value:new XG.Color(0)},lightIntensitySun:{type:"f",value:1},lightIntensityHemi:{type:"f",value:1},samplerSSAO:{type:"t",value:null}}]),fragmentShader:["uniform float lightIntensitySun;","uniform float lightIntensityHemi;","uniform vec3 lightColorSun;","uniform vec3 lightColorSky;","uniform vec3 lightColorGround;","uniform vec3 lightDirectionVSSun;","uniform vec3 lightDirectionVSHemi;","uniform mat4 matProjInverse;","#ifdef USE_SSAO","uniform sampler2D samplerSSAO;","#endif",XG.ShaderChunk.utils_pars_fragment,XG.ShaderChunk.skin_pars_fragment,XG.DeferredShaderChunk.multiShadowMapsUniforms,XG.DeferredShaderChunk.gbuffersUniforms,XG.DeferredShaderChunk.projectedTextureUniforms,XG.DeferredShaderChunk.unpackFloat,XG.DeferredShaderChunk.shadowMapPCFSoft,XG.DeferredShaderChunk.geometryFactor,XG.DeferredShaderChunk.specularBRDF,XG.DeferredShaderChunk.environmentBRDF,"void main() {",XG.DeferredShaderChunk.computeVertexPositionVS,XG.DeferredShaderChunk.computeNormal,XG.DeferredShaderChunk.unpackColorMap,"vec3 lightVector = lightDirectionVSSun;",XG.DeferredShaderChunk.computeDiffuse,XG.DeferredShaderChunk.computeSpecular,XG.DeferredShaderChunk.directionalShadows,XG.DeferredShaderChunk.directionalProjectedTexture,"diffuse -= diffuse * fresnel;","vec3 directionalTerm = ( occlusion * lightIntensitySun ) * lightColorSun * ( albedo * diffuse + specular );","vec3 lightVectorHemi = lightDirectionVSHemi;",XG.DeferredShaderChunk.hemiTerm,"mgl_FragColor = vec4( directionalTerm + hemiTerm, 1.0 );","#ifdef SHADOWMAP_DEBUG","mgl_FragColor.xyz *= debugColor;","#endif","}"].join("\n"),vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangle},XG.DeferredShaders.dayLightCube={uniforms:XG.UniformsUtils.merge([XG.DeferredUniformsLib.gbuffers,XG.DeferredUniformsLib.multiShadowMaps,XG.DeferredUniformsLib.projectedTexture,{matProjInverse:{type:"m4",value:new XG.Matrix4,shared:!0},lightDirectionVSSun:{type:"v3",value:new XG.Vector3(0,1,0)},lightColorSun:{type:"c",value:new XG.Color(0)},lightIntensitySun:{type:"f",value:1},lightIntensityAmbient:{type:"f",value:1},matViewInverse:{type:"m4",value:new XG.Matrix4,shared:!0},samplerSpecular:{type:"t",value:null},samplerDiffuse:{type:"t",value:null},samplerSSAO:{type:"t",value:null},maxMipSpecular:{type:"f",value:7}}]),fragmentShader:["uniform float lightIntensitySun;","uniform float lightIntensityAmbient;","uniform vec3 lightColorSun;","uniform vec3 lightDirectionVSSun;","uniform mat4 matProjInverse;","uniform mat4 matViewInverse;","uniform samplerCube samplerSpecular;","uniform samplerCube samplerDiffuse;","#ifdef USE_SSAO","uniform sampler2D samplerSSAO;","#endif","uniform float maxMipSpecular;",XG.ShaderChunk.utils_pars_fragment,XG.ShaderChunk.skin_pars_fragment,XG.DeferredShaderChunk.multiShadowMapsUniforms,XG.DeferredShaderChunk.gbuffersUniforms,XG.DeferredShaderChunk.projectedTextureUniforms,XG.DeferredShaderChunk.unpackFloat,XG.DeferredShaderChunk.shadowMapPCFSoft,XG.DeferredShaderChunk.geometryFactor,XG.DeferredShaderChunk.specularBRDF,XG.DeferredShaderChunk.environmentBRDF,"void main() {",XG.DeferredShaderChunk.computeVertexPositionVS,XG.DeferredShaderChunk.computeNormal,XG.DeferredShaderChunk.unpackColorMap,"vec3 lightVector = lightDirectionVSSun;",XG.DeferredShaderChunk.computeDiffuse,XG.DeferredShaderChunk.computeSpecular,XG.DeferredShaderChunk.directionalShadows,XG.DeferredShaderChunk.directionalProjectedTexture,"diffuse -= diffuse * fresnel;","vec3 directionalTerm = ( occlusion * lightIntensitySun ) * lightColorSun * ( albedo * diffuse + specular );","float gloss = shininess / 8192.0;","vec3 reflectVS = reflect( -eyeVector, normal );","vec4 reflectWS = matViewInverse * vec4( reflectVS, 0.0 );","vec3 cubeCoord = reflectWS.xyz;","float maxMipLevel = maxMipSpecular - 2.0;","#ifdef SUPPORTS_TEXTURE_LOD","float mipLod = max( ( maxMipLevel * ( 1.0 - gloss ) ), 1.5 );","vec3 cubeColorSpecular = textureCubeLodEXT( samplerSpecular, cubeCoord, mipLod ).rgb;","cubeColorSpecular *= cubeColorSpecular;","#else","const float mipUnit = 255.0 / 16.0;","#ifdef SPECULAR_MIP_FIX","float curvature = length( fwidth( cubeCoord ) );","float mipLevelMinification = mipUnit * textureCube( samplerSpecular, cubeCoord, -curvature ).a;","float mipLevelMagnification = mipUnit * textureCube( samplerSpecular, cubeCoord, maxMipSpecular - 1.0 - curvature ).a;","#else","const float curvature = 0.0;","float mipLevelMinification = mipUnit * textureCube( samplerSpecular, cubeCoord ).a;","float mipLevelMagnification = mipUnit * textureCube( samplerSpecular, cubeCoord, maxMipSpecular - 1.0 ).a;","#endif","float mipLevel;","if ( mipLevelMinification == 0.0 ) {","mipLevel = mipLevelMagnification - ( maxMipSpecular - 1.0 );","} else {","mipLevel = mipLevelMinification;","}","float mipBias = max( ( maxMipLevel * ( 1.0 - gloss ) ) - mipLevel, 0.0 );","mipBias -= curvature;","vec3 cubeColorSpecular = textureCube( samplerSpecular, cubeCoord, mipBias ).rgb;","cubeColorSpecular *= cubeColorSpecular;","#endif","vec4 normalWS = matViewInverse * vec4( normal, 0.0 );","vec3 cubeColorDiffuse = textureCube( samplerDiffuse, normalWS.xyz ).rgb;","cubeColorDiffuse *= cubeColorDiffuse;","vec3 fresnelEnv = EnvironmentBRDF( gloss, dot( eyeVector, normal ), specularColor );","vec3 imageDiffuse = ( 1.0 - fresnelEnv ) * cubeColorDiffuse;","vec3 imageSpecular = fresnelEnv * cubeColorSpecular;","#ifdef USE_SSAO","float occlusionAmbient = texture2D( samplerSSAO, texCoord ).x;","#else","float occlusionAmbient = 1.0;","#endif","vec3 imageTerm = lightIntensityAmbient * ( albedo * imageDiffuse + imageSpecular ) * occlusionAmbient * occlusionAmbient * lightMapIntensity;","mgl_FragColor = vec4( directionalTerm + imageTerm, 1.0 );","#ifdef SHADOWMAP_DEBUG","mgl_FragColor.xyz *= debugColor;","#endif","}"].join("\n"),vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangle},XG.DeferredShaders.areaLight={uniforms:XG.UniformsUtils.merge([XG.DeferredUniformsLib.gbuffers,{matProjInverse:{type:"m4",value:new XG.Matrix4,shared:!0},lightPositionVS:{type:"v3",value:new XG.Vector3(0,1,0)},lightNormalVS:{type:"v3",value:new XG.Vector3(0,-1,0)},lightRightVS:{type:"v3",value:new XG.Vector3(1,0,0)},lightUpVS:{type:"v3",value:new XG.Vector3(1,0,0)},lightColor:{type:"c",value:new XG.Color(0)},lightIntensity:{type:"f",value:1},lightWidth:{type:"f",value:1},lightHeight:{type:"f",value:1},constantAttenuation:{type:"f",value:1.5},linearAttenuation:{type:"f",value:.5},quadraticAttenuation:{type:"f",value:.1},samplerTexture:{type:"t",value:null},matShadow:{type:"m4",value:new XG.Matrix4},samplerShadowMap:{type:"t",value:null},shadowMapSize:{type:"v2",value:new XG.Vector2(512,512)},shadowDarkness:{type:"f",value:.5},shadowBias:{type:"f",value:0}}]),fragmentShader:["uniform vec3 lightPositionVS;","uniform vec3 lightNormalVS;","uniform vec3 lightRightVS;","uniform vec3 lightUpVS;","#ifdef AREA_TEXTURE","uniform sampler2D samplerTexture;","#endif","uniform float lightWidth;","uniform float lightHeight;","uniform float constantAttenuation;","uniform float linearAttenuation;","uniform float quadraticAttenuation;","uniform float lightIntensity;","uniform vec3 lightColor;","uniform mat4 matProjInverse;","#ifdef USE_SHADOWMAP","uniform mat4 matShadow;","#ifdef USE_SHADOWSAMPLER","uniform sampler2DShadow samplerShadowMap;","#else","uniform sampler2D samplerShadowMap;","#endif","uniform float shadowBias;","uniform float shadowDarkness;","uniform vec2 shadowMapSize;","#endif",XG.ShaderChunk.utils_pars_fragment,XG.ShaderChunk.skin_pars_fragment,XG.DeferredShaderChunk.gbuffersUniforms,XG.DeferredShaderChunk.unpackFloat,XG.DeferredShaderChunk.shadowMapPCFSoft,XG.DeferredShaderChunk.geometryFactor,XG.DeferredShaderChunk.specularBRDF,"vec3 projectOnPlane( vec3 point, vec3 planeCenter, vec3 planeNorm ) {","return point - dot( point - planeCenter, planeNorm ) * planeNorm;","}","bool sideOfPlane( vec3 point, vec3 planeCenter, vec3 planeNorm ) {","return ( dot( point - planeCenter, planeNorm ) >= 0.0 );","}","vec3 linePlaneIntersect( vec3 lp, vec3 lv, vec3 pc, vec3 pn ) {","return lp + lv * ( dot( pn, pc - lp ) / dot( pn, lv ) );","}","float calculateAttenuation( float dist ) {","return ( 1.0 / ( constantAttenuation + linearAttenuation * dist + quadraticAttenuation * dist * dist ) );","}","void main() {",XG.DeferredShaderChunk.computeVertexPositionVS,XG.DeferredShaderChunk.computeNormal,XG.DeferredShaderChunk.unpackColorMap,"float w = lightWidth;","float h = lightHeight;","vec3 proj = projectOnPlane( vertexPositionVS.xyz, lightPositionVS, lightNormalVS );","vec3 dir = proj - lightPositionVS;","vec2 diagonal = vec2( dot( dir, lightRightVS ), dot( dir, lightUpVS ) );","vec2 nearest2D = vec2( clamp( diagonal.x, -w, w ), clamp( diagonal.y, -h, h ) );","vec3 nearestPointInside = lightPositionVS + ( lightRightVS * nearest2D.x + lightUpVS * nearest2D.y );","vec3 lightDir = normalize( nearestPointInside - vertexPositionVS.xyz );","float NdotL = max( dot( lightNormalVS, -lightDir ), 0.0 );","float NdotL2 = max( dot( normal, lightDir ), 0.0 );","float dotLN = sqrt( NdotL * NdotL2 );","vec3 diffuse = vec3( dotLN );","#ifdef SKIN_HQ","if ( wrapAround < 0.0 && NdotL > 0.0 ) {","float curvature = length( fwidth( normal ) ) / length( fwidth( vertexPositionVS.xyz ) );","diffuse = PSSFitFunction( dotLN, curvature );","}","#else","if ( wrapAround < 0.0 && NdotL > 0.0 ) {","float dotLNHalf = max( 0.25 * dotLN + 0.25, 0.0 );","diffuse = mix( diffuse, vec3( dotLNHalf ), wrapRGB );","}","#endif","#ifdef AREA_TEXTURE","float d = distance( vertexPositionVS.xyz, nearestPointInside );","vec2 co = ( diagonal.xy + vec2( w, h ) ) / ( 2.0 * vec2( w, h ) );","co.y = 1.0 - co.y;","vec3 ve = vertexPositionVS.xyz - lightPositionVS;","vec4 diff = vec4( 0.0 );","if ( dot( ve, lightNormalVS ) < 0.0 ) {","diff = vec4( 0.0 );","} else {","float lod = max( pow( d, 0.1 ), 0.0 ) * 5.0;","vec4 t00 = texture2D( samplerTexture, co, lod );","vec4 t01 = texture2D( samplerTexture, co, lod + 1.0 );","diff = mix( t00, t01, 0.5 );","}","diffuse *= diff.xyz;","#endif","vec3 fresnel = vec3( 0.0 );","vec3 specular = vec3( 0.0 );","vec3 eyeVector = normalize( -vertexPositionVS.xyz );","vec3 R = reflect( eyeVector, normal );","vec3 E = linePlaneIntersect( vertexPositionVS.xyz, R, lightPositionVS, lightNormalVS );","float specAngle = dot( R, lightNormalVS );","if ( dot( vertexPositionVS.xyz - lightPositionVS, lightNormalVS )>=0.0 && specAngle > 0.0 ) {","vec3 dirSpec = E - lightPositionVS;","vec2 dirSpec2D = vec2( dot( dirSpec, lightRightVS ), dot( dirSpec, lightUpVS ) );","vec2 nearestSpec2D = vec2( clamp( dirSpec2D.x, -w, w ), clamp( dirSpec2D.y, -h, h ) );","vec3 nearestPointInsideSpec = lightPositionVS + ( lightRightVS * nearestSpec2D.x + lightUpVS * nearestSpec2D.y );","vec3 lightDirSpec = normalize( nearestPointInsideSpec - vertexPositionVS.xyz );","vec3 halfVectorSpec = normalize( lightDirSpec + eyeVector );","float dotNormalHalf = max( dot( normal, halfVectorSpec ), 0.0 );","float dotLH = max( dot( lightDirSpec, halfVectorSpec ), 0.0 );","float dotLN = max( dot( lightDirSpec, normal ), 0.0 );","fresnel = specularColor + ( 1.0 - specularColor ) * pow( 1.0 - dotLH, 5.0 );","#if defined( BRDF_BLINN_PHONG )","specular = BlinnPhong_Specular( shininess, dotLN, dotNormalHalf, eyeVector, normal ) * ( fresnel * diffuse ) * specAngle;","#elif defined( BRDF_GGX )","float roughness = saturate( sqrt( 8.0 / ( shininess + 7.0 ) ) );","specular = GGX_Specular( roughness, normal, halfVectorSpec, eyeVector, lightDirSpec ) * ( fresnel * diffuse ) * specAngle;","#else","specular = specularColor * max( pow( dotNormalHalf, shininess ), 0.0 ) * diffuse * specAngle;","#endif","#ifdef AREA_TEXTURE","const float hard = 16.0;","const float gloss = 16.0;","vec3 specPlane = lightPositionVS + ( lightRightVS * dirSpec2D.x + lightUpVS * dirSpec2D.y );","float dist = max( distance( vertexPositionVS.xyz, specPlane ), 0.0 );","float d = ( ( 1.0 / hard ) / 2.0 ) * ( dist / gloss );","w = max( w, 0.0 );","h = max( h, 0.0 );","vec2 co = dirSpec2D / ( d + 1.0 );","co /= 2.0 * vec2( w, h );","co = co + vec2( 0.5 );","co.y = 1.0 - co.y;","float lod = ( 2.0 / hard * max( dist, 0.0 ) );","vec4 t00 = texture2D( samplerTexture, co, lod );","vec4 t01 = texture2D( samplerTexture, co, lod + 1.0 );","vec4 spec = mix( t00, t01, 0.5 );","specular *= spec.xyz;","#endif","}","diffuse -= diffuse * fresnel * specAngle;","float occlusion = 1.0;","#ifdef USE_SHADOWMAP","vec4 posLightCS = matShadow * vertexPositionVS;","vec2 shadowCoord = ( posLightCS.xy / posLightCS.w ) * 0.5 + 0.5;","float vertexDepth = posLightCS.z / posLightCS.w;","#if defined( DEPTH_TEXTURES )","vertexDepth = vertexDepth * 0.5 + 0.5;","#endif","#if !defined( SLOPE_DEPTH_BIAS )","vertexDepth -= shadowBias;","#endif","#if defined( SHADOWMAP_TYPE_PCF_SOFT )","float shadowValue = sampleShadowPCFSoft( samplerShadowMap, shadowMapSize, shadowCoord, vertexDepth );","#else","#ifdef USE_SHADOWSAMPLER","float shadowValue = 1.0 - texture( samplerShadowMap, vec3( shadowCoord, vertexDepth ) );","#else","float shadowDepth = texture2D( samplerShadowMap, shadowCoord ).x;","float shadowValue = float( vertexDepth > shadowDepth );","#endif","#endif","occlusion = 1.0 - shadowDarkness * shadowValue;","#endif","float dist = distance( vertexPositionVS.xyz, nearestPointInside );","float attenuation = calculateAttenuation( dist ) * occlusion;",XG.DeferredShaderChunk.combine,"}"].join("\n"),vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangle},XG.DeferredShaders.imageLight={uniforms:XG.UniformsUtils.merge([XG.DeferredUniformsLib.gbuffers,{matProjInverse:{type:"m4",value:new XG.Matrix4,shared:!0},matViewInverse:{type:"m4",value:new XG.Matrix4,shared:!0},samplerSpecular:{type:"t",value:null},samplerDiffuse:{type:"t",value:null},samplerMip:{type:"t",value:null},samplerSSAO:{type:"t",value:null},maxMipSpecular:{type:"f",value:7},lightIntensity:{type:"f",value:1},lightPositionWS:{type:"v3",value:new XG.Vector3(0,0,0)},lightSize:{type:"v3",value:new XG.Vector3(1,1,1)}}]),fragmentShader:["uniform mat4 matProjInverse;","uniform mat4 matViewInverse;","uniform samplerCube samplerSpecular;","uniform samplerCube samplerDiffuse;","#ifdef USE_SSAO","uniform sampler2D samplerSSAO;","#endif","uniform float maxMipSpecular;","uniform float lightIntensity;","#ifdef LIGHT_LOCAL","uniform vec3 lightPositionWS;","uniform vec3 lightSize;","#endif","#if !defined( SUPPORTS_TEXTURE_LOD )","uniform samplerCube samplerMip;","#endif",XG.DeferredShaderChunk.gbuffersUniforms,XG.DeferredShaderChunk.unpackFloat,XG.DeferredShaderChunk.environmentBRDF,"float maxLength( vec3 v ) {","return max( v.x, max( v.y, v.z ) );","}","void main() {",XG.DeferredShaderChunk.computeVertexPositionVS,"#ifdef LIGHT_LOCAL","vec4 vertexPositionWS = matViewInverse * vertexPositionVS;","vec3 lightVectorWS = abs( lightPositionWS.xyz - vertexPositionWS.xyz );","if ( lightVectorWS.x > lightSize.x || lightVectorWS.y > lightSize.y || lightVectorWS.z > lightSize.z ) discard;","float localFade = max( 1.0 - maxLength( lightVectorWS / lightSize ), 0.0 );","#else","float localFade = 1.0;","#endif",XG.DeferredShaderChunk.computeNormal,XG.DeferredShaderChunk.unpackColorMap,"vec3 eyeVector = normalize( -vertexPositionVS.xyz );","vec3 reflectVS = reflect( -eyeVector, normal );","vec4 reflectWS = matViewInverse * vec4( reflectVS, 0.0 );","#ifdef LIGHT_LOCAL","vec3 BoxMin = lightPositionWS - lightSize;","vec3 BoxMax = lightPositionWS + lightSize;","vec3 FirstPlaneIntersect  = ( BoxMax - vertexPositionWS.xyz ) / reflectWS.xyz;","vec3 SecondPlaneIntersect = ( BoxMin - vertexPositionWS.xyz ) / reflectWS.xyz;","vec3 FurthestPlane = max( FirstPlaneIntersect, SecondPlaneIntersect );","float Distance = min( min( FurthestPlane.x, FurthestPlane.y ), FurthestPlane.z );","vec3 IntersectPositionWS = vertexPositionWS.xyz + reflectWS.xyz * Distance;","reflectWS.xyz = IntersectPositionWS - lightPositionWS;","#endif","vec3 cubeCoord = reflectWS.xyz;","float gloss = shininess / 8192.0;","float maxMipLevel = maxMipSpecular - 2.0;","#ifdef SUPPORTS_TEXTURE_LOD","float mipLod = max( ( maxMipLevel * ( 1.0 - gloss ) ), 1.5 );","vec3 cubeColorSpecular = textureCubeLodEXT( samplerSpecular, cubeCoord, mipLod ).rgb;","#ifndef CUBE_SPECULAR_LINEAR","cubeColorSpecular *= cubeColorSpecular;","#endif","#else","const float mipUnit = 255.0 / 16.0;","#ifdef SPECULAR_MIP_FIX","float curvature = length( fwidth( cubeCoord ) );","float mipLevelMinification = mipUnit * textureCube( samplerMip, cubeCoord, -curvature ).a;","float mipLevelMagnification = mipUnit * textureCube( samplerMip, cubeCoord, maxMipSpecular - 1.0 - curvature ).a;","#else","const float curvature = 0.0;","float mipLevelMinification = mipUnit * textureCube( samplerMip, cubeCoord ).a;","float mipLevelMagnification = mipUnit * textureCube( samplerMip, cubeCoord, maxMipSpecular - 1.0 ).a;","#endif","float mipLevel;","if ( mipLevelMinification == 0.0 ) {","mipLevel = mipLevelMagnification - ( maxMipSpecular - 1.0 );","} else {","mipLevel = mipLevelMinification;","}","float mipBias = max( ( maxMipLevel * ( 1.0 - gloss ) ) - mipLevel, 0.0 );","mipBias -= curvature;","vec3 cubeColorSpecular = textureCube( samplerSpecular, cubeCoord, mipBias ).rgb;","#ifndef CUBE_SPECULAR_LINEAR","cubeColorSpecular *= cubeColorSpecular;","#endif","#endif","vec4 normalWS = matViewInverse * vec4( normal, 0.0 );","vec3 cubeColorDiffuse = textureCube( samplerDiffuse, normalWS.xyz ).rgb;","#ifndef CUBE_DIFFUSE_LINEAR","cubeColorDiffuse *= cubeColorDiffuse;","#endif","vec3 fresnelEnv = EnvironmentBRDF( gloss, dot( eyeVector, normal ), specularColor );","vec3 diffuse = ( 1.0 - fresnelEnv ) * cubeColorDiffuse;","vec3 specular = fresnelEnv * cubeColorSpecular;","#ifdef USE_SSAO","float occlusion = texture2D( samplerSSAO, texCoord ).x;","#else","float occlusion = 1.0;","#endif","mgl_FragColor = vec4( lightIntensity * ( albedo * diffuse + specular ), occlusion * occlusion * lightMapIntensity * localFade );","}"].join("\n"),vertexShader:["void main() { ","#ifdef LIGHT_LOCAL","vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );","gl_Position = projectionMatrix * mvPosition;","#else","gl_Position = vec4( position.xyz, 1.0 );","#endif","}"].join("\n")},XG.DeferredShaders.composite={uniforms:XG.UniformsUtils.merge([XG.UniformsLib.fogAtmo,{samplerLight:{type:"t",value:null},samplerBloom:{type:"t",value:null},samplerDepth:{type:"t",value:null},samplerParticles:{type:"t",value:null},samplerParticlesRevealage:{type:"t",value:null},samplerBlur:{type:"t",value:null},samplerBlurAmount:{type:"t",value:null},brightness:{type:"f",value:1},whitePoint:{type:"f",value:1},bloomStrength:{type:"f",value:1},cameraNearFar:{type:"v2",value:new XG.Vector2(1,1e3)}}]),fragmentShader:["varying vec2 vUv;","uniform sampler2D samplerLight;","#ifdef BLOOM_ENABLED","uniform sampler2D samplerBloom;","uniform float bloomStrength;","#endif","#ifdef OFFSCREEN_PARTICLES","uniform sampler2D samplerParticles;","#ifdef PARTICLE_OIT","uniform sampler2D samplerParticlesRevealage;","#endif","#endif","#ifdef FANCY_DOF","uniform sampler2D samplerBlur;","uniform sampler2D samplerBlurAmount;","#endif","#ifdef FOG_ENABLED","uniform sampler2D samplerDepth;","uniform vec2 cameraNearFar;","#endif",XG.ShaderChunk.fogAtmoFragmentPars,XG.ShaderChunk.linearDepthFragmentPars,XG.ShaderChunk.tonemappingFragmentPars,XG.ShaderChunk.ditheringFragmentPars,XG.DeferredShaderChunk.unpackFloat,"void main() {","vec3 color = texture2D( samplerLight, vUv ).xyz;","#ifdef FOG_ENABLED","#if defined( RGBA_DEPTH )","vec4 packedDepth = texture2D( samplerDepth, vUv );","float depth = unpackDepth( packedDepth );","#elif defined( FLOAT_DEPTH )","float depth = texture2D( samplerDepth, vUv ).w;","#elif defined( TEXTURE_DEPTH )","float depth = texture2D( samplerDepth, vUv ).x * 2.0 - 1.0;","#endif","float linearDepth = linearizeDepth( depth, cameraNearFar );","color = addFog( color, linearDepth );","#endif","#ifdef FANCY_DOF","float bias = texture2D( samplerBlurAmount, vUv ).a;","vec3 blur = texture2D( samplerBlur, vUv ).rgb;","color = mix( color, blur, smoothstep( 0.0, 0.1, bias ) );","#endif","#ifdef OFFSCREEN_PARTICLES","#if defined( PARTICLE_OIT )","vec4 accum = texture2D( samplerParticles, vUv );","float rev = texture2D( samplerParticlesRevealage, vUv ).r;","vec4 transparent = vec4( accum.rgb / clamp( rev, 1e-4, 5e4 ), accum.a );","color = transparent.a * color.rgb + ( 1.0 - transparent.a ) * transparent.rgb;","#else","vec3 particleColor = texture2D( samplerParticles, vUv ).xyz;","color += particleColor;","#endif","#endif","#ifdef TONEMAPPING","color = applyTonemapping( color, brightness, whitePoint );","#endif","#ifdef DITHERING_ENABLED","color = applyDithering( color, vUv );","#endif","#ifdef BLOOM_ENABLED","vec3 bloomColor = texture2D( samplerBloom, vUv ).xyz;","color += bloomStrength * bloomColor;","#endif","mgl_FragColor = vec4( color, 1.0 );","}"].join("\n"),vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV},XG.ConvolutionShader={defines:{KERNEL_SIZE_FLOAT:"25.0",KERNEL_SIZE_INT:"25"},uniforms:{tDiffuse:{type:"t",value:null},uImageIncrement:{type:"v2",value:new XG.Vector2(.001953125,0)},cKernel:{type:"fv1",value:[]}},vertexShader:["uniform vec2 uImageIncrement;","varying vec2 vUv;","void main() {","vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement;","gl_Position = vec4( position.xyz, 1.0 );","}"].join("\n"),fragmentShader:["uniform float cKernel[ KERNEL_SIZE_INT ];","uniform sampler2D tDiffuse;","uniform vec2 uImageIncrement;","varying vec2 vUv;","void main() {","vec2 imageCoord = vUv;","vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );","for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) {","sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ];","imageCoord += uImageIncrement;","}","mgl_FragColor = sum;","}"].join("\n"),buildKernel:function(e){function t(e,t){return Math.exp(-(e*e)/(2*t*t))
  }var a,r,i,o,n=25,s=2*Math.ceil(3*e)+1;for(s>n&&(s=n),o=.5*(s-1),r=new Array(s),i=0,a=0;s>a;++a)r[a]=t(a-o,e),i+=r[a];for(a=0;s>a;++a)r[a]/=i;return r}},XG.CopyShader={uniforms:{tDiffuse:{type:"t",value:null},opacity:{type:"f",value:1}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform float opacity;","uniform sampler2D tDiffuse;","varying vec2 vUv;","void main() {","vec4 texel = texture2D( tDiffuse, vUv );","mgl_FragColor = opacity * texel;","}"].join("\n")},XG.FXAAShader={uniforms:{tDiffuse:{type:"t",value:null},resolution:{type:"v2",value:new XG.Vector2(1/1024,1/512)}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform sampler2D tDiffuse;","uniform vec2 resolution;","varying vec2 vUv;","#define FXAA_REDUCE_MIN   (1.0/128.0)","#define FXAA_REDUCE_MUL   (1.0/8.0)","#define FXAA_SPAN_MAX     8.0","void main() {","vec3 rgbNW = texture2D( tDiffuse, ( gl_FragCoord.xy + vec2( -1.0, -1.0 ) ) * resolution ).xyz;","vec3 rgbNE = texture2D( tDiffuse, ( gl_FragCoord.xy + vec2( 1.0, -1.0 ) ) * resolution ).xyz;","vec3 rgbSW = texture2D( tDiffuse, ( gl_FragCoord.xy + vec2( -1.0, 1.0 ) ) * resolution ).xyz;","vec3 rgbSE = texture2D( tDiffuse, ( gl_FragCoord.xy + vec2( 1.0, 1.0 ) ) * resolution ).xyz;","vec4 rgbaM  = texture2D( tDiffuse,  gl_FragCoord.xy  * resolution );","vec3 rgbM  = rgbaM.xyz;","float opacity  = rgbaM.w;","vec3 luma = vec3( 0.299, 0.587, 0.114 );","float lumaNW = dot( rgbNW, luma );","float lumaNE = dot( rgbNE, luma );","float lumaSW = dot( rgbSW, luma );","float lumaSE = dot( rgbSE, luma );","float lumaM  = dot( rgbM,  luma );","float lumaMin = min( lumaM, min( min( lumaNW, lumaNE ), min( lumaSW, lumaSE ) ) );","float lumaMax = max( lumaM, max( max( lumaNW, lumaNE) , max( lumaSW, lumaSE ) ) );","vec2 dir;","dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));","dir.y =  ((lumaNW + lumaSW) - (lumaNE + lumaSE));","float dirReduce = max( ( lumaNW + lumaNE + lumaSW + lumaSE ) * ( 0.25 * FXAA_REDUCE_MUL ), FXAA_REDUCE_MIN );","float rcpDirMin = 1.0 / ( min( abs( dir.x ), abs( dir.y ) ) + dirReduce );","dir = min( vec2( FXAA_SPAN_MAX,  FXAA_SPAN_MAX),","max( vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),","dir * rcpDirMin)) * resolution;","vec3 rgbA = 0.5 * (","texture2D( tDiffuse, gl_FragCoord.xy  * resolution + dir * ( 1.0 / 3.0 - 0.5 ) ).xyz +","texture2D( tDiffuse, gl_FragCoord.xy  * resolution + dir * ( 2.0 / 3.0 - 0.5 ) ).xyz );","vec3 rgbB = rgbA * 0.5 + 0.25 * (","texture2D( tDiffuse, gl_FragCoord.xy  * resolution + dir * -0.5 ).xyz +","texture2D( tDiffuse, gl_FragCoord.xy  * resolution + dir * 0.5 ).xyz );","float lumaB = dot( rgbB, luma );","if ( ( lumaB < lumaMin ) || ( lumaB > lumaMax ) ) {","mgl_FragColor = vec4( rgbA, opacity );","} else {","mgl_FragColor = vec4( rgbB, opacity );","}","}"].join("\n")},XG.SSAOShader={defines:{PREBAKED_SAMPLES:!0,NUM_PREBAKED_SAMPLES:"9"},uniforms:{tDepth:{type:"t",value:null},size:{type:"v2",value:new XG.Vector2(512,512)},cameraCoef:{type:"v3",value:new XG.Vector3(101,99,2)},onlyAO:{type:"i",value:0},aoClamp:{type:"f",value:.3},radius:{type:"f",value:15},samplePoints:{type:"fv2",value:XG.Math.generatePoissonDiscSamples(9)}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform vec3 cameraCoef;","uniform float radius;","uniform vec2 size;","uniform float aoClamp;","uniform sampler2D tDepth;","uniform vec2 samplePoints[ NUM_PREBAKED_SAMPLES ];","varying vec2 vUv;","#define DL 2.399963229728653","#define EULER 2.718281828459045","#define WIDTH size.x","#define HEIGHT size.y","#define CAMERA_FAR_PLUS_NEAR cameraCoef.x","#define CAMERA_FAR_MINUS_NEAR cameraCoef.y","#define CAMERA_NEAR2 cameraCoef.z","#ifndef SAMPLES","#define SAMPLES 8","#endif","const int samples = SAMPLES;","#define USE_NOISE 1","const float noiseAmount = 0.0002;","const float diffAreaSq = 0.16;","const float gDisplace = 0.4;","#ifdef RGBA_DEPTH","float unpackDepth( vec4 rgba ) {","return clamp( dot( rgba, vec4( 1.0, 1.0/255.0, 1.0/65025.0, 1.0/16581375.0 ) ), 0.0, 1.0 );","}","#endif","vec2 rand( const in vec2 coord ) {","#ifdef USE_NOISE","float nx = dot ( coord, vec2( 12.9898, 78.233 ) );","float ny = dot ( coord, vec2( 25.9796, 156.466 ) );","vec2 noise = clamp( fract ( 43758.5453 * sin( vec2( nx, ny ) ) ), 0.0, 1.0 );","#else","float ff = fract( 1.0 - coord.s * ( WIDTH / 2.0 ) );","float gg = fract( coord.t * ( HEIGHT / 2.0 ) );","vec2 noise = vec2( 0.25, 0.75 ) * vec2( ff ) + vec2( 0.75, 0.25 ) * gg;","#endif","return ( noise * 2.0  - 1.0 ) * noiseAmount;","}","float readDepth( const in vec2 coord ) {","#if defined( RGBA_DEPTH )","vec4 packedDepth = texture2D( tDepth, coord );","float depth = unpackDepth( packedDepth );","#elif defined( FLOAT_DEPTH )","float depth = texture2D( tDepth, coord ).w;","#elif defined( TEXTURE_DEPTH )","float depth = texture2D( tDepth, coord ).x * 2.0 - 1.0;","#endif","return CAMERA_NEAR2 / ( CAMERA_FAR_PLUS_NEAR - depth * CAMERA_FAR_MINUS_NEAR );","}","float compareDepths( const in float depth1, const in float depth2, inout int far ) {","float gareaSq = 4.0;","float diff = ( depth1 - depth2 ) * 100.0;","if ( diff < gDisplace ) {","gareaSq = diffAreaSq;","} else {","far = 1;","}","float dd = diff - gDisplace;","return pow( EULER, -2.0 * dd * dd / gareaSq );","}","float calcAO( const in float depth, const in float dw, const in float dh ) {","float dd = radius - depth * radius;","vec2 vv = vec2( dw, dh );","vec2 coord1 = vUv + dd * vv;","vec2 coord2 = vUv - dd * vv;","float temp1 = 0.0;","float temp2 = 0.0;","int far = 0;","temp1 = compareDepths( depth, readDepth( coord1 ), far );","if ( far > 0 ) {","temp2 = compareDepths( readDepth( coord2 ), depth, far );","temp1 += ( 1.0 - temp1 ) * temp2;","}","return temp1;","}","void main() {","vec2 noise = rand( vUv );","float depth = readDepth( vUv );","float tt = clamp( depth, aoClamp, 1.0 );","float w = ( 1.0 / WIDTH )  / tt + ( noise.x * ( 1.0 - noise.x ) );","float h = ( 1.0 / HEIGHT ) / tt + ( noise.y * ( 1.0 - noise.y ) );","float pw = 0.0;","float ph = 0.0;","float ao = 0.0;","#if defined( PREBAKED_SAMPLES )","for ( int i = 0; i < NUM_PREBAKED_SAMPLES; i ++ ) {","vec2 samplePoint = samplePoints[ i ];","ao += calcAO( depth, samplePoint.x * w, samplePoint.y * h );","}","ao /= float( NUM_PREBAKED_SAMPLES );","#else","float dz = 1.0 / float( samples );","float z = 1.0 - dz / 2.0;","float l = 0.0;","for ( int i = 0; i <= samples; i ++ ) {","float r = sqrt( 1.0 - z );","pw = cos( l ) * r;","ph = sin( l ) * r;","ao += calcAO( depth, pw * w, ph * h );","z = z - dz;","l = l + DL;","}","ao /= float( samples );","#endif","mgl_FragColor = vec4( vec3( 1.0 - ao ), 1.0 );","}"].join("\n")},XG.SSAOHorizontalBlurShader={uniforms:{tDiffuse:{type:"t",value:null},h:{type:"f",value:1/512}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform sampler2D tDiffuse;","uniform float h;","varying vec2 vUv;","void main() {","vec4 sum = vec4( 0.0 );","vec4 h1 = texture2D( tDiffuse, vec2( vUv.x - 1.0 * h, vUv.y ) );","vec4 h2 = texture2D( tDiffuse, vec2( vUv.x + 1.0 * h, vUv.y ) );","vec4 h0 = texture2D( tDiffuse, vec2( vUv.x, vUv.y ) );","vec4 m = ( h1 - h2 ) * 0.5;","float d = abs( h0.x - m.x );","if ( d > 0.15 ) {","sum = min( h1, h2 );","} else {","sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * h, vUv.y ) ) * 0.051;","sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * h, vUv.y ) ) * 0.0918;","sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * h, vUv.y ) ) * 0.12245;","sum += h1 * 0.1531;","sum += h0 * 0.1633;","sum += h2 * 0.1531;","sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * h, vUv.y ) ) * 0.12245;","sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * h, vUv.y ) ) * 0.0918;","sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * h, vUv.y ) ) * 0.051;","}","mgl_FragColor = sum;","}"].join("\n")},XG.SSAOVerticalBlurShader={uniforms:{tDiffuse:{type:"t",value:null},v:{type:"f",value:1/512}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform sampler2D tDiffuse;","uniform float v;","varying vec2 vUv;","void main() {","vec4 sum = vec4( 0.0 );","vec4 v1 = texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * v ) );","vec4 v2 = texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * v ) );","vec4 v0 = texture2D( tDiffuse, vec2( vUv.x, vUv.y ) );","vec4 m = ( v1 - v2 ) * 0.5;","float d = abs( v0.x - m.x );","if ( d > 0.15 ) {","sum = min( v1, v2 );","} else {","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * v ) ) * 0.051;","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * v ) ) * 0.0918;","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * v ) ) * 0.12245;","sum += v1 * 0.1531;","sum += v0 * 0.1633;","sum += v2 * 0.1531;","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * v ) ) * 0.12245;","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * v ) ) * 0.0918;","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * v ) ) * 0.051;","}","mgl_FragColor = sum;","}"].join("\n")},XG.SSAOBilateralHorizontalBlurShader={uniforms:{tDiffuse:{type:"t",value:null},tDepth:{type:"t",value:null},tNormal:{type:"t",value:null},h:{type:"f",value:1/512},cameraCoef:{type:"v3",value:new XG.Vector3(101,99,2)}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform vec3 cameraCoef;","#define CAMERA_FAR_PLUS_NEAR cameraCoef.x","#define CAMERA_FAR_MINUS_NEAR cameraCoef.y","#define CAMERA_NEAR2 cameraCoef.z","float linearizeDepth( float d ) {","return CAMERA_NEAR2 / ( CAMERA_FAR_PLUS_NEAR - d * CAMERA_FAR_MINUS_NEAR );","}","float computeWeight( vec4 a, vec4 b ) {","vec3 na = a.xyz * 2.0 - 1.0;","vec3 nb = b.xyz * 2.0 - 1.0;","float dotab = max( dot( na, nb ), 0.0 );","float wn = pow( dotab, 32.0 );","float za = linearizeDepth( a.w );","float zb = linearizeDepth( b.w );","float zz = 10.0 * abs( za - zb );","float wz = 1.0 / ( 1.0 + zz );","return wn * wz;","}","uniform sampler2D tDiffuse;","uniform sampler2D tDepth;","uniform float h;","#if defined( RGBA_DEPTH )","float unpackDepth( vec4 rgba ) {","return clamp( dot( rgba, vec4( 1.0, 1.0/255.0, 1.0/65025.0, 1.0/16581375.0 ) ), 0.0, 1.0 );","}","uniform sampler2D tNormal;","#elif defined( TEXTURE_DEPTH )","uniform sampler2D tNormal;","#endif","varying vec2 vUv;","void main() {","vec4 sum = vec4( 0.0 );","vec2 c1 = vec2( vUv.x - 1.0 * h, vUv.y );","vec2 c2 = vec2( vUv.x + 1.0 * h, vUv.y );","vec2 c3 = vec2( vUv.x - 2.0 * h, vUv.y );","vec2 c4 = vec2( vUv.x + 2.0 * h, vUv.y );","#if defined( RGBA_DEPTH )","vec4 normalDepth0 = texture2D( tNormal, vUv );","vec4 normalDepth1 = texture2D( tNormal, c1 );","vec4 normalDepth2 = texture2D( tNormal, c2 );","vec4 normalDepth3 = texture2D( tNormal, c3 );","vec4 normalDepth4 = texture2D( tNormal, c4 );","normalDepth0.w = unpackDepth( texture2D( tDepth, vUv ) );","normalDepth1.w = unpackDepth( texture2D( tDepth, c1 ) );","normalDepth2.w = unpackDepth( texture2D( tDepth, c2 ) );","normalDepth3.w = unpackDepth( texture2D( tDepth, c3 ) );","normalDepth4.w = unpackDepth( texture2D( tDepth, c4 ) );","#elif defined( FLOAT_DEPTH )","vec4 normalDepth0 = texture2D( tDepth, vUv );","vec4 normalDepth1 = texture2D( tDepth, c1 );","vec4 normalDepth2 = texture2D( tDepth, c2 );","vec4 normalDepth3 = texture2D( tDepth, c3 );","vec4 normalDepth4 = texture2D( tDepth, c4 );","#elif defined( TEXTURE_DEPTH )","vec4 normalDepth0 = texture2D( tNormal, vUv );","vec4 normalDepth1 = texture2D( tNormal, c1 );","vec4 normalDepth2 = texture2D( tNormal, c2 );","vec4 normalDepth3 = texture2D( tNormal, c3 );","vec4 normalDepth4 = texture2D( tNormal, c4 );","normalDepth0.w = texture2D( tDepth, vUv ).x * 2.0 - 1.0;","normalDepth1.w = texture2D( tDepth, c1 ).x * 2.0 - 1.0;","normalDepth2.w = texture2D( tDepth, c2 ).x * 2.0 - 1.0;","normalDepth3.w = texture2D( tDepth, c3 ).x * 2.0 - 1.0;","normalDepth4.w = texture2D( tDepth, c4 ).x * 2.0 - 1.0;","#endif","float w0 = 0.1633;","float w1 = computeWeight( normalDepth0, normalDepth1 ) * 0.1531;","float w2 = computeWeight( normalDepth0, normalDepth2 ) * 0.1531;","float w3 = computeWeight( normalDepth0, normalDepth3 ) * 0.12245;","float w4 = computeWeight( normalDepth0, normalDepth4 ) * 0.12245;","float ws = w0 + w1 + w2 + w3 + w4;","vec4 h0 = texture2D( tDiffuse, vUv );","vec4 h1 = texture2D( tDiffuse, c1 );","vec4 h2 = texture2D( tDiffuse, c2 );","vec4 h3 = texture2D( tDiffuse, c3 );","vec4 h4 = texture2D( tDiffuse, c4 );","sum += h3 * w3;","sum += h1 * w1;","sum += h0 * w0;","sum += h2 * w2;","sum += h4 * w4;","sum /= ws;","mgl_FragColor = sum;","}"].join("\n")},XG.SSAOBilateralVerticalBlurShader={uniforms:{tDiffuse:{type:"t",value:null},tDepth:{type:"t",value:null},tNormal:{type:"t",value:null},v:{type:"f",value:1/512},cameraCoef:{type:"v3",value:new XG.Vector3(101,99,2)}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform vec3 cameraCoef;","#define CAMERA_FAR_PLUS_NEAR cameraCoef.x","#define CAMERA_FAR_MINUS_NEAR cameraCoef.y","#define CAMERA_NEAR2 cameraCoef.z","float linearizeDepth( float d ) {","return CAMERA_NEAR2 / ( CAMERA_FAR_PLUS_NEAR - d * CAMERA_FAR_MINUS_NEAR );","}","float computeWeight( vec4 a, vec4 b ) {","vec3 na = a.xyz * 2.0 - 1.0;","vec3 nb = b.xyz * 2.0 - 1.0;","float dotab = max( dot( na, nb ), 0.0 );","float wn = pow( dotab, 32.0 );","float za = linearizeDepth( a.w );","float zb = linearizeDepth( b.w );","float zz = 10.0 * abs( za - zb );","float wz = 1.0 / ( 1.0 + zz );","return wn * wz;","}","uniform sampler2D tDiffuse;","uniform sampler2D tDepth;","uniform float v;","#if defined( RGBA_DEPTH )","float unpackDepth( vec4 rgba ) {","return clamp( dot( rgba, vec4( 1.0, 1.0/255.0, 1.0/65025.0, 1.0/16581375.0 ) ), 0.0, 1.0 );","}","uniform sampler2D tNormal;","#elif defined( TEXTURE_DEPTH )","uniform sampler2D tNormal;","#endif","varying vec2 vUv;","void main() {","vec4 sum = vec4( 0.0 );","vec2 c1 = vec2( vUv.x, vUv.y - 1.0 * v );","vec2 c2 = vec2( vUv.x, vUv.y + 1.0 * v );","#if defined( RGBA_DEPTH )","vec4 normalDepth0 = texture2D( tNormal, vUv );","vec4 normalDepth1 = texture2D( tNormal, c1 );","vec4 normalDepth2 = texture2D( tNormal, c2 );","normalDepth0.w = unpackDepth( texture2D( tDepth, vUv ) );","normalDepth1.w = unpackDepth( texture2D( tDepth, c1 ) );","normalDepth2.w = unpackDepth( texture2D( tDepth, c2 ) );","#elif defined( FLOAT_DEPTH )","vec4 normalDepth0 = texture2D( tDepth, vUv );","vec4 normalDepth1 = texture2D( tDepth, c1 );","vec4 normalDepth2 = texture2D( tDepth, c2 );","#elif defined( TEXTURE_DEPTH )","vec4 normalDepth0 = texture2D( tNormal, vUv );","vec4 normalDepth1 = texture2D( tNormal, c1 );","vec4 normalDepth2 = texture2D( tNormal, c2 );","normalDepth0.w = texture2D( tDepth, vUv ).x * 2.0 - 1.0;","normalDepth1.w = texture2D( tDepth, c1 ).x * 2.0 - 1.0;","normalDepth2.w = texture2D( tDepth, c2 ).x * 2.0 - 1.0;","#endif","float w0 = 0.1633;","float w1 = computeWeight( normalDepth0, normalDepth1 ) * 0.1531;","float w2 = computeWeight( normalDepth0, normalDepth2 ) * 0.1531;","float ws = w0 + w1 + w2;","vec4 h0 = texture2D( tDiffuse, vUv );","vec4 h1 = texture2D( tDiffuse, c1 );","vec4 h2 = texture2D( tDiffuse, c2 );","sum += h1 * w1;","sum += h0 * w0;","sum += h2 * w2;","sum /= ws;","mgl_FragColor = sum;","}"].join("\n")},XG.BloomHorizontalBlurShader={uniforms:{tDiffuse:{type:"t",value:null},h:{type:"f",value:1/512}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform sampler2D tDiffuse;","uniform float h;","varying vec2 vUv;","void main() {","vec3 sum = vec3( 0.0 );","sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * h, vUv.y ) ).xyz * 0.051;","sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * h, vUv.y ) ).xyz * 0.0918;","sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * h, vUv.y ) ).xyz * 0.12245;","sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * h, vUv.y ) ).xyz * 0.1531;","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ).xyz * 0.1633;","sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * h, vUv.y ) ).xyz * 0.1531;","sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * h, vUv.y ) ).xyz * 0.12245;","sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * h, vUv.y ) ).xyz * 0.0918;","sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * h, vUv.y ) ).xyz * 0.051;","mgl_FragColor.rgb = sum;","mgl_FragColor.a = 1.0;","}"].join("\n")},XG.BloomVerticalBlurShader={uniforms:{tDiffuse:{type:"t",value:null},v:{type:"f",value:1/512}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform sampler2D tDiffuse;","uniform float v;","varying vec2 vUv;","void main() {","vec3 sum = vec3( 0.0 );","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * v ) ).xyz * 0.051;","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * v ) ).xyz * 0.0918;","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * v ) ).xyz * 0.12245;","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * v ) ).xyz * 0.1531;","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ).xyz * 0.1633;","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * v ) ).xyz * 0.1531;","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * v ) ).xyz * 0.12245;","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * v ) ).xyz * 0.0918;","sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * v ) ).xyz * 0.051;","mgl_FragColor.rgb = sum;","mgl_FragColor.a = 1.0;","}"].join("\n")},XG.BloomFilterShader={uniforms:{tSource:{type:"t",value:null},threshold:{type:"f",value:1},brightness:{type:"f",value:1},whitePoint:{type:"f",value:1}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform sampler2D tSource;","uniform float threshold;",XG.ShaderChunk.tonemappingFragmentPars,"varying vec2 vUv;","void main() {","vec3 color = texture2D( tSource, vUv ).rgb;","const vec3 luma = vec3( 0.299, 0.587, 0.114 );","float v = dot( color, luma );","vec3 outColor = vec3( 0.0 );","if ( v > threshold ) {","outColor = applyTonemapping( color, brightness, whitePoint );","}","mgl_FragColor = vec4( outColor, 1.0 );","}"].join("\n")},XG.IBLDiffuseConvolutionShader={uniforms:{tCube:{type:"t",value:null}},vertexShader:["varying vec3 vWorldNormal;","void main() {","vec4 worldNormal = modelMatrix * vec4( normal, 0.0 );","vWorldNormal = worldNormal.xyz;","vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );","gl_Position = projectionMatrix * mvPosition;","}"].join("\n"),fragmentShader:["uniform samplerCube tCube;","varying vec3 vWorldNormal;","const int zSamples = 30;","const int tSamples = 2 * zSamples;","const float zFract = 1.0 / float( zSamples );","const float tFract = 3.14159265 * zFract;","const float normFract = 4.0 * 3.14159265 / float( ( tSamples + 1 ) * ( tSamples ) );","void main() {","vec3 surfaceNormal = normalize( vWorldNormal );","vec3 total = vec3( 0.0 );","for ( int z = -zSamples; z <= zSamples; z ++ ) {","for ( int t = 0; t < tSamples; t ++ ) {","float fz = float( z ) * zFract;","float ft = float( t ) * tFract;","float r = sqrt( 1.0 - fz * fz );","float x = r * cos( ft );","float y = r * sin( ft );","vec3 sampleNormal = vec3( x, y, fz );","float dotProduct = max( dot( surfaceNormal, sampleNormal ), 0.0 );","vec4 pixel = textureCube( tCube, sampleNormal );","total += pixel.rgb * dotProduct;","}","}","mgl_FragColor.rgb = total * normFract;","mgl_FragColor.a = 1.0;","}"].join("\n")},XG.IBLDiffuseProbeShader={uniforms:{tCube:{type:"t",value:null}},vertexShader:["varying vec3 vWorldNormal;","void main() {","vec4 worldNormal = modelMatrix * vec4( normal, 0.0 );","vWorldNormal = worldNormal.xyz;","vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );","gl_Position = projectionMatrix * mvPosition;","}"].join("\n"),fragmentShader:["uniform samplerCube tCube;","varying vec3 vWorldNormal;","void main() {","vec3 surfaceNormal = normalize( vWorldNormal );","mgl_FragColor = textureCube( tCube, surfaceNormal );","mgl_FragColor.rgb *= mgl_FragColor.rgb;","mgl_FragColor.a = 1.0;","}"].join("\n")},XG.DOFBlurPass1Shader={uniforms:{tDiffuse:{type:"t",value:null},tBlurAmount:{type:"t",value:null},resolution:{type:"v2",value:new XG.Vector2(1024,512)},samplePoints1:{type:"fv2",value:XG.Math.generateConcentricCircleSamples(7,6)},samplePoints2:{type:"fv2",value:XG.Math.generateConcentricCircleSamples(3,6)}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["#define PREBAKED_SAMPLES","#define NUM_PREBAKED_SAMPLES1 49","#define NUM_PREBAKED_SAMPLES2 9","#define DL 2.399963229728653","#define PI 3.141592653589793","#define PI4 0.7853981633974483","uniform sampler2D tDiffuse;","uniform sampler2D tBlurAmount;","uniform vec2 resolution;","uniform vec2 samplePoints1[ NUM_PREBAKED_SAMPLES1 ];","uniform vec2 samplePoints2[ NUM_PREBAKED_SAMPLES2 ];","varying vec2 vUv;","#if defined( RGBA_DEPTH )","float unpackDepth( vec4 rgba ) {","return clamp( dot( rgba, vec4( 1.0, 1.0/255.0, 1.0/65025.0, 1.0/16581375.0 ) ), 0.0, 1.0 );","}","#endif","#ifdef CONCENTRIC_CIRCLE_SAMPLE","vec2 mapSquareToDisk( float a, float b ) {","float r;","float fi;","if ( a > -b ) {","if ( a > b ) {","r = a;","fi = PI4 * ( b/a );","} else {","r = b;","fi = PI4 * ( 2.0 - a/b );","}","} else {","if ( a < b ) {","r = -a;","fi = PI4 * ( 4.0 + b/a );","} else {","r = -b;","if ( b != 0.0 ) {","fi = PI4 * ( 6.0 - a/b );","} else {","fi = 0.0;","}","}","}","float u = r * cos( fi );","float v = r * sin( fi );","return vec2( u, v );","}","#endif","void main() {","float centerBias = texture2D( tBlurAmount, vUv ).a;","vec4 mixed = vec4( 0.0 );","vec2 pixelRatio = centerBias * 16.0 / resolution;","#if defined( PREBAKED_SAMPLES )","for ( int i = 0; i < NUM_PREBAKED_SAMPLES1; i ++ ) {","vec4 sampleColor = texture2D( tBlurAmount, vUv + samplePoints1[ i ] * pixelRatio );","mixed += sampleColor;","}","#elif defined( CONCENTRIC_CIRCLE_SAMPLES )","const int samples = 3;","for ( int i = -samples; i <= samples; i ++ ) {","for ( int j = -samples; j <= samples; j ++ ) {","float a = float( j ) / 3.0;","float b = float( i ) / 3.0;","vec2 offset = mapSquareToDisk( a, b );","vec4 sampleColor = texture2D( tBlurAmount, vUv + ( offset * pixelRatio ) );","mixed += sampleColor;","}","}","#else","const int samples = 16;","float dz = 1.0 / float( samples );","float z = 1.0 - dz / 2.0;","float l = 0.0;","for ( int i = 0; i <= samples; i ++ ) {","float r = sqrt( 1.0 - z );","float dx = cos( l );","float dy = sin( l );","vec4 sampleColor = texture2D( tBlurAmount, vUv + ( vec2( dx, dy ) * pixelRatio ) * r );","mixed += sampleColor;","z = z - dz;","l = l + DL;","}","#endif","mixed.rgb /= mixed.a;","mixed.a /= float( NUM_PREBAKED_SAMPLES1 );","mixed.rgb *= mixed.a;","if ( mixed.a == 0.0 ) mixed.rgb = texture2D( tDiffuse, vUv ).rgb;","mgl_FragColor = vec4( mixed.rgb, mixed.a );","}"].join("\n")},XG.DOFBlurPass2Shader={uniforms:{tDiffuse:{type:"t",value:null},tBlurAmount:{type:"t",value:null},resolution:{type:"v2",value:new XG.Vector2(1024,512)},samplePoints:{type:"fv2",value:XG.Math.generateConcentricCircleSamples(3,6)}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["#define PREBAKED_SAMPLES","#define NUM_PREBAKED_SAMPLES 9","#define DL 2.399963229728653","#define PI 3.141592653589793","#define PI4 0.7853981633974483","uniform sampler2D tDiffuse;","uniform sampler2D tBlurAmount;","uniform vec2 resolution;","uniform vec2 samplePoints[ NUM_PREBAKED_SAMPLES ];","varying vec2 vUv;","#if defined( RGBA_DEPTH )","float unpackDepth( vec4 rgba ) {","return clamp( dot( rgba, vec4( 1.0, 1.0/255.0, 1.0/65025.0, 1.0/16581375.0 ) ), 0.0, 1.0 );","}","#endif","#ifdef CONCENTRIC_CIRCLE_SAMPLE","vec2 mapSquareToDisk( float a, float b ) {","float r;","float fi;","if ( a > -b ) {","if ( a > b ) {","r = a;","fi = PI4 * ( b/a );","} else {","r = b;","fi = PI4 * ( 2.0 - a/b );","}","} else {","if ( a < b ) {","r = -a;","fi = PI4 * ( 4.0 + b/a );","} else {","r = -b;","if ( b != 0.0 ) {","fi = PI4 * ( 6.0 - a/b );","} else {","fi = 0.0;","}","}","}","float u = r * cos( fi );","float v = r * sin( fi );","return vec2( u, v );","}","#endif","void main() {","float centerBias = texture2D( tDiffuse, vUv ).a;","vec4 mixed = vec4( 0.0 );","vec2 pixelRatio = centerBias * 3.0 / resolution;","#if defined( PREBAKED_SAMPLES )","for ( int i = 0; i < NUM_PREBAKED_SAMPLES; i ++ ) {","vec4 sampleColor = texture2D( tDiffuse, vUv + samplePoints[ i ] * pixelRatio );","mixed += sampleColor;","}","#elif defined( CONCENTRIC_CIRCLE_SAMPLES )","const int samples = 3;","for ( int i = -samples; i <= samples; i ++ ) {","for ( int j = -samples; j <= samples; j ++ ) {","float a = float( j ) / 3.0;","float b = float( i ) / 3.0;","vec2 offset = mapSquareToDisk( a, b );","vec4 sampleColor = texture2D( tBlurAmount, vUv + ( offset * pixelRatio ) );","mixed += sampleColor;","}","}","#else","const int samples = 16;","float dz = 1.0 / float( samples );","float z = 1.0 - dz / 2.0;","float l = 0.0;","for ( int i = 0; i <= samples; i ++ ) {","float r = sqrt( 1.0 - z );","float dx = cos( l );","float dy = sin( l );","vec4 sampleColor = texture2D( tBlurAmount, vUv + ( vec2( dx, dy ) * pixelRatio ) * r );","mixed += sampleColor;","z = z - dz;","l = l + DL;","}","#endif","mixed.rgb /= mixed.a;","if ( mixed.a == 0.0 ) mixed.rgb = texture2D( tDiffuse, vUv ).rgb;","mgl_FragColor = vec4( mixed.rgb, 1.0 );","}"].join("\n")},XG.DOFShaderChunk={computeBlurPars:["#ifdef DOF_PHYSICAL","uniform float lensAperture;","uniform float lensFocalLength;","uniform float lensBlurScale;","uniform float lensMaxCoc;","float computeBlurStrength( float pointDepth, float focalDepth ) {","float coc = abs( lensAperture * ( ( lensFocalLength * ( focalDepth - pointDepth ) ) / ( pointDepth * ( focalDepth - lensFocalLength ) ) ) );","return min( coc, lensMaxCoc );","}","#else","uniform float focusRampStart;","uniform float focusRampEnd;","uniform float maxBlur;","const float maxBias = 8.0;","float computeBlurBias( float pointDepth, float focalDepth ) {","float blurFactor = abs( focalDepth - pointDepth );","blurFactor *= smoothstep( focusRampStart, focusRampEnd, blurFactor );","float blurBias = maxBlur * blurFactor;","blurBias = min( blurBias, maxBias );","return blurBias;","}","#endif"].join("\n")},XG.DOFBlurAmountShader={defines:{DOF_PHYSICAL:!0},uniforms:XG.UniformsUtils.merge([XG.UniformsLib.fogAtmo,{tDepth:{type:"t",value:null},tDistance:{type:"t",value:null},tDiffuse:{type:"t",value:null},resolution:{type:"v2",value:new XG.Vector2(1920,1080)},autoFocus:{type:"i",value:1},autoFocusPoint:{type:"v2",value:new XG.Vector2(.5,.5)},focusDistance:{type:"f",value:5},focusRampStart:{type:"f",value:2},focusRampEnd:{type:"f",value:8},maxBlur:{type:"f",value:1},lensFocalLength:{type:"f",value:50},lensAperture:{type:"f",value:12.5},lensBlurScale:{type:"f",value:50},lensMaxCoc:{type:"f",value:1},cameraNearFar:{type:"v2",value:new XG.Vector2(1,1e3)}}]),vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:[XG.DOFShaderChunk.computeBlurPars,"uniform bool autoFocus;","uniform vec2 autoFocusPoint;","uniform float focusDistance;","uniform vec2 cameraNearFar;","uniform sampler2D tDepth;","uniform sampler2D tDistance;","uniform sampler2D tDiffuse;","uniform vec2 resolution;","varying vec2 vUv;","#if defined( RGBA_DEPTH )","float unpackDepth( vec4 rgba ) {","return clamp( dot( rgba, vec4( 1.0, 1.0/255.0, 1.0/65025.0, 1.0/16581375.0 ) ), 0.0, 1.0 );","}","float texture2D_bicubic_packed( sampler2D texSampler, vec2 uv, vec2 textureDimensions ) {","vec2 invTextureDimensions = 1.0 / textureDimensions;","uv *= textureDimensions;","vec2 texelCenter   = floor( uv - 0.5 ) + 0.5;","vec2 fracOffset    = uv - texelCenter;","vec2 fracOffset_x2 = fracOffset * fracOffset;","vec2 fracOffset_x3 = fracOffset * fracOffset_x2;","vec2 weight0 = fracOffset_x2 - 0.5 * ( fracOffset_x3 + fracOffset );","vec2 weight1 = 1.5 * fracOffset_x3 - 2.5 * fracOffset_x2 + 1.0;","vec2 weight3 = 0.5 * ( fracOffset_x3 - fracOffset_x2 );","vec2 weight2 = 1.0 - weight0 - weight1 - weight3;","vec2 scalingFactor0 = weight0 + weight1;","vec2 scalingFactor1 = weight2 + weight3;","vec2 f0 = weight1 / ( weight0 + weight1 );","vec2 f1 = weight3 / ( weight2 + weight3 );","vec2 texCoord0 = texelCenter - 1.0 + f0;","vec2 texCoord1 = texelCenter + 1.0 + f1;","texCoord0 *= invTextureDimensions;","texCoord1 *= invTextureDimensions;","return unpackDepth(texture2D( texSampler, vec2( texCoord0.x, texCoord0.y ) )) * scalingFactor0.x * scalingFactor0.y +","unpackDepth(texture2D( texSampler, vec2( texCoord1.x, texCoord0.y ) )) * scalingFactor1.x * scalingFactor0.y +","unpackDepth(texture2D( texSampler, vec2( texCoord0.x, texCoord1.y ) )) * scalingFactor0.x * scalingFactor1.y +","unpackDepth(texture2D( texSampler, vec2( texCoord1.x, texCoord1.y ) )) * scalingFactor1.x * scalingFactor1.y;","}","#endif","vec4 texture2D_bicubic( sampler2D texSampler, vec2 uv, vec2 textureDimensions ) {","vec2 invTextureDimensions = 1.0 / textureDimensions;","uv *= textureDimensions;","vec2 texelCenter   = floor( uv - 0.5 ) + 0.5;","vec2 fracOffset    = uv - texelCenter;","vec2 fracOffset_x2 = fracOffset * fracOffset;","vec2 fracOffset_x3 = fracOffset * fracOffset_x2;","vec2 weight0 = fracOffset_x2 - 0.5 * ( fracOffset_x3 + fracOffset );","vec2 weight1 = 1.5 * fracOffset_x3 - 2.5 * fracOffset_x2 + 1.0;","vec2 weight3 = 0.5 * ( fracOffset_x3 - fracOffset_x2 );","vec2 weight2 = 1.0 - weight0 - weight1 - weight3;","vec2 scalingFactor0 = weight0 + weight1;","vec2 scalingFactor1 = weight2 + weight3;","vec2 f0 = weight1 / ( weight0 + weight1 );","vec2 f1 = weight3 / ( weight2 + weight3 );","vec2 texCoord0 = texelCenter - 1.0 + f0;","vec2 texCoord1 = texelCenter + 1.0 + f1;","texCoord0 *= invTextureDimensions;","texCoord1 *= invTextureDimensions;","return texture2D( texSampler, vec2( texCoord0.x, texCoord0.y ) ) * scalingFactor0.x * scalingFactor0.y +","texture2D( texSampler, vec2( texCoord1.x, texCoord0.y ) ) * scalingFactor1.x * scalingFactor0.y +","texture2D( texSampler, vec2( texCoord0.x, texCoord1.y ) ) * scalingFactor0.x * scalingFactor1.y +","texture2D( texSampler, vec2( texCoord1.x, texCoord1.y ) ) * scalingFactor1.x * scalingFactor1.y;","}",XG.ShaderChunk.fogAtmoFragmentPars,XG.ShaderChunk.linearDepthFragmentPars,"void main() {","#if defined( RGBA_DEPTH )","float depth = texture2D_bicubic_packed( tDepth, vUv, resolution );","#elif defined( FLOAT_DEPTH )","float depth = texture2D_bicubic( tDepth, vUv, resolution ).w;","#elif defined( TEXTURE_DEPTH )","float depth = texture2D( tDepth, vUv ).x * 2.0 - 1.0;","#endif","depth = linearizeDepth( depth, cameraNearFar );","float zFocusDistance;","if ( autoFocus ) {","zFocusDistance = texture2D( tDistance, autoFocusPoint ).x;","} else {","zFocusDistance = focusDistance;","}","#ifdef DOF_PHYSICAL","float blurAmount = computeBlurStrength( lensBlurScale * depth, lensBlurScale * zFocusDistance );","#else","float blurAmount = computeBlurBias( depth, zFocusDistance );","#endif","vec3 color = texture2D_bicubic( tDiffuse, vUv, resolution ).rgb;","#ifdef FOG_ENABLED","color = addFog( color, depth );","#endif","mgl_FragColor = vec4( color * blurAmount, blurAmount );","}"].join("\n")},XG.DepthOfFieldShader={uniforms:{tDiffuse:{type:"t",value:null},tDepth:{type:"t",value:null},tBlur:{type:"t",value:null},tDistance:{type:"t",value:null},focusDistance:{type:"f",value:5},focusRampStart:{type:"f",value:2},focusRampEnd:{type:"f",value:8},cameraNearFar:{type:"v2",value:new XG.Vector2(1,1e3)},maxBlur:{type:"f",value:1},blurSize:{type:"v2",value:new XG.Vector2(1024,512)},autoFocus:{type:"i",value:1},autoFocusPoint:{type:"v2",value:new XG.Vector2(.5,.5)}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform bool autoFocus;","uniform vec2 autoFocusPoint;","uniform float focusDistance;","uniform float focusRampStart;","uniform float focusRampEnd;","uniform vec2 cameraNearFar;","uniform float maxBlur;","uniform vec2 blurSize;","uniform sampler2D tDiffuse;","uniform sampler2D tBlur;","uniform sampler2D tDepth;","uniform sampler2D tDistance;","varying vec2 vUv;","const float maxBias = 3.0;",XG.ShaderChunk.linearDepthFragmentPars,"#if defined( RGBA_DEPTH )","float unpackDepth( vec4 rgba ) {","return clamp( dot( rgba, vec4( 1.0, 1.0/255.0, 1.0/65025.0, 1.0/16581375.0 ) ), 0.0, 1.0 );","}","#endif","void main() {","#if defined( RGBA_DEPTH )","vec4 packedDepth = texture2D( tDepth, vUv );","float depth = unpackDepth( packedDepth );","#elif defined( FLOAT_DEPTH )","float depth = texture2D( tDepth, vUv ).w;","#elif defined( TEXTURE_DEPTH )","float depth = texture2D( tDepth, vUv ).x * 2.0 - 1.0;","#endif","depth = linearizeDepth( depth, cameraNearFar );","float zFocusDistance;","if ( autoFocus ) {","zFocusDistance = texture2D( tDistance, autoFocusPoint ).x;","} else {","zFocusDistance = focusDistance;","}","float blurFactor = abs( zFocusDistance - depth );","#ifdef DOF_DEBUG","vec4 debugColor = vec4( 1.0 );","if ( blurFactor < 0.1 ) {","debugColor = vec4( 1.0, 0.0, 0.0, 1.0 );","}","if ( autoFocus && any( lessThan( abs( vUv - autoFocusPoint ), 0.001 * vec2( 1.0, 2.0 ) ) ) ) {","debugColor *= vec4( 0.0, 0.0, 0.0, 1.0 );","}","#endif","blurFactor *= smoothstep( focusRampStart, focusRampEnd, blurFactor );","float bias = maxBlur * blurFactor;","bias = min( bias, maxBias );","float blurStep = 10.0 * maxBlur;","float dx = blurStep / blurSize.x;","float dy = blurStep / blurSize.y;","vec4 blur0 = texture2D( tBlur, vUv, bias );","vec4 blur1 = texture2D( tBlur, vUv + vec2( -dx, -dy ), bias );","vec4 blur2 = texture2D( tBlur, vUv + vec2(  dx,  dy ), bias );","vec4 blur3 = texture2D( tBlur, vUv + vec2( -dx,  dy ), bias  );","vec4 blur4 = texture2D( tBlur, vUv + vec2(  dx, -dy ), bias  );","vec4 blur = ( blur0 + blur1 + blur2 + blur3 + blur4 ) * 0.2;","vec4 sharp = texture2D( tDiffuse, vUv );","vec4 mixed = mix( sharp, blur, min( bias, 1.0 ) );","mgl_FragColor = mixed;","mgl_FragColor.a = 1.0;","#ifdef DOF_DEBUG","mgl_FragColor *= debugColor;","#endif","}"].join("\n")},XG.DistanceShader={uniforms:{tDepth:{type:"t",value:null},tDistance:{type:"t",value:null},cameraNearFar:{type:"v2",value:new XG.Vector2(1,1e3)},persistence:{type:"f",value:.75},samplePoint:{type:"v2",value:new XG.Vector2(.5,.5)}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform vec2 cameraNearFar;","uniform float persistence;","uniform vec2 samplePoint;","uniform sampler2D tDepth;","uniform sampler2D tDistance;","varying vec2 vUv;",XG.ShaderChunk.linearDepthFragmentPars,"#if defined( RGBA_DEPTH )","float unpackDepth( vec4 rgba ) {","return clamp( dot( rgba, vec4( 1.0, 1.0/255.0, 1.0/65025.0, 1.0/16581375.0 ) ), 0.0, 1.0 );","}","#endif","void main() {","#if defined( RGBA_DEPTH )","vec4 packedDepth = texture2D( tDepth, samplePoint );","float depth = unpackDepth( packedDepth );","#elif defined( FLOAT_DEPTH )","float depth = texture2D( tDepth, samplePoint ).w;","#elif defined( TEXTURE_DEPTH )","float depth = texture2D( tDepth, samplePoint ).x * 2.0 - 1.0;","#endif","depth = linearizeDepth( depth, cameraNearFar );","float oldDepth = texture2D( tDistance, samplePoint ).x;","depth = mix( depth, oldDepth, persistence );","mgl_FragColor = vec4( depth );","mgl_FragColor.a = 1.0;","}"].join("\n")},XG.ChromaticAberrationShader={uniforms:{tDiffuse:{type:"t",value:null},amount:{type:"f",value:.005},angle:{type:"f",value:0}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform sampler2D tDiffuse;","uniform float amount;","uniform float angle;","varying vec2 vUv;","void main() {","vec2 offset = amount * ( length( vUv - 0.5 ) + 0.01 ) * vec2( cos( angle ), sin( angle ) );","vec4 cr = texture2D( tDiffuse, vUv + offset );","vec4 cga = texture2D( tDiffuse, vUv );","vec4 cb = texture2D( tDiffuse, vUv - offset );","mgl_FragColor = vec4( cr.r, cga.g, cb.b, cga.a );","}"].join("\n")},XG.CLUTShader={defines:{LINEAR_FILTER:1},uniforms:{tDiffuse:{type:"t",value:null},tCLUT:{type:"t",value:null},cubeSize:{type:"f",value:64},texSize:{type:"f",value:512}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform sampler2D tDiffuse;","uniform sampler2D tCLUT;","uniform float cubeSize;","uniform float texSize;","varying vec2 vUv;","#ifdef LINEAR_FILTER","vec4 subsample( sampler2D tex, float pixelR, float pixelG, float pixelB, float size, float nPixels ) {","float linearPixelIndex = pixelB * size * size + pixelG * size + pixelR;","float xPixelIndex = mod( linearPixelIndex, nPixels );","float yPixelIndex = floor( linearPixelIndex / nPixels );","vec4 outColor = texture2D( tex, vec2( xPixelIndex, yPixelIndex ) / nPixels );","return outColor;","}","vec4 sampleAs3DTextureLinear( sampler2D tex, vec3 texCoord, float size, float nPixels ) {","float n = size - 1.0;","vec3 pixel = texCoord.rgb * n;","vec3 pixelMin = floor( pixel );","vec3 pixelMax = ceil( pixel );","vec4 RminGminBmin = subsample( tex, pixelMin.r, pixelMin.g, pixelMin.b, size, nPixels );","vec4 RminGminBmax = subsample( tex, pixelMin.r, pixelMin.g, pixelMax.b, size, nPixels );","vec4 RminGmaxBmin = subsample( tex, pixelMin.r, pixelMax.g, pixelMin.b, size, nPixels );","vec4 RminGmaxBmax = subsample( tex, pixelMin.r, pixelMax.g, pixelMax.b, size, nPixels );","vec4 RmaxGminBmin = subsample( tex, pixelMax.r, pixelMin.g, pixelMin.b, size, nPixels );","vec4 RmaxGminBmax = subsample( tex, pixelMax.r, pixelMin.g, pixelMax.b, size, nPixels );","vec4 RmaxGmaxBmin = subsample( tex, pixelMax.r, pixelMax.g, pixelMin.b, size, nPixels );","vec4 RmaxGmaxBmax = subsample( tex, pixelMax.r, pixelMax.g, pixelMax.b, size, nPixels );","vec3 t = pixel - pixelMin;","RminGminBmin = mix( RminGminBmin, RminGminBmax, t.b );","RminGmaxBmin = mix( RminGmaxBmin, RminGmaxBmax, t.b );","RmaxGminBmin = mix( RmaxGminBmin, RmaxGminBmax, t.b );","RmaxGmaxBmin = mix( RmaxGmaxBmin, RmaxGmaxBmax, t.b );","RminGminBmin = mix( RminGminBmin, RminGmaxBmin, t.g );","RmaxGminBmin = mix( RmaxGminBmin, RmaxGmaxBmin, t.g );","RminGminBmin = mix( RminGminBmin, RmaxGminBmin, t.r );","return RminGminBmin;","}","#else","vec4 sampleAs3DTextureNearest( sampler2D tex, vec3 texCoord, float size, float nPixels ) {","float n = size - 1.0;","vec3 pixel = floor( texCoord.rgb * n );","float linearPixelIndex = pixel.b * size * size + pixel.g * size + pixel.r;","float xPixelIndex = mod( linearPixelIndex, nPixels );","float yPixelIndex = floor( linearPixelIndex / nPixels );","vec4 outColor = texture2D( tex, vec2( xPixelIndex, yPixelIndex ) / nPixels );","return outColor;","}","#endif","void main() {","vec4 srcColor = texture2D( tDiffuse, vUv );","#ifdef LINEAR_FILTER","vec4 dstColor = sampleAs3DTextureLinear( tCLUT, srcColor.rgb, cubeSize, texSize );","#else","vec4 dstColor = sampleAs3DTextureNearest( tCLUT, srcColor.rgb, cubeSize, texSize );","#endif","mgl_FragColor = vec4( dstColor.rgb, srcColor.a );","}"].join("\n")},XG.SpriteShader={defines:{BILLBOARD:!1,SDF:!1,FOG:!1,ANTIALIAS:!1,ALPHATEST:.5},extensions:{OES_standard_derivatives:!0},uniforms:{map:{type:"t",value:null},alphaTest:{type:"f",value:.5},epsilon:{type:"f",value:.1},fogDensity:{type:"f",value:.015},fogColor:{type:"c",value:new XG.Color(0)},baseColor:{type:"c",value:new XG.Color(16777215)}},vertexShader:["attribute vec3 color;","attribute vec3 offset;","attribute vec2 scale;","varying vec2 vUv;","varying vec3 vColor;","void main() {","vUv = uv;","vColor = color;","#ifdef BILLBOARD","vec4 tmpPosition = modelViewMatrix * vec4( offset, 1.0 ) + vec4( position * vec3( scale, 1.0 ), 0.0 );","gl_Position = projectionMatrix * tmpPosition;","#else","vec3 spritePosition = position * vec3( scale, 1.0 ) + offset;","vec4 mvPosition = modelViewMatrix * vec4( spritePosition, 1.0 );","gl_Position = projectionMatrix * mvPosition;","#endif","}"].join("\n"),fragmentShader:["uniform sampler2D map;","uniform float alphaTest;","uniform float epsilon;","uniform float fogDensity;","uniform vec3 fogColor;","uniform vec3 baseColor;","varying vec2 vUv;","varying vec3 vColor;","void main() {","vec4 texture = texture2D( map, vUv );","#ifdef SDF","#if defined( GL_OES_standard_derivatives ) || __VERSION__ >= 300","float w = clamp( 200.0 * epsilon * ( abs( dFdx( vUv.x ) ) + abs( dFdy( vUv.y ) ) ), 0.0, 0.5 );","#else","float w = epsilon;","#endif","float alpha = smoothstep( 0.5 - w, 0.5 + w, texture.r );","alpha = pow( alpha, 1.0/2.2 );","if ( alpha < alphaTest ) discard;","#ifdef ANTIALIAS","mgl_FragColor = vec4( baseColor * vColor, alpha );","#else","mgl_FragColor = vec4( baseColor * vColor, 1.0 );","#endif","#else","float alpha = texture.a;","#ifdef ALPHATEST","if ( alpha < alphaTest ) discard;","#endif","mgl_FragColor = vec4( baseColor * vColor * texture.rgb, 1.0 );","#endif","#ifdef FOG","float depth = gl_FragCoord.z / gl_FragCoord.w;","const float LOG2 = 1.442695;","float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );","fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );","mgl_FragColor = mix( mgl_FragColor, vec4( fogColor, mgl_FragColor.a ), fogFactor );","#endif","}"].join("\n")},XG.RendererUtils={},XG.RendererUtils.getUvScale=function(e){var t;
  return e.map?t=e.map:e.displacementMap?t=e.displacementMap:e.lightMap?t=e.lightMap:e.specularMap?t=e.specularMap:e.glossMap?t=e.glossMap:e.normalGlossMap?t=e.normalGlossMap:e.normalMap?t=e.normalMap:e.bumpMap&&(t=e.bumpMap),t},XG.ForwardRenderer=function(e){function t(e,t,a){var o,n,s,l,h=e.attributesList,d=e.offsets,c=e.numInstances>0&&er,u=e.attributes.index;(d.length>1||c)&&(a=!0);for(var f=0,p=d.length;p>f;f++){var m=d[f];if(a){for(var v=m.index,g=0,S=h.length;S>g;g++)o=h[g],o.attached&&(s=o.name,"index"!==s&&(n=t[s],0>n||void 0===n||(l=o.itemSize,i(n),Ft.bindBuffer(Ft.ARRAY_BUFFER,o.buffer),Ft.vertexAttribPointer(n,l,Ft.FLOAT,!1,0,v*l*4),c&&o.divisor>0&&(ar?Ft.vertexAttribDivisor(n,o.divisor):$t.vertexAttribDivisorANGLE(n,o.divisor)))));Ft.bindBuffer(Ft.ELEMENT_ARRAY_BUFFER,u.buffer)}if(Lr(t,e,m.index),r(),c){ar?Ft.drawElementsInstanced(Ft.TRIANGLES,m.count,u.type,m.start*u.typeSize,e.numVisibleInstances):$t.drawElementsInstancedANGLE(Ft.TRIANGLES,m.count,u.type,m.start*u.typeSize,e.numVisibleInstances);for(var g=0,S=h.length;S>g;g++)o=h[g],o.attached&&(s=o.name,"index"!==s&&(n=t[s],0>n||void 0===n||o.divisor>0&&(Ft.bindBuffer(Ft.ARRAY_BUFFER,o.buffer),ar?Ft.vertexAttribDivisor(n,0):$t.vertexAttribDivisorANGLE(n,0))))}else Ft.drawElements(Ft.TRIANGLES,m.count,u.type,m.start*u.typeSize)}}function a(e,t,a,o){var n,s,l=e.attributesList,h=e.numInstances>0&&er;if(o||h)for(var d=0,c=l.length;c>d;d++)n=l[d],n.attached&&(s=t[n.name],0>s||void 0===s||(i(s),Ft.bindBuffer(Ft.ARRAY_BUFFER,n.buffer),Ft.vertexAttribPointer(s,n.itemSize,Ft.FLOAT,!1,0,0),h&&n.divisor>0&&(ar?Ft.vertexAttribDivisor(s,n.divisor):$t.vertexAttribDivisorANGLE(s,n.divisor))));Lr(t,e,0),r();var u=e.attributes.position;if(h){ar?Ft.drawArraysInstanced(a,0,u.numItems/3,e.numVisibleInstances):$t.drawArraysInstancedANGLE(a,0,u.numItems/3,e.numVisibleInstances);for(var d=0,c=l.length;c>d;d++)n=l[d],n.attached&&(s=t[n.name],0>s||void 0===s||(Ft.bindBuffer(Ft.ARRAY_BUFFER,n.buffer),n.divisor>0&&(ar?Ft.vertexAttribDivisor(s,0):$t.vertexAttribDivisorANGLE(s,0))))}else Ft.drawArrays(a,0,u.numItems/3)}function r(){for(var e=0,t=La.length;t>e;e++){var a=La[e];!Ta[a]&&Pa[a]&&(Ft.enableVertexAttribArray(a),void 0===Ta[a]&&ba.push(a),Ta[a]=!0)}for(var e=0,t=ba.length;t>e;e++){var a=ba[e];Ta[a]&&!Pa[a]&&(Ft.disableVertexAttribArray(a),Ta[a]=!1)}}function i(e){Pa[e]||(Pa[e]=!0,La.push(e))}function o(){for(var e=0,t=La.length;t>e;e++){var a=La[e];Pa[a]=!1}La.length=0}function n(e,t){return e.z!==t.z?t.z-e.z:t.id-e.id}function s(e,t){return t[0]-e[0]}function l(e,t,a){if(e.length)for(var r=0,i=e.length;i>r;r++)ra=null,sa=null,ua=-1,Sa=-1,Ga=-1,da=-1,ca=-1,na=-1,oa=-1,Va=!0,e[r].render(t,a,Aa,Ca),ra=null,sa=null,ua=-1,Sa=-1,Ga=-1,da=-1,ca=-1,na=-1,oa=-1,Va=!0}function h(e,t,a,r,i,o,n,s){var l,h,d,c;t?(h=e.length-1,d=-1,c=-1):(h=0,d=e.length,c=1);for(var u,f=h;f!==d;f+=c)l=e[f],l.render&&(u=l[a],u&&u.visible!==!1&&u.enabled!==!1&&(s&&ea.setBlending(u.blending,u.blendEquation,u.blendSrcColor,u.blendDstColor,u.blendSrcAlpha,u.blendDstAlpha),ea.setDepthTest(u.depthTest),ea.setDepthWrite(u.depthWrite),ea.setPolygonOffset(u.polygonOffset,u.polygonOffsetFactor,u.polygonOffsetUnits),ea.setMaterialFaces(u),ea.setProgram(r,i,o,n,u,l.object,l.geometry),ea.renderGeometry(u,l.geometry,l.object)))}function d(e,t,a,r,i,o,n){for(var s,l,h,d=0,c=e.length;c>d;d++)s=e[d],l=s.object,s.render&&(h=s[t],h&&h.visible!==!1&&h.enabled!==!1&&(n&&ea.setBlending(h.blending,h.blendEquation,h.blendSrcColor,h.blendDstColor,h.blendSrcAlpha,h.blendDstAlpha),ea.setDepthTest(h.depthTest),ea.setDepthWrite(h.depthWrite),ea.setPolygonOffset(h.polygonOffset,h.polygonOffsetFactor,h.polygonOffsetUnits),ea.setProgram(a,r,i,o,h,l,null),ea.renderImmediateObject(a,r,i,h,l)))}function c(e){var t=e.object,a=e.index,r=t.materials[a];r&&(r.transparent?(e.transparent=r,e.opaque=null):(e.opaque=r,e.transparent=null))}function u(e){var t=e.object,a=e.index,r=t.materials[a];r&&(r.transparent?(e.transparent=r,e.opaque=null):(e.opaque=r,e.transparent=null))}function f(e,t){var a;if(!e.__webglInit&&(e.__webglInit=!0,e._modelViewMatrix=new XG.Matrix4,e._normalMatrix=new XG.Matrix3,e instanceof XG.Mesh||e instanceof XG.Particles))for(var r=0,i=e.geometries.length;i>r;r++)a=e.geometries[r],Pr(a);if(!e.__webglActive){if(e instanceof XG.Mesh||e instanceof XG.Particles)for(var r=0,i=e.geometries.length;i>r;r++)a=e.geometries[r],p(t.__webglObjects,a,e,r);else(e instanceof XG.ImmediateRenderObject||e.immediateRenderCallback)&&m(t.__webglObjectsImmediate,e);e.__webglActive=!0}}function p(e,t,a,r){e.push({render:!1,index:r,geometry:t,object:a,opaque:null,transparent:null,z:0,id:0})}function m(e,t){e.push({render:!1,index:0,object:t,opaque:null,transparent:null,z:0,id:0})}function v(e){var t=e.geometries;if(e instanceof XG.Mesh||e instanceof XG.Particles)for(var a=0,r=t.length;r>a;a++)ea.setBuffers(t[a])}function g(e,t){e instanceof XG.Mesh||e instanceof XG.Particles?S(t.__webglObjects,e):(e instanceof XG.ImmediateRenderObject||e.immediateRenderCallback)&&S(t.__webglObjectsImmediate,e),e.__webglActive=!1}function S(e,t){for(var a=e.length-1;a>=0;a--)e[a].object===t&&e.splice(a,1)}function G(e,t){e.uniforms=XG.UniformsUtils.clone(t.uniforms),e.vertexShader=t.vertexShader,e.fragmentShader=t.fragmentShader}function x(e,t){var a=t.color;if(ea.gammaInput?e.diffuse.value.setRGBAGamma(a,t.opacity):e.diffuse.value.setRGBA(a,t.opacity),t instanceof XG.EmissiveMaterial||t instanceof XG.DynamicParticleMaterial){var r=e.diffuse.value.data,i=t.intensity;r[0]*=i,r[1]*=i,r[2]*=i}e.map.value=t.map,e.lightMap.value=t.lightMap;var o=Tr(t);if(void 0!==o){var n=o.offset,s=o.repeat;e.offsetRepeat.value.set(n.data[0],n.data[1],s.data[0],s.data[1])}e.brightness.value=ea.brightness,e.whitePoint.value=ea.whitePoint}function M(e,t,a){e.particleSize.value=t.particleSize,e.screenWidth.value=Aa,t instanceof XG.DynamicParticleMaterial&&(e.time.value=t.time,e.timeRange.value=t.timeRange,e.timeOffset.value=t.timeOffset,e.numFrames.value=t.numFrames,e.frameDuration.value=t.frameDuration,e.cameraNearFar.value.set(a.near,a.far),e.additiveFactor.value=t.additiveFactor)}function y(e,t,a){e.fogColor.value=t.color,t instanceof XG.LinearFog?e.fogNearFar.value.set(t.near,t.far):t instanceof XG.ExponentialFog?e.fogDensity.value=t.density:t instanceof XG.AtmosphericFog&&(e.fogStartStrength.value.set(t.start,t.strength),e.cameraNearFar.value.set(a.near,a.far))}function X(e,t){e.fogHeight.value=t.height,e.fogVisibilityDistance.value=t.visibilityDistance,e.fogFadeSpeed.value=t.fadeSpeed,e.fogShallowDepthColor.value=t.shallowDepthColor,e.fogDeepDepthColor.value=t.deepDepthColor,e.fogRgbExtinctionDistance.value=t.rgbExtinctionDistance}function D(e,t){var a=t.specular;ea.gammaInput?e.specular.value.setRGBAGamma(a,t.shininess):e.specular.value.setRGBA(a,t.shininess),t.displacementMap&&(e.displacementMap.value=t.displacementMap,e.displacementScaleBias.value.set(t.displacementScale,t.displacementBias),e.displacementNormalScale.value=t.displacementNormalScale),t.specularMap&&(e.specularMap.value=t.specularMap),t.glossMap&&(e.glossMap.value=t.glossMap),t.bumpMap&&(e.bumpMap.value=t.bumpMap,e.bumpScale.value=t.bumpScale),(t.normalMap||t.normalGlossMap)&&(e.normalMap.value=t.normalGlossMap?t.normalGlossMap:t.normalMap,e.normalScale.value.copy(t.normalScale)),t.bumpDetailMap&&(e.bumpDetailMap.value=t.bumpDetailMap),t.normalDetailMap&&(e.normalDetailMap.value=t.normalDetailMap),(t.bumpDetailMap||t.normalDetailMap)&&e.detailRepeatScale.value.set(t.detailRepeat.x,t.detailRepeat.y,t.detailScale),t.wrapAround&&(e.wrapRGB.value=t.wrapRGB),t.parallax&&(e.parallaxScale.value=t.parallaxScale)}function _(e,t){e.directionalLightPositionVS&&(e.directionalLightPositionVS.value=t.directional.positionsFull),e.directionalLightColor.value=t.directional.colors,e.directionalLightDirectionVS.value=t.directional.positionsNorm,e.directionalLightPars.value=t.directional.pars,e.pointLightColor.value=t.point.colors,e.pointLightPositionVS.value=t.point.positions,e.pointLightDistance.value=t.point.distances,e.sphereLightColor.value=t.sphere.colors,e.sphereLightPositionVS.value=t.sphere.positions,e.sphereLightPars.value=t.sphere.pars,e.tubeLightColor.value=t.tube.colors,e.tubeLightPosition0VS.value=t.tube.positions0,e.tubeLightPosition1VS.value=t.tube.positions1,e.tubeLightPars.value=t.tube.pars,e.spotLightColor.value=t.spot.colors,e.spotLightPositionVS.value=t.spot.positions,e.spotLightDirectionVS.value=t.spot.directions,e.spotLightPars.value=t.spot.pars,e.hemisphereLightSkyColor.value=t.hemi.skyColors,e.hemisphereLightGroundColor.value=t.hemi.groundColors,e.hemisphereLightDirectionVS.value=t.hemi.positions,e.areaLightColor.value=t.area.colors,e.areaLightPosition.value=t.area.positions,e.areaLightNormal.value=t.area.normals,e.areaLightRight.value=t.area.rights,e.areaLightUp.value=t.area.ups,e.areaLightPars.value=t.area.pars,e.areaLightAttenuation.value=t.area.attenuations,e.areaLightTexture.value=t.area.textures,e.imageLightTextureDiffuse.value=t.image.texturesDiffuse,e.imageLightTextureSpecular.value=t.image.texturesSpecular,e.imageLightTextureMip.value=t.image.texturesMip,e.imageLightPars.value=t.image.pars,e.imageLightPositionWS.value=t.image.positions,e.imageLightSize.value=t.image.sizes}function w(e,t,a,r,i){e.useDepthTexture&&qa&&ea.shadowMapUseDepthTextures&&(e=e.depthTexture),r.shadowMap.value[i]=e,r.shadowMatrix.value[i]=t;var o=Math.sqrt(a.shadowDarkness),n=a.properties.shadowMapPars;n.setZ(o),n.setW(a.shadowBias),r.shadowMapPars.value[i]=n}function A(e,t){for(var a=0,r=0,i=t.length;i>r;r++){var o=t[r];if(o.castShadow){if(o instanceof XG.SpotLight||o instanceof XG.AreaLight||(o instanceof XG.DirectionalLight||o instanceof XG.DayLight||o instanceof XG.DayLightCube)&&!o.shadowCascade){var n=o.properties,s=n.shadowMap,l=n.shadowMatrixForward;if(s instanceof Array)for(var h=0,d=s.length;d>h;h++)w(s[h],l[h],o,e,a),a++;else w(s,l,o,e,a),a++}if(o instanceof XG.SphereLight){var n=o.properties,s=n.shadowMap,l=n.shadowMatrixForward;if(s instanceof Array){var h=o.forwardShadowSide;w(s[h],l[h],o,e,a)}else w(s,l,o,e,a);a++}}}}function C(e,t){e.modelViewMatrix&&Ft.uniformMatrix4fv(e.modelViewMatrix,!1,t._modelViewMatrix.elements),e.normalMatrix&&Ft.uniformMatrix3fv(e.normalMatrix,!1,t._normalMatrix.elements),e.modelMatrix&&Ft.uniformMatrix4fv(e.modelMatrix,!1,t.matrixWorld.elements)}function T(){var e=la;return e>=rr&&console.warn("XG:ForwardRenderer: trying to use "+(e+1)+" texture units while this GPU supports only "+rr),la+=1,e}function b(e){for(var t,a,r,i,o,n,s,l,h,d,c=0,u=e.length;u>c;c++)if(t=e[c],a=t[0],o=t[1],i=a.type,r=a.value,"i"===i)Ft.uniform1i(o,r);else if("f"===i)Ft.uniform1f(o,r);else if("v2"===i)Ft.uniform2fv(o,r.data);else if("v3"===i)Ft.uniform3fv(o,r.data);else if("v4"===i)Ft.uniform4fv(o,r.data);else if("c"===i)Ft.uniform3f(o,r.r,r.g,r.b);else if("iv1"===i)Ft.uniform1iv(o,r);else if("iv2"===i)Ft.uniform2iv(o,r);else if("iv3"===i)Ft.uniform3iv(o,r);else if("fv1"===i)Ft.uniform1fv(o,r);else if("fv2"===i)Ft.uniform2fv(o,r);else if("fv3"===i)Ft.uniform3fv(o,r);else if("fv4"===i)Ft.uniform4fv(o,r);else if("v2v"===i){for(void 0===a._array&&(a._array=new Float32Array(2*r.length)),l=0,h=r.length;h>l;l++)d=2*l,a._array.set(r[l].data,d);Ft.uniform2fv(o,a._array)}else if("v3v"===i){for(void 0===a._array&&(a._array=new Float32Array(3*r.length)),l=0,h=r.length;h>l;l++)d=3*l,a._array.set(r[l].data,d);Ft.uniform3fv(o,a._array)}else if("v4v"===i){for(void 0===a._array&&(a._array=new Float32Array(4*r.length)),l=0,h=r.length;h>l;l++)d=4*l,a._array.set(r[l].data,d);Ft.uniform4fv(o,a._array)}else if("m4"===i)Ft.uniformMatrix4fv(o,!1,r.elements);else if("m4v"===i){for(void 0===a._array&&(a._array=new Float32Array(16*r.length)),l=0,h=r.length;h>l;l++)r[l].flattenToArrayOffset(a._array,16*l);Ft.uniformMatrix4fv(o,!1,a._array)}else if("t"===i){if(n=r,s=T(),Ft.uniform1i(o,s),!n)continue;n.image instanceof Array?Y(n,s):n instanceof XG.RenderTargetCube?Q(n,s):ea.setTexture(n,s)}else if("tv"===i){for(void 0===a._array&&(a._array=[]),l=0,h=a.value.length;h>l;l++)a._array[l]=T();for(Ft.uniform1iv(o,a._array),l=0,h=a.value.length;h>l;l++)n=a.value[l],s=a._array[l],n&&(n.image instanceof Array?Y(n,s):n instanceof XG.RenderTargetCube?Q(n,s):ea.setTexture(n,s))}}function P(e,t){e._modelViewMatrix.multiply(t.matrixWorldInverse,e.matrixWorld),e._normalMatrix.getNormalMatrix(e._modelViewMatrix)}function L(e,t,a,r){var i=a.r*r,o=a.g*r,n=a.b*r;ea.gammaInput&&(i*=i,o*=o,n*=n),e[t]=i,e[t+1]=o,e[t+2]=n}function E(e,t,a){var r=a.data;e[t]=r[0],e[t+1]=r[1],e[t+2]=r[2]}function F(e,t,a,r){var i=a.data;e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=r}function R(e,t,a,r){e[t]=a,e[t+1]=r}function U(e,t,a,r,i){e[t]=a,e[t+1]=r,e[t+2]=i}function N(e,t,a,r,i,o){e[t]=a,e[t+1]=r,e[t+2]=i,e[t+3]=o}function I(e,t){var a,r,i,o,n,s,l,h=Ha,d=h.directional.colors,c=h.directional.positionsNorm,u=h.directional.positionsFull,f=h.directional.pars,p=h.point.colors,m=h.point.positions,v=h.point.distances,g=h.sphere.colors,S=h.sphere.positions,G=h.sphere.pars,x=h.tube.colors,M=h.tube.positions0,y=h.tube.positions1,X=h.tube.pars,D=h.spot.colors,_=h.spot.positions,w=h.spot.directions,A=h.spot.pars,C=h.hemi.skyColors,T=h.hemi.groundColors,b=h.hemi.positions,P=h.area.colors,I=h.area.positions,B=h.area.normals,O=h.area.rights,k=h.area.ups,V=h.area.pars,H=h.area.attenuations,z=h.area.textures,W=h.image.pars,j=h.image.texturesDiffuse,q=h.image.texturesSpecular,K=h.image.texturesMip,Z=h.image.positions,Y=h.image.sizes,Q=0,J=0,$=0,et=0,tt=0,at=0,rt=0,it=0,ot=0,nt=0,st=0,lt=0,ht=0,dt=0,ct=0,ut=0,ft=999999,pt=0,mt=0,vt=[],gt=[],St=[],Gt=[],xt=t.matrixWorldInverse;for(a=0,r=e.length;r>a;a++)if(i=e[a],i.onlyShadow)i instanceof XG.DirectionalLight||i instanceof XG.DayLight||i instanceof XG.DayLightCube?i.castShadow&&vt.push(i):i instanceof XG.SpotLight?i.castShadow&&gt.push(i):i instanceof XG.AreaLight?i.castShadow&&St.push(i):i instanceof XG.SphereLight&&i.castShadow&&Gt.push(i);else{if(o=i.color,n=i.intensity,s=i.distance,l=i.matrixWorld,i instanceof XG.DirectionalLight){if(ot+=1,!i.visible)continue;if(Ia.copy(l.getPosition()),Ia.subSelf(i.target.matrixWorld.getPosition()),Ia.normalize(),xt.rotateAxis(Ia),0===Ia.data[0]&&0===Ia.data[1]&&0===Ia.data[2])continue;Na.copy(l.getPosition()),xt.multiplyVector3(Na),E(c,3*Q,Ia),F(u,4*Q,Na,s),L(d,3*Q,o,n),f[Q]=i.castShadow?pt:ft,i.castShadow&&vt.push(i),Q+=1}else if(i instanceof XG.PointLight){if(nt+=1,!i.visible)continue;Na.copy(l.getPosition()),xt.multiplyVector3(Na),E(m,3*J,Na),L(p,3*J,o,n),v[J]=s,J+=1}else if(i instanceof XG.SphereLight){if(st+=1,!i.visible)continue;Na.copy(l.getPosition()),xt.multiplyVector3(Na),E(S,3*$,Na),L(g,3*$,o,n),U(G,3*$,s,i.radius,i.castShadow?pt:ft),i.castShadow&&Gt.push(i),$+=1}else if(i instanceof XG.TubeLight){if(lt+=1,!i.visible)continue;Na.copy(i.endPoint0.matrixWorld.getPosition()),xt.multiplyVector3(Na),E(M,3*et,Na),Na.copy(i.endPoint1.matrixWorld.getPosition()),xt.multiplyVector3(Na),E(y,3*et,Na),L(x,3*et,o,n),R(X,2*et,s,i.radius),et+=1}else if(i instanceof XG.SpotLight){if(ht+=1,!i.visible)continue;Na.copy(l.getPosition()),xt.multiplyVector3(Na),Ia.copy(l.getPosition()),Ia.subSelf(i.target.matrixWorld.getPosition()),Ia.normalize(),xt.rotateAxis(Ia),E(_,3*tt,Na),E(w,3*tt,Ia),L(D,3*tt,o,n),mt=Math.cos(.5*i.angle),N(A,4*tt,mt,i.exponent,s,i.castShadow?pt:ft),i.castShadow&&gt.push(i),tt+=1}else if(i instanceof XG.HemisphereLight){if(dt+=1,!i.visible)continue;if(Ia.copy(l.getPosition()),Ia.normalize(),xt.rotateAxis(Ia),0===Ia.data[0]&&0===Ia.data[1]&&0===Ia.data[2])continue;E(b,3*at,Ia),L(C,3*at,i.color,n),L(T,3*at,i.groundColor,n),at+=1}else if(i instanceof XG.AreaLight){if(ct+=1,!i.visible)continue;Na.copy(l.getPosition()),xt.multiplyVector3(Na),Ba.copy(i.normal),l.rotateAxis(Ba),xt.rotateAxis(Ba),Oa.copy(i.right),l.rotateAxis(Oa),xt.rotateAxis(Oa),ka.cross(Oa,Ba),ka.normalize(),E(I,3*rt,Na),E(B,3*rt,Ba),E(O,3*rt,Oa),E(k,3*rt,ka),L(P,3*rt,o,n),U(H,3*rt,i.constantAttenuation,i.linearAttenuation,i.quadraticAttenuation),N(V,4*rt,i.width,i.height,i.texture?1:0,i.castShadow?pt:ft),z[rt]=i.texture,i.castShadow&&St.push(i),rt+=1}else if(i instanceof XG.ImageLight){if(ut+=1,!i.visible)continue;i.textureDiffuse instanceof XG.RenderTargetCube&&(n/=ea.brightness),ea.gammaInput&&(n*=n),Na.copy(l.getPosition()),E(Z,3*it,Na),E(Y,3*it,i.size),U(W,3*it,i.textureSpecular.mipmapCount,n,i.local?1:0),j[it]=i.textureDiffuse,q[it]=i.textureSpecular,K[it]=i.textureMip,it+=1}else if(i instanceof XG.DayLight){if(dt+=1,ot+=1,!i.visible)continue;if(Ia.copy(i.hemiPosition),Ia.normalize(),xt.rotateAxis(Ia),0===Ia.data[0]&&0===Ia.data[1]&&0===Ia.data[2])continue;if(E(b,3*at,Ia),L(C,3*at,i.skyColor,i.hemiIntensity),L(T,3*at,i.groundColor,i.hemiIntensity),at+=1,Ia.copy(l.getPosition()),Ia.subSelf(i.target.matrixWorld.getPosition()),Ia.normalize(),xt.rotateAxis(Ia),0===Ia.data[0]&&0===Ia.data[1]&&0===Ia.data[2])continue;Na.copy(l.getPosition()),xt.multiplyVector3(Na),E(c,3*Q,Ia),F(u,4*Q,Na,s),L(d,3*Q,o,i.sunIntensity),f[Q]=i.castShadow?pt:ft,i.castShadow&&vt.push(i),Q+=1}else if(i instanceof XG.DayLightCube){if(ut+=1,ot+=1,!i.visible)continue;var Mt=i.ambientIntensity;if(ea.gammaInput&&(Mt*=Mt),Na.copy(l.getPosition()),E(Z,3*it,Na),U(Y,3*it,0,0,0),U(W,3*it,i.textureSpecular.mipmapCount,Mt,i.local?1:0),j[it]=i.textureDiffuse,q[it]=i.textureSpecular,K[it]=i.textureMip,it+=1,Ia.copy(l.getPosition()),Ia.subSelf(i.target.matrixWorld.getPosition()),Ia.normalize(),xt.rotateAxis(Ia),0===Ia.data[0]&&0===Ia.data[1]&&0===Ia.data[2])continue;Na.copy(l.getPosition()),xt.multiplyVector3(Na),E(c,3*Q,Ia),F(u,4*Q,Na,s),L(d,3*Q,o,n),f[Q]=i.castShadow?pt:ft,i.castShadow&&vt.push(i),Q+=1}i.castShadow&&(pt+=1)}var yt=h.shadowCasters;yt.length=0;var Xt,Dt,_t;for(Xt=0,Dt=vt.length;Dt>Xt;Xt++)_t=vt[Xt],yt.push(_t);for(Xt=0,Dt=gt.length;Dt>Xt;Xt++)_t=gt[Xt],yt.push(_t);for(Xt=0,Dt=St.length;Dt>Xt;Xt++)_t=St[Xt],yt.push(_t);for(Xt=0,Dt=Gt.length;Dt>Xt;Xt++)_t=Gt[Xt],yt.push(_t);for(a=3*Q,r=Math.max(d.length,3*ot);r>a;a++)d[a]=0;for(a=3*J,r=Math.max(p.length,3*nt);r>a;a++)p[a]=0;for(a=3*$,r=Math.max(g.length,3*st);r>a;a++)g[a]=0;for(a=3*et,r=Math.max(x.length,3*lt);r>a;a++)x[a]=0;for(a=3*tt,r=Math.max(D.length,3*ht);r>a;a++)D[a]=0;for(a=3*at,r=Math.max(C.length,3*dt);r>a;a++)C[a]=0;for(a=3*at,r=Math.max(T.length,3*dt);r>a;a++)T[a]=0;for(a=3*rt,r=Math.max(P.length,3*ct);r>a;a++)P[a]=0;h.directional.length=Q,h.point.length=J,h.sphere.length=$,h.tube.length=et,h.spot.length=tt,h.hemi.length=at,h.area.length=rt,h.image.length=it}function B(e,t){var a;"fragment"===e?a=Ft.FRAGMENT_SHADER:"vertex"===e&&(a=Ft.VERTEX_SHADER);var r=Ft.createShader(a);Ft.shaderSource(r,t),Ft.compileShader(r),Ft.getShaderParameter(r,Ft.COMPILE_STATUS)||console.error(e.toUpperCase()+" SHADER COMPILATION FAILED");var i=Ft.getShaderInfoLog(r);if(""!==i){var o=XG.DebugUtils.parseGLSLShaderErrorLog(i);XG.DebugUtils.prettyPrintShaderErrors(t,o)}return r}function O(e){var t,a,r=[];for(var i in e)t=e[i],t!==!1&&(void 0!==t?(a="#define "+i+" "+t,r.push(a)):console.warn("XG.ForwardRenderer generateDefines(): undefined value for label ["+i+"]"));return r.join("\n")}function k(e){var t,a,r,i={OES_standard_derivatives:"GL_OES_standard_derivatives",WEBGL_draw_buffers:"GL_EXT_draw_buffers",EXT_shader_texture_lod:"GL_EXT_shader_texture_lod",EXT_frag_depth:"GL_EXT_frag_depth"},o={EXT_shader_texture_lod:!0,WEBGL_draw_buffers:!0,OES_standard_derivatives:!0,EXT_frag_depth:!0,OES_element_index_uint:!0,ANGLE_instanced_arrays:!0,OES_vertex_array_object:!0,EXT_blend_minmax:!0,EXT_sRGB:!0},n=[];for(var s in e)a=e[s],ar&&o[s]||a!==!1&&(void 0!==a?(t=i[s],void 0!==t?(r="#extension "+t+" : enable",n.push(r)):console.warn("XG.ForwardRenderer generateExtensions(): unknown extension ["+s+"]")):console.warn("XG.ForwardRenderer generateExtensions(): undefined state for extension ["+s+"]"));return n.join("\n")}function V(e,t,a,r,i){var o=t.fragmentShader,n=t.vertexShader,s=t.extensions||{},l=t.defines||{},h=[];e?h.push(e):(h.push(o),h.push(n));var d;for(d in l)h.push(d),h.push(l[d]);for(d in i)h.push(d),h.push(i[d]);for(var c=h.join(),u=0,f=ta.length;f>u;u++){var p=ta[u];if(p.code===c)return p.usedTimes++,p.program}var m="SHADOWMAP_TYPE_BASIC";i.shadowMapType===XG.PCFSoftShadowMap?m="SHADOWMAP_TYPE_PCF_SOFT":i.shadowMapType===XG.PCFSoftHQShadowMap&&(m="SHADOWMAP_TYPE_PCF_SOFT_HQ");var v;switch(Et){case XG.SimpleOperator:v="TONEMAP_SIMPLE";break;case XG.LinearOperator:v="TONEMAP_LINEAR";break;case XG.ReinhardOperator:v="TONEMAP_REINHARD";break;case XG.FilmicOperator:v="TONEMAP_FILMIC";break;case XG.Filmic2015Operator:v="TONEMAP_FILMIC_2015";break;case XG.UnchartedOperator:v="TONEMAP_UNCHARTED";break;case XG.LumaReinhardOperator:v="TONEMAP_REINHARD_LUMA";break;case XG.WhitePreservingReinhardOperator:v="TONEMAP_REINHARD_WHITE";break;case XG.PhotographicOperator:v="TONEMAP_PHOTOGRAPHIC"}var g;switch(ea.specularBRDF){case XG.SimpleBRDF:g="BRDF_SIMPLE";break;case XG.BlinnPhongBRDF:g="BRDF_BLINN_PHONG";break;case XG.GGXBRDF:g="BRDF_GGX"}var S;i.fog instanceof XG.LinearFog?S="LINEAR_FOG":i.fog instanceof XG.ExponentialFog?S="EXPONENTIAL_FOG":i.fog instanceof XG.AtmosphericFog&&(S="ATMOSPHERIC_FOG");var G;switch(t.displacementDirection){case XG.DisplaceByNormal:G="DISPLACE_BY_NORMAL";break;case XG.DisplaceByPosition:G="DISPLACE_BY_POSITION"}var x=i.bumpMap||i.normalMap||i.bumpDetailMap||i.normalDetailMap||i.normalGlossMap||i.wrapAroundSkin||i.displacementMap,M=i.maxImageLights>0;s.OES_standard_derivatives=Wa&&(s.OES_standard_derivatives||!!x),s.EXT_shader_texture_lod=Qa&&(s.EXT_shader_texture_lod||!!M);var y=k(s),X=O(l),D=Ft.createProgram(),_=["precision "+yt+" float;","precision "+yt+" int;",X,ea.gammaInput?"#define GAMMA_INPUT":"",ea.gammaOutput?"#define GAMMA_OUTPUT":"",ea.physicallyBasedShading?"#define PHYSICALLY_BASED_SHADING":"",Et?"#define TONEMAPPING":"",v?"#define "+v:"",wt?"#define DITHERING_ENABLED":"",i.instances?"#define USE_INSTANCES":"","#define "+g,"#define MAX_DIR_LIGHTS "+i.maxDirLights,"#define MAX_POINT_LIGHTS "+i.maxPointLights,"#define MAX_SPHERE_LIGHTS "+i.maxSphereLights,"#define MAX_TUBE_LIGHTS "+i.maxTubeLights,"#define MAX_SPOT_LIGHTS "+i.maxSpotLights,"#define MAX_HEMI_LIGHTS "+i.maxHemiLights,"#define MAX_AREA_LIGHTS "+i.maxAreaLights,"#define MAX_IMAGE_LIGHTS "+i.maxImageLights,i.areaTextures?"#define AREA_TEXTURE":"",qa&&ea.shadowMapUseDepthTextures?"#define DEPTH_TEXTURES":"","#define MAX_SHADOWS "+i.maxShadows,i.alphaTest?"#define ALPHATEST "+i.alphaTest:"",i.map?"#define USE_MAP":"",i.lightMap?"#define USE_LIGHTMAP":"",Wa&&i.bumpMap?"#define USE_BUMPMAP":"",Wa&&i.normalMap?"#define USE_NORMALMAP":"",Wa&&i.normalGlossMap?"#define USE_NORMALGLOSSMAP":"",Wa&&i.bumpDetailMap?"#define USE_BUMPDETAILMAP":"",Wa&&i.normalDetailMap?"#define USE_NORMALDETAILMAP":"",i.glossMap?"#define USE_GLOSSMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",Wa&&sr&&i.displacementMap?"#define USE_DISPLACEMENTMAP":"",Wa&&sr&&i.displacementMap?"#define "+G:"",i.vertexColors?"#define USE_COLOR":"",i.shadowMapEnabled?"#define USE_SHADOWMAP":"",i.shadowMapEnabled?"#define "+m:"",i.shadowMapDebug?"#define SHADOWMAP_DEBUG":"",i.shadowMapCascade?"#define SHADOWMAP_CASCADE":"",i.shadowSampler?"#define USE_SHADOWSAMPLER":"","#define DIR_INDEX_OFFSET "+i.dirIndexOffset,"#define SPOT_INDEX_OFFSET "+i.spotIndexOffset,"#define AREA_INDEX_OFFSET "+i.areaIndexOffset,"#define SPHERE_INDEX_OFFSET "+i.sphereIndexOffset,i.isParticle?"#define PARTICLE":"",i.sizeAttenuation?"#define USE_PARTICLE_SIZEATTENUATION":"",i.interpolateParticleFrames?"#define INTERPOLATE_PARTICLE_FRAMES":"",i.wrapAround?"#define WRAP_AROUND":"",Wa&&i.wrapAroundSkin?"#define WRAP_AROUND_SKIN":"",i.doubleSided?"#define DOUBLE_SIDED":"",i.flipSided?"#define FLIP_SIDED":"",i.osxHack?"#define OSX_HACK":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","\n"].join("\n"),w=["#if __VERSION__ >= 300","#define attribute in","#define varying out","#define texture2D texture","#define texture2DLod textureLod","#define texture2DProj textureProj","#define texture2DProjLod textureProjLod","#define textureCube texture","#define textureCubeLod textureLod","#endif",sr?"#define VERTEX_TEXTURES":"","#define MAX_BONES "+i.maxBones,i.skinning?"#define USE_SKINNING":"",i.useVertexTexture?"#define BONE_TEXTURE":"",i.boneTextureWidth?"#define N_BONE_PIXEL_X "+i.boneTextureWidth.toFixed(1):"",i.boneTextureHeight?"#define N_BONE_PIXEL_Y "+i.boneTextureHeight.toFixed(1):"",i.morphTargets?"#define USE_MORPHTARGETS":"",i.morphNormals?"#define USE_MORPHNORMALS":"","#define MAX_MORPHTARGETS "+i.maxMorphTargets,"#define MAX_MORPHNORMALS "+i.maxMorphNormals,i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fog?"#define "+S:"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat3 normalMatrix;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","attribute vec2 uv2;","#ifdef USE_COLOR","attribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","attribute vec3 morphTarget0;","attribute vec3 morphTarget1;","attribute vec3 morphTarget2;","attribute vec3 morphTarget3;","#ifdef USE_MORPHNORMALS","attribute vec3 morphNormal0;","attribute vec3 morphNormal1;","attribute vec3 morphNormal2;","attribute vec3 morphNormal3;","#endif","#endif","#ifdef USE_SKINNING","attribute vec4 skinIndex;","attribute vec4 skinWeight;","#endif",""].join("\n"),A=["#if __VERSION__ >= 300","precision highp sampler2DShadow;","#define varying in","#ifdef MRT_OUTPUT","out vec4 mgl_FragData[ "+tr+" ];","#else","out vec4 mgl_FragColor;","#endif","#define texture2D texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define textureCube texture","#define textureCubeLodEXT textureLod","#define shadow2D texture","#else","#define mgl_FragColor gl_FragColor","#define mgl_FragData  gl_FragData","#endif","",Qa?"#define SUPPORTS_TEXTURE_LOD":"",i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fog?"#define "+S:"",i.metal?"#define METAL":"",i.parallax?"#define USE_PARALLAX":"",i.parallax&&i.parallaxRefineSteps>0?"#define PARALLAX_REFINE_STEPS "+i.parallaxRefineSteps.toFixed(0):"",""].join("\n"),C=y+"\n"+_+A+o,T=_+w+n;ar&&(C="#version 300 es\n"+C,T="#version 300 es\n"+T);var b=B("fragment",C),P=B("vertex",T);Ft.attachShader(D,P),Ft.attachShader(D,b),Ft.linkProgram(D),Ft.getProgramParameter(D,Ft.LINK_STATUS)||console.error("Could not link shader program\nVALIDATE_STATUS: "+Ft.getProgramParameter(D,Ft.VALIDATE_STATUS)+"\nGL_ERROR: "+XG.DebugUtils.translateGLErrorCode(Ft.getError()));var L=Ft.getProgramInfoLog(D);if(""!==L)if(Yt){var E=(Yt.getTranslatedShaderSource(P),Yt.getTranslatedShaderSource(b)),F=XG.DebugUtils.parseTranslatedShaderErrorLog(L);XG.DebugUtils.prettyPrintTranslatedShaderErrors(E,F)}else console.warn("PROGRAM_INFO_LOG: "+L);Ft.deleteShader(b),Ft.deleteShader(P),D.uniforms={},D.attributes={};var R;R=[];for(d in a)R.push(d);H(D,R),R=[];for(d in r)R.push(d);return z(D,R),D.id=aa++,ta.push({program:D,code:c,usedTimes:1}),ea.info.memory.programs=ta.length,D}function H(e,t){var a,r,i;for(a=0,r=t.length;r>a;a++)i=t[a],e.uniforms[i]=Ft.getUniformLocation(e,i)}function z(e,t){var a,r,i;for(a=0,r=t.length;r>a;a++)i=t[a],e.attributes[i]=Ft.getAttribLocation(e,i)}function W(e){return 0===(e&e-1)}function j(e,t,a){a?(Ft.texParameteri(e,Ft.TEXTURE_WRAP_S,t.wrapS),Ft.texParameteri(e,Ft.TEXTURE_WRAP_T,t.wrapT),Ft.texParameteri(e,Ft.TEXTURE_MAG_FILTER,t.magFilter),Ft.texParameteri(e,Ft.TEXTURE_MIN_FILTER,t.minFilter)):(Ft.texParameteri(e,Ft.TEXTURE_WRAP_S,Ft.CLAMP_TO_EDGE),Ft.texParameteri(e,Ft.TEXTURE_WRAP_T,Ft.CLAMP_TO_EDGE),Ft.texParameteri(e,Ft.TEXTURE_MAG_FILTER,ht(t.magFilter)),Ft.texParameteri(e,Ft.TEXTURE_MIN_FILTER,ht(t.minFilter))),Ot&&t.type!==XG.FloatType&&(t.anisotropy>1||t.__oldAnisotropy)&&(Ft.texParameterf(e,Ot.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,nr)),t.__oldAnisotropy=t.anisotropy)}function q(e,t){Ft.activeTexture(Ft.TEXTURE0+t),Ft.bindTexture(Ft.TEXTURE_2D,e.__webglTexture),Ea[t]=e.id,Ft.pixelStorei(Ft.UNPACK_FLIP_Y_WEBGL,e.flipY),Ft.pixelStorei(Ft.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),Ft.pixelStorei(Ft.UNPACK_ALIGNMENT,e.unpackAlignment);var a=e.image,r=W(a.width)&&W(a.height),i=e.format,o=e.type;j(Ft.TEXTURE_2D,e,r);var n,s=e.mipmaps;if(e instanceof XG.DataTexture)if(s.length>0&&r){for(var l=0,h=s.length;h>l;l++)n=s[l],Ft.texImage2D(Ft.TEXTURE_2D,l,i,n.width,n.height,0,i,o,n.data);e.generateMipmaps=!1}else Ft.texImage2D(Ft.TEXTURE_2D,0,i,a.width,a.height,0,i,o,a.data);else if(e instanceof XG.CompressedTexture)for(var l=0,h=s.length;h>l;l++)n=s[l],Ft.pixelStorei(Ft.UNPACK_ALIGNMENT,n.unpackAlignment),i===XG.RGBAFormat||i===XG.RGBFormat?Ft.texImage2D(Ft.TEXTURE_2D,l,i,n.width,n.height,0,i,o,n.data):Ft.compressedTexImage2D(Ft.TEXTURE_2D,l,i,n.width,n.height,0,n.data);else if(s.length>0&&r){for(var l=0,h=s.length;h>l;l++)n=s[l],Ft.texImage2D(Ft.TEXTURE_2D,l,i,i,o,n);e.generateMipmaps=!1}else Ft.texImage2D(Ft.TEXTURE_2D,0,i,i,o,e.image);e.generateMipmaps&&r&&Ft.generateMipmap(Ft.TEXTURE_2D),e.needsUpdate=!1,e.onUpdate&&e.onUpdate()}function K(e,t){if(e.width<=t&&e.height<=t)return e;var a=Math.max(e.width,e.height),r=Math.floor(e.width*t/a),i=Math.floor(e.height*t/a),o=document.createElement("canvas");o.width=r,o.height=i;var n=o.getContext("2d");return n.drawImage(e,0,0,e.width,e.height,0,0,r,i),o}function Z(e,t){Ft.activeTexture(Ft.TEXTURE0+t),Ft.bindTexture(Ft.TEXTURE_CUBE_MAP,e.image.__webglTextureCube),Ea[t]=e.id,Ft.pixelStorei(Ft.UNPACK_FLIP_Y_WEBGL,e.flipY),Ft.pixelStorei(Ft.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),Ft.pixelStorei(Ft.UNPACK_ALIGNMENT,e.unpackAlignment);for(var a=e instanceof XG.CompressedTexture,r=[],i=0;6>i;i++)r[i]=ea.autoScaleCubemaps&&!a?K(e.image[i],or):e.image[i];var o=r[0],n=W(o.width)&&W(o.height),s=e.format,l=e.type;j(Ft.TEXTURE_CUBE_MAP,e,n);for(var i=0;6>i;i++){var h=r[i].mipmaps;if(h&&h.length>0)for(var d=0,c=h.length;c>d;d++){var u=h[d];Ft.pixelStorei(Ft.UNPACK_ALIGNMENT,u.unpackAlignment),s===XG.RGBAFormat||s===XG.RGBFormat?Ft.texImage2D(Ft.TEXTURE_CUBE_MAP_POSITIVE_X+i,d,s,u.width,u.height,0,s,l,u.data):Ft.compressedTexImage2D(Ft.TEXTURE_CUBE_MAP_POSITIVE_X+i,d,s,u.width,u.height,0,u.data)}else Ft.texImage2D(Ft.TEXTURE_CUBE_MAP_POSITIVE_X+i,0,s,s,l,r[i])}e.generateMipmaps&&n&&(Ft.generateMipmap(Ft.TEXTURE_CUBE_MAP),e.mipmapCount=Math.log(Math.max(o.width,o.height))/Math.LN2),e.needsUpdate=!1,e.onUpdate&&e.onUpdate()}function Y(e,t){if(!e.__webglInit){e.__webglInit=!0,e.image.__webglTextureCube=Ft.createTexture(),ea.info.memory.textures++,Ft.activeTexture(Ft.TEXTURE0+t),Ft.bindTexture(Ft.TEXTURE_CUBE_MAP,e.image.__webglTextureCube),Ea[t]=e.id;for(var a=0;6>a;a++)Ft.texImage2D(Ft.TEXTURE_CUBE_MAP_POSITIVE_X+a,0,Ft.RGBA,1,1,0,Ft.RGBA,Ft.UNSIGNED_BYTE,za)}e.needsUpdate&&Z(e,t),Ea[t]!==e.id&&e.image.__webglTextureCube&&(Ft.activeTexture(Ft.TEXTURE0+t),Ft.bindTexture(Ft.TEXTURE_CUBE_MAP,e.image.__webglTextureCube),Ea[t]=e.id)}function Q(e,t){e.__webglInit||(st(e),e.__webglInit=!0),Ea[t]!==e.id&&e.__webglTexture&&(Ft.activeTexture(Ft.TEXTURE0+t),Ft.bindTexture(Ft.TEXTURE_CUBE_MAP,e.__webglTexture),Ea[t]=e.id)}function J(e,t,a,r,i){Ft.bindFramebuffer(Ft.FRAMEBUFFER,e),i&&Ft.framebufferTexture2D(Ft.FRAMEBUFFER,Ft.COLOR_ATTACHMENT0,a,t.__webglTexture,0),r&&Ft.framebufferTexture2D(Ft.FRAMEBUFFER,Ft.DEPTH_ATTACHMENT,a,t.depthTexture.__webglTexture,0)}function $(e,t){if(Ft.bindRenderbuffer(Ft.RENDERBUFFER,e),t.depthBuffer&&!t.stencilBuffer)Ft.renderbufferStorage(Ft.RENDERBUFFER,Ft.DEPTH_COMPONENT16,t.width,t.height),Ft.framebufferRenderbuffer(Ft.FRAMEBUFFER,Ft.DEPTH_ATTACHMENT,Ft.RENDERBUFFER,e);else if(!t.depthBuffer&&t.stencilBuffer)Ft.renderbufferStorage(Ft.RENDERBUFFER,Ft.STENCIL_INDEX8,t.width,t.height),Ft.framebufferRenderbuffer(Ft.FRAMEBUFFER,Ft.STENCIL_ATTACHMENT,Ft.RENDERBUFFER,e);else if(t.depthBuffer&&t.stencilBuffer){var a=ar?Ft.DEPTH24_STENCIL8:Ft.DEPTH_STENCIL;Ft.renderbufferStorage(Ft.RENDERBUFFER,a,t.width,t.height),Ft.framebufferRenderbuffer(Ft.FRAMEBUFFER,Ft.DEPTH_STENCIL_ATTACHMENT,Ft.RENDERBUFFER,e)
  }}function et(e){if(!ja)return void console.error("XG.ForwardRenderer: can't create RenderTargetArray");var t=e.colorTexture.length;e.__webglFramebuffer=Ft.createFramebuffer(),e.__attachments=[],Ft.bindFramebuffer(Ft.FRAMEBUFFER,e.__webglFramebuffer);for(var a=0;t>a;a++)e.__attachments.push(Ft.COLOR_ATTACHMENT0+a);ar?Ft.drawBuffers(e.__attachments):Zt.drawBuffersEXT?Zt.drawBuffersEXT(e.__attachments):Zt.drawBuffersWEBGL(e.__attachments),e.__webglTexture=[];for(var a=0;t>a;a++){var r=e.colorTexture[a];r.__webglTexture=Ft.createTexture(),ea.info.memory.textures++}e.depthTexture?(e.depthTexture.__webglTexture=Ft.createTexture(),ea.info.memory.textures++):e.__webglRenderbuffer=Ft.createRenderbuffer()}function tt(e){var t;if(ar)switch(e){case XG.UnsignedShortType:t=Ft.DEPTH_COMPONENT16;break;case XG.UnsignedIntType:t=Ft.DEPTH_COMPONENT24;break;case XG.FloatType:t=Ft.DEPTH_COMPONENT32F}else t=Ft.DEPTH_COMPONENT;return t}function at(e){var t=W(e.width)&&W(e.height),a=e.colorTexture.length;Ft.bindFramebuffer(Ft.FRAMEBUFFER,e.__webglFramebuffer);for(var r=0;a>r;r++){var i=e.__attachments[r],o=e.colorTexture[r],n=o.internalFormat,s=o.format,l=o.type;Ft.bindTexture(Ft.TEXTURE_2D,o.__webglTexture),j(Ft.TEXTURE_2D,o,t),Ft.texImage2D(Ft.TEXTURE_2D,0,n,e.width,e.height,0,s,l,null),Ft.framebufferTexture2D(Ft.FRAMEBUFFER,i,Ft.TEXTURE_2D,o.__webglTexture,0),o.needsUpdate=!1}if(e.depthTexture){var h=e.depthTexture.depthTextureType,d=tt(h);Ft.bindTexture(Ft.TEXTURE_2D,e.depthTexture.__webglTexture),j(Ft.TEXTURE_2D,e.depthTexture,t),Ft.texImage2D(Ft.TEXTURE_2D,0,d,e.width,e.height,0,Ft.DEPTH_COMPONENT,h,null),Ft.framebufferTexture2D(Ft.FRAMEBUFFER,Ft.DEPTH_ATTACHMENT,Ft.TEXTURE_2D,e.depthTexture.__webglTexture,0),e.depthTexture.needsUpdate=!1}else $(e.__webglRenderbuffer,e)}function rt(e){e.__webglFramebuffer=[],e.__webglRenderbuffer=[],e.__webglTexture=Ft.createTexture();for(var t=0;6>t;t++)e.__webglFramebuffer[t]=Ft.createFramebuffer(),e.__webglRenderbuffer[t]=Ft.createRenderbuffer();ea.info.memory.textures++}function it(e){var t=W(e.width)&&W(e.height),a=e.internalFormat,r=e.format,i=e.type;Ft.activeTexture(Ft.TEXTURE0),Ft.bindTexture(Ft.TEXTURE_CUBE_MAP,e.__webglTexture),j(Ft.TEXTURE_CUBE_MAP,e,t);for(var o=0;6>o;o++)Ft.texImage2D(Ft.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,a,e.width,e.height,0,r,i,null),J(e.__webglFramebuffer[o],e,Ft.TEXTURE_CUBE_MAP_POSITIVE_X+o,!1,!0),$(e.__webglRenderbuffer[o],e);t&&(e.generateMipmaps||e.minFilter!==XG.NearestFilter&&e.minFilter!==XG.LinearFilter)&&Ft.generateMipmap(Ft.TEXTURE_CUBE_MAP),t&&(e.mipmapCount=Math.log(Math.max(e.width,e.height))/Math.LN2)}function ot(e){var t=e.useColorTexture,a=e.useDepthTexture&&qa;e.__webglFramebuffer=Ft.createFramebuffer(),t&&(e.__webglTexture=Ft.createTexture(),ea.info.memory.textures++),e.shareDepthFrom||(a?(e.depthTexture={__webglTexture:Ft.createTexture(),id:XG.TextureIdCount++},ea.info.memory.textures++):e.__webglRenderbuffer=Ft.createRenderbuffer())}function nt(e){var t=e.useColorTexture,a=e.useDepthTexture&&qa,r=W(e.width)&&W(e.height),i=e.internalFormat,o=e.format,n=e.type;if(t&&(Ft.activeTexture(Ft.TEXTURE0),Ft.bindTexture(Ft.TEXTURE_2D,e.__webglTexture),j(Ft.TEXTURE_2D,e,r),Ft.texImage2D(Ft.TEXTURE_2D,0,i,e.width,e.height,0,o,n,null),r&&e.generateMipmaps&&Ft.generateMipmap(Ft.TEXTURE_2D)),a)if(e.shareDepthFrom)e.depthTexture=e.shareDepthFrom.depthTexture;else{var s=e.depthTextureType,l=tt(s);Ft.bindTexture(Ft.TEXTURE_2D,e.depthTexture.__webglTexture),j(Ft.TEXTURE_2D,e,r),ar&&(Ft.texParameteri(Ft.TEXTURE_2D,Ft.TEXTURE_COMPARE_MODE,Ft.COMPARE_REF_TO_TEXTURE),Ft.texParameteri(Ft.TEXTURE_2D,Ft.TEXTURE_COMPARE_FUNC,Ft.LEQUAL)),Ft.texImage2D(Ft.TEXTURE_2D,0,l,e.width,e.height,0,Ft.DEPTH_COMPONENT,s,null)}J(e.__webglFramebuffer,e,Ft.TEXTURE_2D,a,t),a||(e.shareDepthFrom&&e.shareDepthFrom.depthTexture?(e.depthTexture=e.shareDepthFrom.depthTexture,Ft.framebufferTexture2D(Ft.FRAMEBUFFER,Ft.DEPTH_ATTACHMENT,Ft.TEXTURE_2D,e.depthTexture.__webglTexture,0)):e.shareDepthFrom?(e.__webglRenderbuffer=e.shareDepthFrom.__webglRenderbuffer,e.depthBuffer&&!e.stencilBuffer?Ft.framebufferRenderbuffer(Ft.FRAMEBUFFER,Ft.DEPTH_ATTACHMENT,Ft.RENDERBUFFER,e.__webglRenderbuffer):e.depthBuffer&&e.stencilBuffer&&Ft.framebufferRenderbuffer(Ft.FRAMEBUFFER,Ft.DEPTH_STENCIL_ATTACHMENT,Ft.RENDERBUFFER,e.__webglRenderbuffer)):$(e.__webglRenderbuffer,e))}function st(e){if(e.needsUpdate){var t=e instanceof XG.RenderTargetCube,a=e instanceof XG.RenderTargetArray;void 0===e.__webglFramebuffer&&(void 0===e.depthBuffer&&(e.depthBuffer=!0),void 0===e.stencilBuffer&&(e.stencilBuffer=!0),a?et(e):t?rt(e):ot(e)),a?at(e):t?it(e):nt(e),t?Ft.bindTexture(Ft.TEXTURE_CUBE_MAP,null):Ft.bindTexture(Ft.TEXTURE_2D,null),Ea[0]=-1,Ft.bindRenderbuffer(Ft.RENDERBUFFER,null),Ft.bindFramebuffer(Ft.FRAMEBUFFER,null),e.needsUpdate=!1,e.onUpdate&&e.onUpdate()}}function lt(e){if(Ft.activeTexture(Ft.TEXTURE0),e instanceof XG.RenderTargetCube)Ft.bindTexture(Ft.TEXTURE_CUBE_MAP,e.__webglTexture),Ft.generateMipmap(Ft.TEXTURE_CUBE_MAP),Ft.bindTexture(Ft.TEXTURE_CUBE_MAP,null);else if(e instanceof XG.RenderTargetArray){for(var t=0,a=e.colorTexture.length;a>t;t++)Ft.bindTexture(Ft.TEXTURE_2D,e.colorTexture[t].__webglTexture),Ft.generateMipmap(Ft.TEXTURE_2D);Ft.bindTexture(Ft.TEXTURE_2D,null)}else Ft.bindTexture(Ft.TEXTURE_2D,e.__webglTexture),Ft.generateMipmap(Ft.TEXTURE_2D),Ft.bindTexture(Ft.TEXTURE_2D,null);Ea[0]=-1}function ht(e){return e===XG.NearestFilter||e===XG.NearestMipMapNearestFilter||e===XG.NearestMipMapLinearFilter?Ft.NEAREST:Ft.LINEAR}function dt(e){if(lr&&e&&e.useVertexTexture)return 1024;var t=Ft.getParameter(Ft.MAX_VERTEX_UNIFORM_VECTORS),a=Math.floor((t-20)/4),r=a;return void 0!==e&&e instanceof XG.SkinnedMesh&&(r=Math.min(e.bones.length,r),r<e.bones.length&&console.warn("XG.ForwardRenderer: too many bones - "+e.bones.length+", this GPU supports just "+r+" (try OpenGL instead of ANGLE)")),r}function ct(e){var t,a,r,i,o,n,s,l,h,d,c,u,f,p;a=r=i=o=n=s=l=h=d=0,c=u=f=p=0;for(var m=0,v=e.length;v>m;m++)t=e[m],t.onlyShadow||(t instanceof XG.DirectionalLight&&(a++,t.castShadow&&c++),t instanceof XG.SpotLight&&(n++,t.castShadow&&u++),t instanceof XG.AreaLight&&(l++,t.texture&&h++,t.castShadow&&f++),t instanceof XG.DayLight&&(a++,s++,t.castShadow&&c++),t instanceof XG.DayLightCube&&(a++,d++,t.castShadow&&c++),t instanceof XG.SphereLight&&(i++,t.castShadow&&p++),t instanceof XG.PointLight&&r++,t instanceof XG.TubeLight&&o++,t instanceof XG.HemisphereLight&&s++,t instanceof XG.ImageLight&&d++);var g=0,S=g+c,G=S+u,x=G+f,M={directional:a,point:r,sphere:i,tube:o,spot:n,hemi:s,area:l,areaTextures:h,image:d,dirIndexOffset:g,spotIndexOffset:S,areaIndexOffset:G,sphereIndexOffset:x};return M}function ut(e){var t,a,r,i=0;for(t=0,a=e.length;a>t;t++)r=e[t],r.castShadow&&(r instanceof XG.SphereLight&&i++,r instanceof XG.SpotLight&&i++,r instanceof XG.AreaLight&&i++,(r instanceof XG.DirectionalLight||r instanceof XG.DayLight||r instanceof XG.DayLightCube)&&!r.shadowCascade&&i++);return i}function ft(e,t,a){var r=Ft.createFramebuffer(),i=Ft.createTexture();Ft.activeTexture(Ft.TEXTURE0),Ft.bindTexture(Ft.TEXTURE_2D,i),Ft.texImage2D(Ft.TEXTURE_2D,0,e,2,2,0,t,a,null),Ft.bindFramebuffer(Ft.FRAMEBUFFER,r),Ft.framebufferTexture2D(Ft.FRAMEBUFFER,Ft.COLOR_ATTACHMENT0,Ft.TEXTURE_2D,i,0);var o=Ft.checkFramebufferStatus(Ft.FRAMEBUFFER);return Ft.bindFramebuffer(Ft.FRAMEBUFFER,null),Ft.bindTexture(Ft.TEXTURE_2D,null),Ea[0]=-1,o===Ft.FRAMEBUFFER_COMPLETE}function pt(){var e=XG.UnsignedIntType,t=tt(e),a=Ft.createFramebuffer(),r=Ft.createTexture();Ft.activeTexture(Ft.TEXTURE0),Ft.bindTexture(Ft.TEXTURE_2D,r),Ft.texImage2D(Ft.TEXTURE_2D,0,t,2,2,0,Ft.DEPTH_COMPONENT,e,null),Ft.bindFramebuffer(Ft.FRAMEBUFFER,a),Ft.framebufferTexture2D(Ft.FRAMEBUFFER,Ft.DEPTH_ATTACHMENT,Ft.TEXTURE_2D,r,0);var i=Ft.checkFramebufferStatus(Ft.FRAMEBUFFER);return Ft.bindFramebuffer(Ft.FRAMEBUFFER,null),Ft.bindTexture(Ft.TEXTURE_2D,null),Ea[0]=-1,i===Ft.FRAMEBUFFER_COMPLETE}function mt(){Nt=Ft.getExtension("OES_texture_float_linear"),Ot=Ft.getExtension("EXT_texture_filter_anisotropic")||Ft.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),zt=Ft.getExtension("WEBGL_compressed_texture_s3tc")||Ft.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),Wt=Ft.getExtension("WEBGL_compressed_texture_pvrtc")||Ft.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),jt=Ft.getExtension("WEBGL_compressed_texture_atc")||Ft.getExtension("WEBKIT_WEBGL_compressed_texture_atc"),qt=Ft.getExtension("WEBGL_compressed_texture_etc1")||Ft.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),Yt=Ft.getExtension("WEBGL_debug_shaders"),null===Nt&&console.log("XG: linear filtering for float textures not supported."),null===Ot&&console.log("XG: anisotropic texture filtering not supported."),null===zt&&console.log("XG: S3TC compressed textures not supported.")}function vt(){try{var e={alpha:Xt,premultipliedAlpha:Dt,antialias:_t,stencil:At,depth:Ct,preserveDrawingBuffer:Tt};if(Ft=xt.getContext("webgl2",e)||xt.getContext("experimental-webgl2",e),null===Ft)throw"Error creating WebGL 2 context."}catch(t){console.error(t)}console.log("XG: using WebGL 2 backend"),mt(),Qt=Ft.getExtension("WEBGL_color_buffer_float")||Ft.getExtension("EXT_color_buffer_float"),Jt=Ft.getExtension("EXT_color_buffer_half_float"),null===Qt&&console.log("XG: rendering into float textures not supported."),null===Jt&&console.log("XG: rendering into half float textures not supported.")}function gt(){try{var e={alpha:Xt,premultipliedAlpha:Dt,antialias:_t,stencil:At,depth:Ct,preserveDrawingBuffer:Tt};if(Ft=xt.getContext("webgl",e)||xt.getContext("experimental-webgl",e),null===Ft)throw"Error creating WebGL context."}catch(t){console.error(t)}console.log("XG: using WebGL 1 backend"),mt(),Rt=Ft.getExtension("OES_texture_float"),Ut=Ft.getExtension("OES_texture_half_float"),It=Ft.getExtension("OES_texture_half_float_linear"),Bt=Ft.getExtension("OES_standard_derivatives"),Kt=Ft.getExtension("OES_element_index_uint"),Vt=Ft.getExtension("WEBGL_depth_texture")||Ft.getExtension("WEBKIT_WEBGL_depth_texture"),Zt=Ft.getExtension("WEBGL_draw_buffers")||Ft.getExtension("WEBKIT_EXT_draw_buffers"),Ht=Ft.getExtension("EXT_frag_depth"),kt=Ft.getExtension("EXT_shader_texture_lod"),$t=Ft.getExtension("ANGLE_instanced_arrays"),null===Rt&&console.log("XG: float textures not supported."),null===Ut&&console.log("XG: half float textures not supported."),null===It&&console.log("XG: linear filtering for half float textures not supported."),null===Bt&&console.log("XG: standard derivatives not supported."),null===Kt&&console.log("XG: 32-bit unsigned integer indices not supported."),null===Vt&&console.log("XG: depth texture not supported."),null===Zt&&console.log("XG: multiple render targets not supported."),null===Ht&&console.log("XG: fragment depth setting not supported."),null===kt&&console.log("XG: fragment shader texture LOD not supported."),null===$t&&console.log("XG: instancing not supported.")}function St(){Ft.clearColor(0,0,0,1),Ft.clearDepth(1),Ft.clearStencil(0),Ft.enable(Ft.DEPTH_TEST),Ft.depthFunc(Ft.LEQUAL),Ft.frontFace(Ft.CCW),Ft.cullFace(Ft.BACK),Ft.enable(Ft.CULL_FACE),Ft.enable(Ft.BLEND),Ft.blendEquation(Ft.FUNC_ADD),Ft.blendFunc(Ft.SRC_ALPHA,Ft.ONE_MINUS_SRC_ALPHA),Ft.disable(Ft.STENCIL_TEST),Ft.clearColor(bt.r,bt.g,bt.b,Pt)}function Gt(){ea.shadowMapPlugin=new XG.ShadowMapPlugin,ea.addPrePlugin(ea.shadowMapPlugin)}e=e||{};var xt=void 0!==e.canvas?e.canvas:document.createElement("canvas"),Mt=void 0!==e.backend?e.backend:"webgl1",yt=void 0!==e.precision?e.precision:"highp",Xt=void 0!==e.alpha?e.alpha:!1,Dt=void 0!==e.premultipliedAlpha?e.premultipliedAlpha:!0,_t=void 0!==e.antialias?e.antialias:!1,wt=void 0!==e.dither?e.dither:!1,At=void 0!==e.stencil?e.stencil:!0,Ct=void 0!==e.depth?e.depth:!0,Tt=void 0!==e.preserveDrawingBuffer?e.preserveDrawingBuffer:!1,bt=new XG.Color(void 0!==e.clearColor?e.clearColor:0),Pt=void 0!==e.clearAlpha?e.clearAlpha:0,Lt=void 0!==e.scale?e.scale:1,Et=void 0!==e.tonemapping?e.tonemapping:XG.SimpleOperator;this.brightness=void 0!==e.brightness?e.brightness:1,this.whitePoint=void 0!==e.whitePoint?e.whitePoint:1,this.domElement=xt,this.context=null,this.devicePixelRatio=void 0!==e.devicePixelRatio?e.devicePixelRatio:void 0!==window.devicePixelRatio?window.devicePixelRatio:1,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.autoUpdateObjects=!0,this.autoUpdateScene=!0,this.autoUpdateView=!0,this.gammaInput=!0,this.gammaOutput=!1,this.physicallyBasedShading=!0,this.specularBRDF=XG.GGXBRDF,this.shadowMapEnabled=!1,this.shadowMapAutoUpdate=!0,this.shadowMapType=XG.PCFSoftShadowMap,this.shadowMapCullFace=XG.CullFaceFront,this.shadowMapDebug=!1,this.shadowMapCascade=!1,this.shadowMapUseDepthTextures=!1,this.shadowMapDepthTextureType=XG.UnsignedIntType,this.shadowMapSlopeDepthBias=!1,this.shadowMapSlopeScale=2,this.shadowMapSlopeBias=0,this.shadowMapSlopeMax=.001,this.maxMorphTargets=4,this.maxMorphNormals=4,this.autoScaleCubemaps=!0,this.renderPluginsPre=[],this.renderPluginsPost=[],this.info={memory:{programs:0,geometries:0,textures:0},render:{calls:0,vertices:0,faces:0,points:0}};var Ft,Rt,Ut,Nt,It,Bt,Ot,kt,Vt,Ht,zt,Wt,jt,qt,Kt,Zt,Yt,Qt,Jt,$t,ea=this,ta=[],aa=0,ra=null,ia=null,oa=-1,na=null,sa=null,la=0,ha=0,da=-1,ca=-1,ua=-1,fa=-1,pa=-1,ma=-1,va=-1,ga=-1,Sa=-1,Ga=-1,xa=null,Ma=null,ya=null,Xa=0,Da=0,_a=0,wa=0,Aa=0,Ca=0,Ta={},ba=[],Pa={},La=[],Ea=[],Fa=new XG.Frustum,Ra=new XG.Matrix4,Ua=new XG.Vector3,Na=new XG.Vector3,Ia=new XG.Vector3,Ba=new XG.Vector3,Oa=new XG.Vector3,ka=new XG.Vector3,Va=!0,Ha={directional:{length:0,colors:[],positionsNorm:[],positionsFull:[],pars:[]},point:{length:0,colors:[],positions:[],distances:[]},sphere:{length:0,colors:[],positions:[],pars:[]},tube:{length:0,colors:[],positions0:[],positions1:[],pars:[]},spot:{length:0,colors:[],positions:[],directions:[],pars:[]},area:{length:0,colors:[],positions:[],normals:[],rights:[],ups:[],attenuations:[],pars:[],textures:[]},hemi:{length:0,skyColors:[],groundColors:[],positions:[]},image:{length:0,positions:[],sizes:[],texturesDiffuse:[],texturesSpecular:[],texturesMip:[],pars:[]},shadowCasters:[]},za=new Uint8Array([0,0,0,255]);if("webgl2"===Mt){vt();var Wa=!0,ja=!0,qa=!0,Ka=!0,Za=!0,Ya=!0,Qa=!0,Ja=!0,$a=!0,er=!0,tr=Ft.getParameter(Ft.MAX_DRAW_BUFFERS)}else{gt();var Wa=!!Bt,ja=!!Zt,qa=!!Vt,Ka=!!Rt,Za=!!Ut,Ya=!!It,Qa=!!kt,Ja=!!Ht,$a=!!Kt,er=!!$t,tr=ja?Ft.getParameter(Zt.MAX_DRAW_BUFFERS_WEBGL):0}var ar="webgl2"===Mt;St(),this.context=Ft;{var rr=Ft.getParameter(Ft.MAX_TEXTURE_IMAGE_UNITS),ir=Ft.getParameter(Ft.MAX_VERTEX_TEXTURE_IMAGE_UNITS),or=(Ft.getParameter(Ft.MAX_TEXTURE_SIZE),Ft.getParameter(Ft.MAX_CUBE_MAP_TEXTURE_SIZE)),nr=Ot?Ft.getParameter(Ot.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,sr=ir>0,lr=sr&&Rt,hr=!!Nt;zt||Wt||jt||qt?Ft.getParameter(Ft.COMPRESSED_TEXTURE_FORMATS):[]}XG.elementIndexUintAvailable=$a;{var dr=Ft.getShaderPrecisionFormat(Ft.VERTEX_SHADER,Ft.HIGH_FLOAT),cr=Ft.getShaderPrecisionFormat(Ft.VERTEX_SHADER,Ft.MEDIUM_FLOAT),ur=(Ft.getShaderPrecisionFormat(Ft.VERTEX_SHADER,Ft.LOW_FLOAT),Ft.getShaderPrecisionFormat(Ft.FRAGMENT_SHADER,Ft.HIGH_FLOAT)),fr=Ft.getShaderPrecisionFormat(Ft.FRAGMENT_SHADER,Ft.MEDIUM_FLOAT);Ft.getShaderPrecisionFormat(Ft.FRAGMENT_SHADER,Ft.LOW_FLOAT),Ft.getShaderPrecisionFormat(Ft.VERTEX_SHADER,Ft.HIGH_INT),Ft.getShaderPrecisionFormat(Ft.VERTEX_SHADER,Ft.MEDIUM_INT),Ft.getShaderPrecisionFormat(Ft.VERTEX_SHADER,Ft.LOW_INT),Ft.getShaderPrecisionFormat(Ft.FRAGMENT_SHADER,Ft.HIGH_INT),Ft.getShaderPrecisionFormat(Ft.FRAGMENT_SHADER,Ft.MEDIUM_INT),Ft.getShaderPrecisionFormat(Ft.FRAGMENT_SHADER,Ft.LOW_INT)}console.log("XG: render target support autodetection START (please ignore following warnings)");var pr=ft(Ft.RGB,Ft.RGB,Ft.UNSIGNED_BYTE),mr=Ka&&(ar?ft(Ft.RGB32F,Ft.RGB,Ft.FLOAT):ft(Ft.RGB,Ft.RGB,Ft.FLOAT)),vr=Ka&&(ar?ft(Ft.RGBA32F,Ft.RGBA,Ft.FLOAT):ft(Ft.RGBA,Ft.RGBA,Ft.FLOAT)),gr=Ka&&(ar?ft(Ft.R32F,Ft.RED,Ft.FLOAT):ft(Ft.LUMINANCE,Ft.LUMINANCE,Ft.FLOAT)),Sr=Ka&&(ar?ft(Ft.R32F,Ft.RED,Ft.FLOAT):ft(Ft.ALPHA,Ft.ALPHA,Ft.FLOAT)),Gr=Ka&&(ar?ft(Ft.RG32F,Ft.RG,Ft.FLOAT):ft(Ft.LUMINANCE_ALPHA,Ft.LUMINANCE_ALPHA,Ft.FLOAT)),xr=Za&&(ar?ft(Ft.RGB16F,Ft.RGB,Ft.HALF_FLOAT):ft(Ft.RGB,Ft.RGB,Ut.HALF_FLOAT_OES)),Mr=Za&&(ar?ft(Ft.RGBA16F,Ft.RGBA,Ft.HALF_FLOAT):ft(Ft.RGBA,Ft.RGBA,Ut.HALF_FLOAT_OES)),yr=Za&&(ar?ft(Ft.R16F,Ft.RED,Ft.HALF_FLOAT):ft(Ft.LUMINANCE,Ft.LUMINANCE,Ut.HALF_FLOAT_OES)),Xr=Za&&(ar?ft(Ft.R16F,Ft.RED,Ft.HALF_FLOAT):ft(Ft.ALPHA,Ft.ALPHA,Ut.HALF_FLOAT_OES)),Dr=Za&&(ar?ft(Ft.RG16F,Ft.RG,Ft.HALF_FLOAT):ft(Ft.LUMINANCE_ALPHA,Ft.LUMINANCE_ALPHA,Ut.HALF_FLOAT_OES)),_r=qa&&pt();console.log("XG: render target support autodetection END");var wr=dr.precision>0&&ur.precision>0,Ar=cr.precision>0&&fr.precision>0;"highp"!==yt||wr||(Ar?(yt="mediump",console.warn("XG.ForwardRenderer: highp not supported, using mediump")):(yt="lowp",console.warn("XG.ForwardRenderer: highp and mediump not supported, using lowp"))),"mediump"!==yt||Ar||(yt="lowp",console.warn("XG.ForwardRenderer: mediump not supported, using lowp"));var Cr=!1,Tr=XG.RendererUtils.getUvScale;this.getContext=function(){return Ft},this.getRenderingBackend=function(){return Mt},this.supportsStandardDerivatives=function(){return Wa},this.supportsElementIndexUint=function(){return $a},this.supportsFloatTextures=function(){return Ka},this.supportsHalfFloatTextures=function(){return Za},this.supportsFloatTexturesLinear=function(){return hr},this.supportsHalfFloatTexturesLinear=function(){return Ya},this.supportsVertexTextures=function(){return sr},this.supportsRGBUnsignedByteRenderTarget=function(){return pr},this.supportsLuminanceFloatRenderTarget=function(){return gr},this.supportsAlphaFloatRenderTarget=function(){return Sr},this.supportsLuminanceAlphaFloatRenderTarget=function(){return Gr},this.supportsRGBFloatRenderTarget=function(){return mr},this.supportsRGBAFloatRenderTarget=function(){return vr},this.supportsLuminanceHalfFloatRenderTarget=function(){return yr},this.supportsAlphaHalfFloatRenderTarget=function(){return Xr},this.supportsLuminanceAlphaHalfFloatRenderTarget=function(){return Dr},this.supportsRGBHalfFloatRenderTarget=function(){return xr},this.supportsRGBAHalfFloatRenderTarget=function(){return Mr},this.supportsDepthOnlyRenderTarget=function(){return _r},this.supportsDepthTextures=function(){return qa},this.supportsDrawBuffers=function(){return ja},this.supportsFragDepth=function(){return Ja},this.supportsShaderTextureLod=function(){return Qa},this.supportsInstancing=function(){return er},this.getMaxAnisotropy=function(){return nr},this.getPrecision=function(){return yt},this.setSize=function(e,t){xt.width=e*this.devicePixelRatio,xt.height=t*this.devicePixelRatio,xt.style.width=e+"px",xt.style.height=t+"px",this.setViewport(0,0,xt.width,xt.height)},this.setScale=function(e){Lt=e},this.setViewport=function(e,t,a,r){Xa=void 0!==e?e:0,Da=void 0!==t?t:0,_a=void 0!==a?a:xt.width,wa=void 0!==r?r:xt.height,Ft.viewport(Xa,Da,_a,wa)},this.setScissor=function(e,t,a,r){Ft.scissor(e,t,a,r)},this.enableScissorTest=function(e){e?Ft.enable(Ft.SCISSOR_TEST):Ft.disable(Ft.SCISSOR_TEST)},this.setClearColorHex=function(e,t){bt.setHex(e),Pt=t,Et&&bt.copyTonemapped(bt,Et,ea.brightness,ea.whitePoint),Ft.clearColor(bt.r,bt.g,bt.b,Pt)},this.setClearColor=function(e,t){Et?bt.copyTonemapped(e,Et,ea.brightness,ea.whitePoint):bt.copy(e),Pt=t,Ft.clearColor(bt.r,bt.g,bt.b,Pt)},this.getClearColor=function(){return bt},this.getClearAlpha=function(){return Pt},this.clear=function(e,t,a){var r=0;(void 0===e||e)&&(r|=Ft.COLOR_BUFFER_BIT),(void 0===t||t)&&(r|=Ft.DEPTH_BUFFER_BIT),(void 0===a||a)&&(r|=Ft.STENCIL_BUFFER_BIT),Ft.clear(r)},this.clearTarget=function(e,t,a,r){this.setRenderTarget(e),this.clear(t,a,r)},this.addPostPlugin=function(e){e.init(this),this.renderPluginsPost.push(e)},this.addPrePlugin=function(e){e.init(this),this.renderPluginsPre.push(e)},this.updateShadowMap=function(e,t){ra=null,ua=-1,Sa=-1,Ga=-1,na=-1,oa=-1,Va=!0,da=-1,ca=-1,this.shadowMapPlugin.update(e,t)};var br=function(e){var t=e.program;if(void 0!==t){e.program=void 0;var a,r,i,o=!1;for(a=0,r=ta.length;r>a;a++)if(i=ta[a],i.program===t){i.usedTimes--,0===i.usedTimes&&(o=!0);break}if(o===!0){var n=[];for(a=0,r=ta.length;r>a;a++)i=ta[a],i.program!==t&&n.push(i);ta=n,Ft.deleteProgram(t),ea.info.memory.programs--}}},Pr=function(e){for(var t=0,a=e.attributesList.length;a>t;t++){var r=e.attributesList[t];r.buffer||(r.buffer=Ft.createBuffer())}};this.setBuffers=function(e){for(var t,a,r=e.dynamic?Ft.DYNAMIC_DRAW:Ft.STATIC_DRAW,i=e.attributesList,o=0,n=i.length;n>o;o++)a=i[o],a.needsUpdate&&(t="index"===a.name?Ft.ELEMENT_ARRAY_BUFFER:Ft.ARRAY_BUFFER,Ft.bindBuffer(t,a.buffer),a.partialUpdate&&e.alreadyUploaded?Ft.bufferSubData(t,a.subOffset,a.array.subarray(a.subBegin,a.subEnd)):(Ft.bufferData(t,a.array,r),e.alreadyUploaded=!0),a.needsUpdate=!1,e.dynamic||delete a.array)};var Lr=function(e,t,a){for(var r,o,n,s,l,h=t.virtualAttributesList,d=0,c=h.length;c>d;d++)r=h[d],n=r.mapped,n&&(o=e[r.name],0>o||(s=n.buffer,l=n.itemSize,i(o),Ft.bindBuffer(Ft.ARRAY_BUFFER,s),Ft.vertexAttribPointer(o,l,Ft.FLOAT,!1,0,a*l*4)))},Er=function(e,t,a,r){for(var i,o=a.numSupportedMorphTargets,n=[],l=e.morphTargetInfluences,h=0,d=l.length;d>h;h++)i=l[h],i>0&&n.push([i,h]);n.length>o?(n.sort(s),n.length=o):0===n.length&&n.push([0,0]),e.__morphTargetInfluencesArray||(e.__morphTargetInfluencesArray=new Float32Array(ea.maxMorphTargets));for(var c,u,f=e.__morphTargetInfluencesArray,p=t.virtualAttributes,m=t.attributesList,v=t.morphTargets,g=0;o>g;)n[g]?(c=n[g][1],u=v[c].index,p["morphTarget"+g].mapped=m[u],p["morphNormal"+g].mapped=m[u+1],f[g]=l[c]):f[g]=0,g++;null!==r.uniforms.morphTargetInfluences&&Ft.uniform1fv(r.uniforms.morphTargetInfluences,f)};this.renderImmediateGeometry=function(e,t,a){e.hasPositions&&!e.__webglVertexBuffer&&(e.__webglVertexBuffer=Ft.createBuffer()),e.hasNormals&&!e.__webglNormalBuffer&&(e.__webglNormalBuffer=Ft.createBuffer()),e.hasUvs&&!e.__webglUvBuffer&&(e.__webglUvBuffer=Ft.createBuffer()),e.hasColors&&!e.__webglColorBuffer&&(e.__webglColorBuffer=Ft.createBuffer());var r=t.attributes;e.hasPositions&&r.position>=0&&(Ft.bindBuffer(Ft.ARRAY_BUFFER,e.__webglVertexBuffer),Ft.bufferData(Ft.ARRAY_BUFFER,e.positionArray,Ft.STREAM_DRAW),Ft.enableVertexAttribArray(r.position),Ft.vertexAttribPointer(r.position,3,Ft.FLOAT,!1,0,0)),e.hasNormals&&r.normal>=0&&(Ft.bindBuffer(Ft.ARRAY_BUFFER,e.__webglNormalBuffer),Ft.bufferData(Ft.ARRAY_BUFFER,e.normalArray,Ft.STREAM_DRAW),Ft.enableVertexAttribArray(r.normal),Ft.vertexAttribPointer(r.normal,3,Ft.FLOAT,!1,0,0)),e.hasUvs&&r.uv>=0&&(a.map||a.lightMap||a.bumpMap||a.normalMap||a.bumpDetailMap||a.normalDetailMap||a.normalGlossMap||a.glossMap||a.specularMap||a.displacementMap)&&(Ft.bindBuffer(Ft.ARRAY_BUFFER,e.__webglUvBuffer),Ft.bufferData(Ft.ARRAY_BUFFER,e.uvArray,Ft.STREAM_DRAW),Ft.enableVertexAttribArray(r.uv),Ft.vertexAttribPointer(r.uv,2,Ft.FLOAT,!1,0,0)),e.hasColors&&r.color>=0&&a.vertexColors&&(Ft.bindBuffer(Ft.ARRAY_BUFFER,e.__webglColorBuffer),Ft.bufferData(Ft.ARRAY_BUFFER,e.colorArray,Ft.STREAM_DRAW),Ft.enableVertexAttribArray(r.color),Ft.vertexAttribPointer(r.color,3,Ft.FLOAT,!1,0,0)),Ft.drawArrays(Ft.TRIANGLES,0,e.count),e.count=0},this.renderGeometry=function(e,r,i){var n=e.program,s=n.attributes,l=!1,h=16777215*r.id+n.id;if(h!==na&&(na=h,l=!0),l&&o(),i.morphTargetInfluences&&e.morphTargets&&Er(i,r,e,n),i instanceof XG.Mesh)if(r.attributes.index)t(r,s,l);else{var d=i instanceof XG.TriangleStrip?Ft.TRIANGLE_STRIP:Ft.TRIANGLES;a(r,s,d,l)}else if(i instanceof XG.Particles){var d=Ft.POINTS;a(r,s,d,l)}};var Fr=function(e,t){for(var a,r,i,o=0,s=0,l=e.length;l>s;s++)a=e[s],r=a.object,i=a.geometry,a.render=!1,a.id=r.id,r.visible&&r.enabled&&((r instanceof XG.Mesh||r instanceof XG.Particles)&&r.frustumCulled&&!Fa.contains(r,i)||(P(r,t),u(a),a.render=!0,ea.sortObjects===!0&&(null!==r.renderDepth?a.z=r.renderDepth:(Ua.copy(r.matrixWorld.getPosition()),Ra.multiplyVector3(Ua),a.z=Ua.data[2])),o+=1));ea.sortObjects&&o>0&&e.sort(n)};this.cullInstances=function(e,t,a){var r=t.numInstances;t.culledOffsets||(t.culledOffsets=new Float32Array(3*r),t.culledRotations=new Float32Array(4*r),t.srcOffsets=t.attributes.offset.array,t.srcRotations=t.attributes.rotation.array);for(var i=t.attributes.offset,o=t.attributes.rotation,n=t.srcOffsets,s=t.srcRotations,l=t.culledOffsets,h=t.culledRotations,d=0,c=0;r>c;c++){var u=a.containsInstance(e,t,c);if(u){var f=3*c,p=n[f],m=n[f+1],v=n[f+2],g=4*c,S=s[g],G=s[g+1],x=s[g+2],M=s[g+3],y=3*d;l[y]=p,l[y+1]=m,l[y+2]=v;var X=4*d;h[X]=S,h[X+1]=G,h[X+2]=x,h[X+3]=M,d+=1}}t.numVisibleInstances=d,o.array=h,i.array=l,o.needsUpdate=!0,i.needsUpdate=!0,o.partialUpdate=!0,i.partialUpdate=!0,o.subOffset=0,i.subOffset=0,o.subBegin=0,i.subBegin=0,o.subEnd=4*d,i.subEnd=3*d};var Rr=function(e,t){for(var a,r,i=0,o=e.length;o>i;i++)a=e[i],r=a.object,a.render=!1,r.visible&&r.enabled&&(Fa.contains(r,r)||!r.frustumCulled)&&(P(r,t),c(a),a.render=!0)},Ur=function(e){for(var t,a=0,r=e.length;r>a;a++)t=e[a],t.render&&u(t)},Nr=function(e){for(var t,a=0,r=e.length;r>a;a++)t=e[a],t.render&&c(t)};this.renderCube=function(e,t,a){var r=a.generateMipmaps;a.generateMipmaps=!1,a.activeCubeFace=0,this.render(e,t.px,a),a.activeCubeFace=1,this.render(e,t.nx,a),a.activeCubeFace=2,this.render(e,t.py,a),a.activeCubeFace=3,this.render(e,t.ny,a),a.activeCubeFace=4,this.render(e,t.pz,a),a.generateMipmaps=r,a.activeCubeFace=5,this.render(e,t.nz,a)},this.render=function(e,t,a,r){if(t instanceof XG.Camera==!1)return void console.error("XG.ForwardRenderer.render: camera is not an instance of XG.Camera.");var i=e.__lights,o=e.fog,n=e.heightFog;oa=-1,Va=!0,Ea.length=0,this.autoUpdateScene&&e.updateMatrixWorld(),this.autoUpdateView&&(void 0===t.parent&&t.updateMatrixWorld(),t.matrixWorldInverse.getInverse(t.matrixWorld),Ra.multiply(t.projectionMatrix,t.matrixWorldInverse),Fa.setFromMatrix(Ra)),this.autoUpdateObjects&&this.initWebGLObjects(e),Cr||(Gt(),Cr=!0),l(this.renderPluginsPre,e,t);for(var s=0,c=e.__webglObjects.length;c>s;s++){var u=e.__webglObjects[s].object,f=u.geometries;if(u instanceof XG.Mesh||u instanceof XG.Particles)for(var p=0,m=f.length;m>p;p++){var v=f[p],g=v.numInstances,S=g>0&&er;S&&(v.instanceCulled?(v.srcOffsets&&(v.attributes.offset.array=v.srcOffsets,v.attributes.rotation.array=v.srcRotations),ea.cullInstances(u,v,Fa),ea.setBuffers(v)):v.numVisibleInstances=g)}}this.setRenderTarget(a),(this.autoClear||r)&&this.clear(this.autoClearColor,this.autoClearDepth,this.autoClearStencil),this.autoUpdateView?(Fr(e.__webglObjects,t),Rr(e.__webglObjectsImmediate,t)):(Ur(e.__webglObjects),Nr(e.__webglObjectsImmediate)),this.setBlending(XG.NoBlending),h(e.__webglObjects,!0,"opaque",t,i,o,n,!1),d(e.__webglObjectsImmediate,"opaque",t,i,o,n,!1),h(e.__webglObjects,!1,"transparent",t,i,o,n,!0),d(e.__webglObjectsImmediate,"transparent",t,i,o,n,!0),l(this.renderPluginsPost,e,t),a&&a.generateMipmaps&&a.minFilter!==XG.NearestFilter&&a.minFilter!==XG.LinearFilter&&lt(a),this.setDepthTest(!0),this.setDepthWrite(!0);for(var s=0,c=e.__webglObjects.length;c>s;s++){var u=e.__webglObjects[s].object,f=u.geometries;if(u instanceof XG.Mesh||u instanceof XG.Particles)for(var p=0,m=f.length;m>p;p++){var v=f[p];v.srcOffsets&&(v.attributes.offset.array=v.srcOffsets,v.attributes.rotation.array=v.srcRotations)}}},this.renderImmediateObject=function(e,t){var a=e.program;na=-1,ea.setMaterialFaces(e),t.immediateRenderCallback?t.immediateRenderCallback(a,Ft,Fa):t.render(function(t){ea.renderImmediateGeometry(t,a,e)})},this.initWebGLObjects=function(e){for(e.__webglObjects||(e.__webglObjects=[],e.__webglObjectsImmediate=[]);e.__objectsAdded.length;)f(e.__objectsAdded[0],e),e.__objectsAdded.splice(0,1);for(;e.__objectsRemoved.length;)g(e.__objectsRemoved[0],e),e.__objectsRemoved.splice(0,1);for(var t=0,a=e.__webglObjects.length;a>t;t++)v(e.__webglObjects[t].object)},this.initMaterial=function(e,t,a,r,i){var o;e instanceof XG.EmissiveMaterial?o="emissive":e instanceof XG.PhongMaterial?o="phong":e instanceof XG.DynamicParticleMaterial&&(o="dynamicParticle"),o&&G(e,XG.ShaderLib[o]);var n,s,l=ct(t),h=ut(t),d=dt(r),c={map:!!e.map,lightMap:!!e.lightMap,bumpMap:!!e.bumpMap,normalMap:!!e.normalMap,normalGlossMap:!!e.normalGlossMap,bumpDetailMap:!!e.bumpDetailMap,normalDetailMap:!!e.normalDetailMap,glossMap:!!e.glossMap,specularMap:!!e.specularMap,displacementMap:!!e.displacementMap,vertexColors:e.vertexColors,fog:a,useFog:e.fog,isParticle:e.particle,sizeAttenuation:e.particle&&e.particleSizeAttenuation,interpolateParticleFrames:e.particle&&e.interpolateFrames&&e.numFrames>1,skinning:e.skinning,maxBones:d,useVertexTexture:lr&&r&&r.useVertexTexture,boneTextureWidth:r&&r.boneTextureWidth,boneTextureHeight:r&&r.boneTextureHeight,morphTargets:e.morphTargets&&this.maxMorphTargets>0,morphNormals:e.morphNormals&&this.maxMorphNormals>0,maxMorphTargets:this.maxMorphTargets,maxMorphNormals:this.maxMorphNormals,maxDirLights:l.directional,maxPointLights:l.point,maxSphereLights:l.sphere,maxTubeLights:l.tube,maxSpotLights:l.spot,maxHemiLights:l.hemi,maxAreaLights:l.area,areaTextures:l.areaTextures>0,maxImageLights:l.image,maxShadows:h,shadowMapEnabled:this.shadowMapEnabled&&r.receiveShadow&&h>0,shadowMapType:this.shadowMapType,shadowMapDebug:this.shadowMapDebug,shadowMapCascade:this.shadowMapCascade,shadowSampler:ar&&qa&&this.shadowMapUseDepthTextures,areaIndexOffset:l.areaIndexOffset,spotIndexOffset:l.spotIndexOffset,dirIndexOffset:l.dirIndexOffset,sphereIndexOffset:l.sphereIndexOffset,alphaTest:e.alphaTest,metal:e.metal,parallax:e.parallax,parallaxRefineSteps:e.parallaxRefineSteps,wrapAround:e.wrapAround,wrapAroundSkin:e.wrapAroundSkin,doubleSided:e.side===XG.DoubleSide,flipSided:e.side===XG.BackSide,instances:e.instances,osxHack:navigator.platform.toLowerCase().indexOf("mac")>=0},u={position:!0,normal:!0,uv:!0,uv2:!0,tangent:!0,color:!0};for(n=0;n<this.maxMorphTargets;n++)u["morphTarget"+n]=!0;for(n=0;n<this.maxMorphNormals;n++)u["morphNormal"+n]=!0;if(i){for(s in i.attributes)u[s]=!0;for(s in i.virtualAttributes)u[s]=!0}var f={viewMatrix:!0,viewInverseMatrix:!0,modelViewMatrix:!0,projectionMatrix:!0,normalMatrix:!0,modelMatrix:!0,cameraPosition:!0,morphTargetInfluences:!0};c.useVertexTexture?f.boneTexture=!0:f.boneGlobalMatrices=!0;for(s in e.uniforms)f[s]=!0;e.program=V(o,e,f,u,c);var p=e.program.uniforms;e.uniformsListUnique=[],e.uniformsListShared=[];for(var m in e.uniforms){var v=p[m];if(v){var g=e.uniforms[m],S=[g,v];g.shared?e.uniformsListShared.push(S):e.uniformsListUnique.push(S)}}if(e.morphTargets){var x=e.program.attributes;for(e.numSupportedMorphTargets=0,n=0;n<this.maxMorphTargets;n++)x["morphTarget"+n]>=0&&e.numSupportedMorphTargets++}},this.setProgram=function(e,t,a,r,i,o,n){la=0,i.needsUpdate&&(i.program&&br(i),ea.initMaterial(i,t,a,o,n),i.needsUpdate=!1);var s=!1,l=!1,h=i.program;h!==ra&&(Ft.useProgram(h),ra=h,s=!0,l=!0),i.id!==oa&&(oa=i.id,s=!0);var d=h.uniforms,c=i.uniforms;if(i.skinning)if(lr&&o.useVertexTexture){if(null!==d.boneTexture){var u=T();Ft.uniform1i(d.boneTexture,u),ea.setTexture(o.boneTexture,u)}}else null!==d.boneGlobalMatrices&&Ft.uniformMatrix4fv(d.boneGlobalMatrices,!1,o.boneMatrices);if(!l&&e===sa||null===d.projectionMatrix||(Ft.uniformMatrix4fv(d.projectionMatrix,!1,e.projectionMatrix.elements),e!==sa&&(sa=e)),l){if(a&&i.fog&&y(c,a,e),r&&i.defines&&i.defines.USE_HEIGHT_FOG&&X(c,r),i.lights&&(Va&&(I(t,e),Va=!1),_(c,Ha)),o.receiveShadow&&!i._shadowPass&&c.shadowMatrix&&null!==d.shadowMatrix&&A(c,Ha.shadowCasters),null!==d.viewMatrix&&Ft.uniformMatrix4fv(d.viewMatrix,!1,e.matrixWorldInverse.elements),null!==d.viewInverseMatrix&&Ft.uniformMatrix4fv(d.viewInverseMatrix,!1,e.matrixWorld.elements),null!==d.cameraPosition){var f=e.matrixWorld.getPosition();Ft.uniform3fv(d.cameraPosition,f.data)}b(i.uniformsListShared),ha=la}else la=ha;return s&&(i.particle&&M(c,i,e),(i instanceof XG.EmissiveMaterial||i instanceof XG.PhongMaterial||i instanceof XG.DynamicParticleMaterial)&&x(c,i),i instanceof XG.PhongMaterial&&D(c,i),b(i.uniformsListUnique)),C(d,o),h
  },this.setFaceCulling=function(e,t){e===XG.CullFaceNone?Ft.disable(Ft.CULL_FACE):(Ft.frontFace(t===XG.FrontFaceDirectionCW?Ft.CW:Ft.CCW),Ft.cullFace(e===XG.CullFaceBack?Ft.BACK:e===XG.CullFaceFront?Ft.FRONT:Ft.FRONT_AND_BACK),Ft.enable(Ft.CULL_FACE))},this.setMaterialFaces=function(e){var t=e.side===XG.DoubleSide,a=e.side===XG.BackSide;da!==t&&(t?Ft.disable(Ft.CULL_FACE):Ft.enable(Ft.CULL_FACE),da=t),ca!==a&&(Ft.frontFace(a?Ft.CW:Ft.CCW),ca=a)},this.setDepthTest=function(e){Sa!==e&&(e?Ft.enable(Ft.DEPTH_TEST):Ft.disable(Ft.DEPTH_TEST),Sa=e)},this.setDepthWrite=function(e){Ga!==e&&(Ft.depthMask(e),Ga=e)},this.setPolygonOffset=function(e,t,a){xa!==e&&(e?Ft.enable(Ft.POLYGON_OFFSET_FILL):Ft.disable(Ft.POLYGON_OFFSET_FILL),xa=e),(Ma!==t||ya!==a)&&(Ft.polygonOffset(t,a),Ma=t,ya=a)},this.setBlending=function(e,t,a,r,i,o){e!==ua&&(e===XG.NoBlending?Ft.disable(Ft.BLEND):e===XG.AdditiveBlending?(Ft.enable(Ft.BLEND),Ft.blendEquation(Ft.FUNC_ADD),Ft.blendFunc(Ft.SRC_ALPHA,Ft.ONE)):e===XG.SubtractiveBlending?(Ft.enable(Ft.BLEND),Ft.blendEquation(Ft.FUNC_ADD),Ft.blendFunc(Ft.ZERO,Ft.ONE_MINUS_SRC_COLOR)):e===XG.MultiplyBlending?(Ft.enable(Ft.BLEND),Ft.blendEquation(Ft.FUNC_ADD),Ft.blendFunc(Ft.ZERO,Ft.SRC_COLOR)):e===XG.CustomBlending?Ft.enable(Ft.BLEND):(Ft.enable(Ft.BLEND),Ft.blendEquationSeparate(Ft.FUNC_ADD,Ft.FUNC_ADD),Ft.blendFuncSeparate(Ft.SRC_ALPHA,Ft.ONE_MINUS_SRC_ALPHA,Ft.ONE,Ft.ONE_MINUS_SRC_ALPHA)),ua=e),e===XG.CustomBlending?(t!==fa&&(Ft.blendEquation(t),fa=t),(a!==pa||r!==ma||i!==va||o!==ga)&&(Ft.blendFuncSeparate(a,r,i,o),pa=a,ma=r,va=i,ga=o)):(fa=null,pa=null,ma=null,va=null,ga=null)},this.setTexture=function(e,t){e instanceof XG.Texture&&(e.__webglInit||(e.__webglInit=!0,e.__webglTexture=Ft.createTexture(),ea.info.memory.textures++,Ft.activeTexture(Ft.TEXTURE0+t),Ft.bindTexture(Ft.TEXTURE_2D,e.__webglTexture),Ea[t]=e.id,Ft.texImage2D(Ft.TEXTURE_2D,0,Ft.RGBA,1,1,0,Ft.RGBA,Ft.UNSIGNED_BYTE,za)),e.needsUpdate&&q(e,t)),Ea[t]!==e.id&&e.__webglTexture&&(Ft.activeTexture(Ft.TEXTURE0+t),Ft.bindTexture(Ft.TEXTURE_2D,e.__webglTexture),Ea[t]=e.id)},this.setRenderTarget=function(e){{var t,a,r,i,o,n=e instanceof XG.RenderTargetCube;e instanceof XG.RenderTargetArray}e?(st(e),t=n?e.__webglFramebuffer[e.activeCubeFace]:e.__webglFramebuffer,a=e.width,r=e.height,i=0,o=0):(t=null,a=_a,r=wa,i=Xa,o=Da),t!==ia&&(Ft.bindFramebuffer(Ft.FRAMEBUFFER,t),Ft.viewport(i,o,a,r),ia=t),Aa=a,Ca=r},void 0!==e.width&&void 0!==e.height&&this.setSize(e.width,e.height)},XG.DeferredRenderer=function(e){var t=this,a=void 0!==e.width?e.width:800,r=void 0!==e.height?e.height:600,i=void 0!==e.scale?e.scale:1,o=Math.max(1,Math.floor(i*a)),n=Math.max(1,Math.floor(i*r)),s=void 0!==e.tonemapping?e.tonemapping:XG.SimpleOperator,l=void 0!==e.antialias?e.antialias:!1,h=void 0!==e.dither?e.dither:!1,d=void 0!==e.useMultipleRenderTargets?e.useMultipleRenderTargets:!1,c=void 0!==e.backend?e.backend:"webgl1",u="webgl2"===c,f=void 0!==e.specularBRDF?e.specularBRDF:XG.GGXBRDF;t.brightness=void 0!==e.brightness?e.brightness:1,t.whitePoint=void 0!==e.whitePoint?e.whitePoint:1,this.renderer=e.renderer,void 0===this.renderer&&(this.renderer=new XG.ForwardRenderer({alpha:!1,antialias:!1,depth:!1,stencil:!1,tonemapping:XG.NoOperator,scale:i,backend:c}),this.renderer.setSize(a,r),this.renderer.setClearColorHex(0,0),this.renderer.gammaInput=!0,this.renderer.gammaOutput=!1,this.renderer.specularBRDF=f,this.renderer.autoClear=!1);var p=this.renderer.devicePixelRatio;o=Math.max(1,Math.floor(o*p)),n=Math.max(1,Math.floor(n*p)),this.domElement=this.renderer.domElement,this.shadowMapEnabled=!1,this.shadowMapAutoUpdate=!0,this.shadowMapType=XG.PCFSoftShadowMap,this.shadowMapSlopeDepthBias=!1,this.shadowMapSlopeScale=2,this.shadowMapSlopeBias=0,this.shadowMapSlopeMax=.001,this.shadowMapProjectionBias=1e-5,this.shadowMapCullFace=XG.CullFaceFront,this.shadowMapUseDepthTextures=!1,this.shadowMapDepthTextureType=XG.UnsignedIntType,this.shadowMapDepthTextureBias=0,this.shadowMapCascadeUpdateThreshold=2,this.shadowMapCascadeUpdateModulo=2,this.shadowMapDebug=!1,this.transparentShadows=!1,this.particlesOffscreen=!1,this.particlesOffscreenScale=.5,this.particlesOit=!1,this.particlesShadows=!1,this.ssaoEnabled=!1,this.ssaoScale=.5,this.ssaoRadius=1,this.ssaoSamples=9,this.bloomEnabled=!1,this.bloomScale=.25,this.bloomStrength=1,this.bloomThreshold=1,this.dofEnabled=!1,this.dofFancy=!1,this.dofPhysical=!0,this.dofLensFstop=4,this.dofLensFocalLength=50,this.dofLensBlurScale=50,this.dofLensMaxCoc=1,this.dofLensApertureSides=7,this.dofDebug=!1,this.dofAutofocus=!1,this.dofAutofocusPoint=new XG.Vector2(.5,.5),this.dofFocusDistance=1,this.dofFocusWidth=1,this.dofFocusRampWidth=2,this.dofMaxBlur=.2,this.fogEnabled=!1,this.fogColor=new XG.Color(0),this.fogStrength=.1,this.fogStart=100,this.specularMipFix=!1,this.useDepthTexture=!1,this.skinHighQuality=!1,d&&!this.renderer.supportsDrawBuffers()&&(console.warn("XG.DeferredRenderer: can't use multiple render targets, falling back to multipass."),d=!1);var m,v,g,S,G,x,M,y,X,D,_,w,A,C,T,b,P,L,E,F,R,U,N,I,B,O,k,V,H,z,W,j,q,K=!1,Z=this.renderer.context,Y=new XG.Projector,Q=new XG.Vector3,J=new XG.Vector3,$=new XG.Color(0),et=new XG.Color(16777215),tt=new XG.Vector3(1,1,1),at=XG.DeferredShaders.combined,rt=XG.DeferredShaders.color,it=XG.DeferredShaders.depth,ot=XG.DeferredShaders.normalDepth,nt=XG.DeferredShaders.composite,st=[],lt=new XG.Color,ht=0,dt=[],ct=[],ut=new XG.ShaderMaterial({uniforms:XG.UniformsUtils.clone(ot.uniforms),vertexShader:ot.vertexShader,fragmentShader:ot.fragmentShader,blending:XG.NoBlending}),ft=new XG.ShaderMaterial({uniforms:XG.UniformsUtils.clone(it.uniforms),vertexShader:it.vertexShader,fragmentShader:it.fragmentShader,blending:XG.NoBlending}),pt={},mt={},vt={},gt={},St=0,Gt=function(e,a){var r=XG.UniformsUtils.clone(at.uniforms),i={USE_MAP:!!e.map,USE_LIGHTMAP:!!e.lightMap,USE_BUMPMAP:!!e.bumpMap,USE_NORMALMAP:!!e.normalMap,USE_NORMALGLOSSMAP:!!e.normalGlossMap,USE_GLOSSMAP:!!e.glossMap,USE_BUMPDETAILMAP:!!e.bumpDetailMap,USE_NORMALDETAILMAP:!!e.normalDetailMap,USE_SPECULARMAP:!!e.specularMap,USE_DISPLACEMENTMAP:!!e.displacementMap,USE_PARALLAX:!!e.parallax,PARTICLE:e.particle,USE_PARTICLE_SIZEATTENUATION:e.particle&&e.particleSizeAttenuation,TEXTURE_DEPTH:t.useDepthTexture,MRT_OUTPUT:!0};if(e.parallax&&e.parallaxRefineSteps>0&&(i.PARALLAX_REFINE_STEPS=e.parallaxRefineSteps.toFixed(0).toString()),e.displacementMap)switch(e.displacementDirection){case XG.DisplaceByNormal:i.DISPLACE_BY_NORMAL=!0;break;case XG.DisplaceByPosition:i.DISPLACE_BY_POSITION=!0}var n={WEBGL_draw_buffers:!0};(i.USE_BUMPMAP||i.USE_NORMALMAP||i.USE_NORMALGLOSSMAP||i.USE_NORMALDETAILMAP||i.USE_BUMPDETAILMAP||i.USE_DISPLACEMENTMAP)&&(n.OES_standard_derivatives=!0);var s=new XG.ShaderMaterial({fragmentShader:at.fragmentShader,vertexShader:at.vertexShader,uniforms:r,defines:i,extensions:n,blending:XG.NoBlending,instances:e.instances}),l=void 0!==e.color?e.color:et,h=void 0!==e.specular?e.specular:$,d=void 0!==e.wrapRGB?e.wrapRGB:tt,c=void 0!==e.shininess?e.shininess:1,u=void 0!==e.wrapAround?e.wrapAround?-1:1:1;if(r.diffuse.value.setRGBA(l,u),r.specular.value.setRGBA(h,c),r.wrapRGB.value.copy(d),r.map.value=e.map,e.lightMap&&(r.lightMap.value=e.lightMap),e.bumpMap&&(r.bumpMap.value=e.bumpMap,r.bumpScale.value=e.bumpScale),(e.normalMap||e.normalGlossMap)&&(r.normalMap.value=e.normalGlossMap?e.normalGlossMap:e.normalMap,r.normalScale.value.copy(e.normalScale)),e.bumpDetailMap&&(r.bumpDetailMap.value=e.bumpDetailMap),e.normalDetailMap&&(r.normalDetailMap.value=e.normalDetailMap),(e.bumpDetailMap||e.normalDetailMap)&&r.detailRepeatScale.value.set(e.detailRepeat.x,e.detailRepeat.y,e.detailScale),e.specularMap&&(r.specularMap.value=e.specularMap),e.glossMap&&(r.glossMap.value=e.glossMap),e.displacementMap&&(r.displacementMap.value=e.displacementMap,r.displacementScaleBias.value.set(e.displacementScale,e.displacementBias),r.displacementNormalScale.value=e.displacementNormalScale),e.particle&&(r.particleSize.value=e.particleSize,r.screenWidth.value=o),e.particle&&e.particleSizeAttenuation&&dt.push({material:s}),e.parallax&&(r.parallaxScale.value=e.parallaxScale),s.vertexColors=e.vertexColors,s.morphTargets=e.morphTargets,s.morphNormals=e.morphNormals,s.skinning=e.skinning,s.alphaTest=e.alphaTest,s.side=e.side,s.visible=e.visible,void 0!==a){var f=a.offset,p=a.repeat;r.offsetRepeat.value.set(f.data[0],f.data[1],p.data[0],p.data[1])}return s},xt=function(e,t){var a=XG.UniformsUtils.clone(rt.uniforms),r={USE_MAP:!!e.map,USE_LIGHTMAP:!!e.lightMap,USE_SPECULARMAP:!!e.specularMap,USE_NORMALGLOSSMAP:!!e.normalGlossMap,USE_GLOSSMAP:!!e.glossMap,USE_BUMPMAP:!!e.bumpMap&&e.parallax,USE_PARALLAX:!!e.parallax,USE_DISPLACEMENTMAP:!!e.displacementMap,PARTICLE:e.particle,USE_PARTICLE_SIZEATTENUATION:e.particle&&e.particleSizeAttenuation};if(e.parallax&&e.parallaxRefineSteps>0&&(r.PARALLAX_REFINE_STEPS=e.parallaxRefineSteps.toFixed(0).toString()),e.displacementMap)switch(e.displacementDirection){case XG.DisplaceByNormal:r.DISPLACE_BY_NORMAL=!0;break;case XG.DisplaceByPosition:r.DISPLACE_BY_POSITION=!0}var i={};(r.USE_BUMPMAP||r.USE_PARALLAX)&&(i.OES_standard_derivatives=!0);var n=new XG.ShaderMaterial({fragmentShader:rt.fragmentShader,vertexShader:rt.vertexShader,uniforms:a,defines:r,extensions:i,instances:e.instances}),s=void 0!==e.color?e.color:et,l=void 0!==e.specular?e.specular:$,h=void 0!==e.wrapRGB?e.wrapRGB:tt,d=void 0!==e.shininess?e.shininess:1,c=void 0!==e.wrapAround?e.wrapAround?-1:1:1;if(a.diffuse.value.setRGBA(s,c),a.specular.value.setRGBA(l,d),a.wrapRGB.value.copy(h),a.map.value=e.map,e.lightMap&&(a.lightMap.value=e.lightMap),e.specularMap&&(a.specularMap.value=e.specularMap),e.glossMap&&(a.glossMap.value=e.glossMap),e.normalGlossMap&&(a.normalMap.value=e.normalGlossMap),e.displacementMap&&(a.displacementMap.value=e.displacementMap,a.displacementScaleBias.value.set(e.displacementScale,e.displacementBias)),e.particle&&(a.particleSize.value=e.particleSize,a.screenWidth.value=o),e.particle&&e.particleSizeAttenuation&&dt.push({material:n}),e.parallax&&(a.parallaxScale.value=e.parallaxScale,a.bumpMap.value=e.bumpMap),n.vertexColors=e.vertexColors,n.morphTargets=e.morphTargets,n.morphNormals=e.morphNormals,n.skinning=e.skinning,n.alphaTest=e.alphaTest,n.side=e.side,n.visible=e.visible,void 0!==t){var u=t.offset,f=t.repeat;a.offsetRepeat.value.set(u.data[0],u.data[1],f.data[0],f.data[1])}return n},Mt=function(e,t){var a={USE_BUMPMAP:!!e.bumpMap,USE_NORMALMAP:!!e.normalMap,USE_NORMALGLOSSMAP:!!e.normalGlossMap,USE_BUMPDETAILMAP:!!e.bumpDetailMap,USE_NORMALDETAILMAP:!!e.normalDetailMap,USE_DISPLACEMENTMAP:!!e.displacementMap,USE_PARALLAX:!!e.parallax,PARTICLE:e.particle,USE_PARTICLE_SIZEATTENUATION:e.particle&&e.particleSizeAttenuation};if(e.parallax&&e.parallaxRefineSteps>0&&(a.PARALLAX_REFINE_STEPS=e.parallaxRefineSteps.toFixed(0).toString()),e.displacementMap)switch(e.displacementDirection){case XG.DisplaceByNormal:a.DISPLACE_BY_NORMAL=!0;break;case XG.DisplaceByPosition:a.DISPLACE_BY_POSITION=!0}var r={};if((a.USE_BUMPMAP||a.USE_NORMALMAP||a.USE_NORMALGLOSSMAP||a.USE_NORMALDETAILMAP||a.USE_BUMPDETAILMAP||a.USE_PARALLAX||a.USE_DISPLACEMENTMAP)&&(r.OES_standard_derivatives=!0),e.morphTargets||e.skinning||e.bumpMap||e.normalMap||e.alphaTest||e.particle||e.displacementMap||e.instances){var i=XG.UniformsUtils.clone(ot.uniforms),n=new XG.ShaderMaterial({uniforms:i,vertexShader:ot.vertexShader,fragmentShader:ot.fragmentShader,blending:XG.NoBlending,instances:e.instances});if(n.morphTargets=e.morphTargets,n.morphNormals=e.morphNormals,n.skinning=e.skinning,e.bumpMap&&(i.bumpMap.value=e.bumpMap,i.bumpScale.value=e.bumpScale),(e.normalMap||e.normalGlossMap)&&(i.normalMap.value=e.normalGlossMap?e.normalGlossMap:e.normalMap,i.normalScale.value.copy(e.normalScale)),e.bumpDetailMap&&(i.bumpDetailMap.value=e.bumpDetailMap),e.normalDetailMap&&(i.normalDetailMap.value=e.normalDetailMap),(e.bumpDetailMap||e.normalDetailMap)&&i.detailRepeatScale.value.set(e.detailRepeat.x,e.detailRepeat.y,e.detailScale),e.displacementMap&&(i.displacementMap.value=e.displacementMap,i.displacementScaleBias.value.set(e.displacementScale,e.displacementBias),i.displacementNormalScale.value=e.displacementNormalScale),void 0!==t){var s=t.offset,l=t.repeat;i.offsetRepeat.value.set(s.data[0],s.data[1],l.data[0],l.data[1])}e.alphaTest&&e.map&&(i.alphaMap.value=e.map),e.particle&&(i.particleSize.value=e.particleSize,i.screenWidth.value=o,e.particleSizeAttenuation&&dt.push({material:n})),e.parallax&&(i.parallaxScale.value=e.parallaxScale)}else var n=ut.clone();return n.defines=a,n.extensions=r,n.vertexColors=e.vertexColors,n.side=e.side,n.alphaTest=e.alphaTest,n.visible=e.visible,n},yt=function(e,a){var r={PARTICLE:e.particle,USE_PARTICLE_SIZEATTENUATION:e.particle&&e.particleSizeAttenuation,USE_DISPLACEMENTMAP:!!e.displacementMap,SLOPE_DEPTH_BIAS:t.shadowMapSlopeDepthBias,DEPTH_TEXTURES:t.shadowMapUseDepthTextures&&t.renderer.supportsDepthTextures()},i={};if(r.SLOPE_DEPTH_BIAS&&!r.DEPTH_TEXTURES&&(i.OES_standard_derivatives=!0),e.displacementMap)switch(e.displacementDirection){case XG.DisplaceByNormal:r.DISPLACE_BY_NORMAL=!0;break;case XG.DisplaceByPosition:r.DISPLACE_BY_POSITION=!0}if(e.morphTargets||e.skinning||e.alphaTest||e.particle||e.displacementMap||e.instances){var n=XG.UniformsUtils.clone(it.uniforms),s=new XG.ShaderMaterial({uniforms:n,vertexShader:it.vertexShader,fragmentShader:it.fragmentShader,blending:XG.NoBlending,instances:e.instances});if(s.morphTargets=e.morphTargets,s.skinning=e.skinning,void 0!==a){var l=a.offset,h=a.repeat;n.offsetRepeat.value.set(l.data[0],l.data[1],h.data[0],h.data[1])}e.alphaTest&&e.map&&(n.alphaMap.value=e.map),e.displacementMap&&(n.displacementMap.value=e.displacementMap,n.displacementScaleBias.value.set(e.displacementScale,e.displacementBias)),e.particle&&(n.particleSize.value=e.particleSize,n.screenWidth.value=o,e.particleSizeAttenuation&&dt.push({material:s}))}else var s=ft.clone();return t.shadowMapSlopeDepthBias&&(s.uniforms.slopeScale.value=t.shadowMapSlopeScale,s.uniforms.slopeBias.value=t.shadowMapSlopeBias,s.uniforms.slopeMax.value=t.shadowMapSlopeMax),s.defines=r,s.extensions=i,s.vertexColors=e.vertexColors,s.alphaTest=e.alphaTest,s.visible=e.visible,s.side=t.shadowMapCullFace===XG.CullFaceFront?XG.BackSide:XG.FrontSide,s},Xt=function(e){var t=e.properties,a=_t(e.materials);t.combinedMaterials=a.combinedMaterials,t.colorMaterials=a.colorMaterials,t.depthMaterials=a.depthMaterials,t.normalDepthMaterials=a.normalDepthMaterials,t.forwardMaterials=e.materials,t.deferredInitialized=!0,t.deferredNeedsUpdate=!1},Dt=XG.RendererUtils.getUvScale,_t=function(e){for(var t={combinedMaterials:[],colorMaterials:[],depthMaterials:[],normalDepthMaterials:[]},a=0,r=e.length;r>a;a++){var i=e[a],o=Dt(i);if(d){void 0===pt[i.id]&&(pt[i.id]=Gt(i,o));var n=pt[i.id];t.combinedMaterials.push(n)}else{void 0===mt[i.id]&&(mt[i.id]=xt(i,o));var s=mt[i.id];t.colorMaterials.push(s),void 0===vt[i.id]&&(vt[i.id]=Mt(i,o));var l=vt[i.id];t.normalDepthMaterials.push(l)}void 0===gt[i.id]&&(gt[i.id]=yt(i,o));var h=gt[i.id];t.depthMaterials.push(h)}return t},wt=function(e){for(var t,a,r,i=e.properties,o=i.forwardMaterials,n=i.combinedMaterials,s=i.colorMaterials,l=i.depthMaterials,h=i.normalDepthMaterials,c=0,u=o.length;u>c;c++){var f=o[c],p=f.visible,m=Dt(f),v=l[c];if(v.visible=p,r=v.uniforms,d){var g=n[c];g.visible=p,t=g.uniforms}else{var S=s[c],G=h[c];S.visible=p,G.visible=p,t=S.uniforms,a=G.uniforms}if(t.map.value=f.map,f instanceof XG.PhongMaterial){var x=f.wrapAround?-1:1,M=f.shininess,y=f.color,X=f.specular,D=f.wrapRGB;t.diffuse.value.setRGBA(y,x),t.specular.value.setRGBA(X,M),t.wrapRGB.value.copy(D),t.lightMap.value=f.lightMap,t.specularMap.value=f.specularMap,t.glossMap.value=f.glossMap,t.bumpMap.value=f.bumpMap,t.normalMap.value=f.normalGlossMap?f.normalGlossMap:f.normalMap,t.displacementMap.value=f.displacementMap,t.parallaxScale.value=f.parallaxScale,t.displacementScaleBias.value.set(f.displacementScale,f.displacementBias),d?(t.bumpDetailMap.value=f.bumpDetailMap,t.normalDetailMap.value=f.normalDetailMap,t.detailRepeatScale.value.set(f.detailRepeat.x,f.detailRepeat.y,f.detailScale),t.normalScale.value.copy(f.normalScale),t.bumpScale.value=f.bumpScale,t.displacementNormalScale.value=f.displacementNormalScale):(a.bumpMap.value=f.bumpMap,a.normalMap.value=f.normalGlossMap?f.normalGlossMap:f.normalMap,a.bumpDetailMap.value=f.bumpDetailMap,a.normalDetailMap.value=f.normalDetailMap,a.detailRepeatScale.value.set(f.detailRepeat.x,f.detailRepeat.y,f.detailScale),a.normalScale.value.copy(f.normalScale),a.bumpScale.value=f.bumpScale,a.parallaxScale.value=f.parallaxScale,a.displacementMap.value=f.displacementMap,a.displacementScaleBias.value.set(f.displacementScale,f.displacementBias),a.displacementNormalScale.value=f.displacementNormalScale,f.alphaTest&&f.map&&(a.alphaMap.value=f.map)),f.alphaTest&&f.map&&(r.alphaMap.value=f.map),f.displacementMap&&(r.displacementMap.value=f.displacementMap,r.displacementScaleBias.value.set(f.displacementScale,f.displacementBias))}if(m){var _=m.offset,w=m.repeat;t.offsetRepeat.value.set(_.data[0],_.data[1],w.data[0],w.data[1]),r.offsetRepeat.value.set(_.data[0],_.data[1],w.data[0],w.data[1]),d||a.offsetRepeat.value.set(_.data[0],_.data[1],w.data[0],w.data[1])}}i.deferredNeedsUpdate=!1},At=function(e){var a,r,i,o,n,s,l,h=e.__objects,d=e.__lights;for(a=0,r=h.length;r>a;a++)n=h[a],l=n.properties,n.materials&&(l.deferredInitialized?l.deferredNeedsUpdate&&wt(n):Xt(n));for(a=0,r=d.length;r>a;a++)s=d[a],s.properties.deferredInitialized||(s instanceof XG.PointLight?(i=new XG.PointLightProxy(s,t),o=s.distance>0?z:H):s instanceof XG.SphereLight?(i=new XG.SphereLightProxy(s,t),o=s.distance>0?z:H):s instanceof XG.TubeLight?(i=new XG.TubeLightProxy(s,t),o=H):s instanceof XG.SpotLight?(i=new XG.SpotLightProxy(s,t),o=H):s instanceof XG.DirectionalLight?(i=new XG.DirectionalLightProxy(s,t),o=H):s instanceof XG.HemisphereLight?(i=new XG.HemisphereLightProxy(s,t),o=H):s instanceof XG.DayLight?(i=new XG.DayLightProxy(s,t),o=H):s instanceof XG.DayLightCube?(i=new XG.DayLightCubeProxy(s,t),o=H):s instanceof XG.AreaLight?(i=new XG.AreaLightProxy(s,t),o=H):s instanceof XG.ImageLight&&(i=new XG.ImageLightProxy(s,t),o=s.local?z:H),i&&(o.add(i),ct.push(i)),s.castShadow&&W.properties.shadowCasters.push(s),s.properties.deferredInitialized=!0)},Ct=function(e,t,a,r,i,o){for(var n=0,s=e.length;s>n;n++){var l=e[n];l.blending=t,t===XG.CustomBlending&&(l.blendSrcColor=a,l.blendDstColor=r,l.blendSrcAlpha=i,l.blendDstAlpha=o)}},Tt=function(e){for(var t=[],a=0,r=e.length;r>a;a++)t[a]=e[a].clone();return t},bt=function(){return d&&t.useDepthTexture?{TEXTURE_DEPTH:!0}:d&&!t.useDepthTexture?{RGBA_DEPTH:!0}:{FLOAT_DEPTH:!0}},Pt=function(e,t){Rt(e,t,!0,!1,!1)},Lt=function(e,t){Rt(e,t,!1,!0,!1)},Et=function(e,t){Rt(e,t,!1,!1,!0)},Ft=function(e,t){Rt(e,t,!0,!0,!0)},Rt=function(e,a,r,i,o){for(var n=e.__objects,s=0,l=n.length;l>s;s++){var h=n[s];if(h.materials){var d=h.properties,c=d[a];if(c){h.materials=c;for(var u=!0,f=d.forwardMaterials,p=0,m=c.length;m>p;p++){var v=c[p],g=f[p],S=g.transparent,G=!S,x=!(S||g instanceof XG.PhongMaterial),M=g.particle&&S;v.enabled=S&&i||G&&r||x&&o,v.enabled=v.enabled&&(!M||!t.particlesOffscreen),v.enabled=v.enabled&&!(x&&!o),u=u&&!v.enabled}h.enabled=!u}}}},Ut=function(e){Nt(e,4)},Nt=function(e,t){for(var a,r=e.__objects,i=0,o=r.length;o>i;i++)if(a=r[i],a.materials)if(a instanceof XG.Particles||4===t&&!a.castShadow)for(var n=0,s=a.materials.length;s>n;n++){var l=a.materials[n];l.enabled=!1}else{var h,d=a.properties,c=d.forwardMaterials;if(0===t);else if(1===t);else if(2===t);else if(3===t);else if(4===t){if(void 0===d.forwardMaterialsTranslucency){var u=Tt(c);Ct(u,XG.AdditiveBlending),d.forwardMaterialsTranslucency=u}h=d.forwardMaterialsTranslucency,It(h)}if(t>0)for(var n=0,s=c.length;s>n;n++){var f=c[n],p=h[n];p.additiveFactor=f.additiveFactor}a.enabled=!0,a.materials=h}},It=function(e){for(var t=0,a=e.length;a>t;t++){{var r=e[t];r.uniforms}if(!r.particle&&r.transparent){if(r.enabled=!0,!r.defines){var i=bt();i.TRANSLUCENT_PASS=!0,r.defines=i}}else r.enabled=!1}},Bt=function(e){zt(e,0)},Ot=function(e){zt(e,1)},kt=function(e){zt(e,2)},Vt=function(e){zt(e,3)},Ht=function(e){zt(e,4)},zt=function(e,t){for(var a,r=e.__objects,i=0,o=r.length;o>i;i++)if(a=r[i],a.materials)if(a instanceof XG.Particles&&(4!==t||a.castShadow)){var n,s=a.properties,l=s.forwardMaterials;if(0===t)n=l,Wt(n,!1);else if(1===t){if(void 0===s.forwardMaterialsMRT){var h=Tt(l);Ct(h,XG.CustomBlending,XG.OneFactor,XG.OneFactor,XG.ZeroFactor,XG.OneMinusSrcAlphaFactor),s.forwardMaterialsMRT=h}n=s.forwardMaterialsMRT,Wt(n,!1)}else if(2===t){if(void 0===s.forwardMaterialsAccumulation){var d=Tt(l);Ct(d,XG.CustomBlending,XG.OneFactor,XG.OneFactor,XG.ZeroFactor,XG.OneMinusSrcAlphaFactor),s.forwardMaterialsAccumulation=d}n=s.forwardMaterialsAccumulation,Wt(n,!0)}else if(3===t){if(void 0===s.forwardMaterialsRevealage){var c=Tt(l);Ct(c,XG.CustomBlending,XG.OneFactor,XG.OneFactor,XG.ZeroFactor,XG.OneMinusSrcAlphaFactor),s.forwardMaterialsRevealage=c}n=s.forwardMaterialsRevealage,Wt(n,!1)}else if(4===t){if(void 0===s.forwardMaterialsTranslucency){var u=Tt(l);Ct(u,XG.AdditiveBlending),s.forwardMaterialsTranslucency=u}n=s.forwardMaterialsTranslucency,jt(n)}if(t>0)for(var f=0,p=l.length;p>f;f++){var m=l[f],v=n[f];v.time=m.time,v.additiveFactor=m.additiveFactor}a.enabled=!0,a.materials=n}else for(var f=0,p=a.materials.length;p>f;f++){var g=a.materials[f];g.enabled=!1}},Wt=function(e,a){for(var r=0,i=e.length;i>r;r++){var s=e[r],l=s.uniforms;if(s.particle&&s.transparent){if(s.enabled=!0,!s.defines){var h=bt();t.particlesOffscreen&&(h.OFFSCREEN_PARTICLES=!0),t.fogEnabled&&(h.FOG_ENABLED=!0),s.lights&&(d||a)&&(h.USE_LIGHTS=!0),t.particlesOit&&(h.OIT_PARTICLES=!0,d?(h.OIT_MRT_PASS=!0,h.MRT_OUTPUT=!0):a?h.OIT_ACCUMULATION_PASS=!0:h.OIT_REVEALAGE_PASS=!0),s.defines=h}s.extensions||(s.extensions={}),t.particlesOit&&d&&(s.extensions.WEBGL_draw_buffers=!0),l&&(l.tDepth.value=d?m.renderTarget2.colorTexture[4]:g.renderTarget2,t.fogEnabled&&(l.fogColor.value.copy(t.fogColor),l.fogStrength.value=t.fogStrength,l.fogStart.value=t.fogStart),l.viewSize.value.set(o*t.particlesOffscreenScale,n*t.particlesOffscreenScale))}else s.enabled=!1}},jt=function(e){for(var t=0,a=e.length;a>t;t++){{var r=e[t];r.uniforms}if(r.particle&&r.transparent){if(r.enabled=!0,!r.defines){var i=bt();i.TRANSLUCENT_PASS=!0,r.defines=i}}else r.enabled=!1}},qt=function(e,a,r){for(var i=0,o=e.length;o>i;i++){var n=e[i],s=n.uniforms,l=a[i].transparent;n.enabled=!l,r?(n.polygonOffset=!0,n.polygonOffsetFactor=1.5,n.polygonOffsetUnits=10,s.depthTextureBias.value=t.shadowMapDepthTextureBias):(s.slopeScale.value=t.shadowMapSlopeScale,s.slopeBias.value=t.shadowMapSlopeBias,s.slopeMax.value=t.shadowMapSlopeMax),n.side=t.shadowMapCullFace===XG.CullFaceFront?XG.BackSide:t.shadowMapCullFace===XG.CullFaceBack?XG.FrontSide:XG.DoubleSide}},Kt=function(e,t){for(var a,r=e.__objects,i=0,o=r.length;o>i;i++)if(a=r[i],a.materials)if(a.castShadow){var n=a.properties.depthMaterials;a.materials=n,qt(n,a.properties.forwardMaterials,t)}else for(var s=0,l=a.materials.length;l>s;s++){var h=a.materials[s];h.enabled=!1}},Zt=function(e,t){e.position.copy(t.matrixWorld.getPosition()),t.target&&e.lookAt(t.target.matrixWorld.getPosition()),e.updateMatrixWorld(),e.matrixWorldInverse.getInverse(e.matrixWorld)},Yt=function(e,t){e.near=t.shadowCameraNear,e.far=t.shadowCameraFar,t instanceof XG.PointLight||t instanceof XG.SphereLight?e.fov=90:t instanceof XG.SpotLight||t instanceof XG.AreaLight?e.fov=t.shadowCameraFov:(t instanceof XG.DirectionalLight||t instanceof XG.DayLight||t instanceof XG.DayLightCube||t instanceof XG.AreaLight)&&(e.left=t.shadowCameraLeft,e.right=t.shadowCameraRight,e.top=t.shadowCameraTop,e.bottom=t.shadowCameraBottom),e.updateProjectionMatrix()},Qt=function(e,t,a,r){e.near=t.shadowCameraNear,e.far=t.shadowCameraFar;var i=t.shadowCascadeNearZ[a],o=t.shadowCascadeFarZ[a],n=t.properties.pointsFrustum[a];n[0].setZ(i),n[1].setZ(i),n[2].setZ(i),n[3].setZ(i),n[4].setZ(o),n[5].setZ(o),n[6].setZ(o),n[7].setZ(o);var s=t.properties.pointsWorld[a];Q.set(1/0,1/0,1/0),J.set(-1/0,-1/0,-1/0);for(var l=Q.data,h=J.data,d=0;8>d;d++){var c=s[d],u=c.data;c.copy(n[d]),Y.unprojectVector(c,r),e.matrixWorldInverse.multiplyVector3(c),u[0]<l[0]&&(l[0]=u[0]),u[0]>h[0]&&(h[0]=u[0]),u[1]<l[1]&&(l[1]=u[1]),u[1]>h[1]&&(h[1]=u[1]),u[2]<l[2]&&(l[2]=u[2]),u[2]>h[2]&&(h[2]=u[2])}e.left=l[0],e.right=h[0],e.top=h[1],e.bottom=l[1],e.updateProjectionMatrix()},Jt=function(e,a,r){var i=t.renderer,o=a.projectionMatrix.elements,n=o[10];o[10]*=1+t.shadowMapProjectionBias,i.render(e,a,r,!0),o[10]=n},$t=function(e,a){var r=t.renderer;r.autoClearDepth=!0,r.autoClearStencil=!1,r.autoUpdateScene=!1;var i=t.shadowMapUseDepthTextures&&r.supportsDepthTextures();i?(r.autoClearColor=!1,Z.colorMask(!1,!1,!1,!1)):(lt.copy(r.getClearColor()),ht=r.getClearAlpha(),r.setClearColor(et,1)),Kt(e,i);for(var o=e.properties.shadowCasters,n=0,s=o.length;s>n;n++){var l=o[n];if(l instanceof XG.SpotLight||l instanceof XG.AreaLight){var h=l.properties.shadowMap,d=l.properties.shadowCamera;Zt(d,l),Yt(d,l),Jt(e,d,h)}else if(l instanceof XG.DirectionalLight||l instanceof XG.DayLight||l instanceof XG.DayLightCube){for(var c=0;c<l.properties.cascadeCount;c++)if(!(c>t.shadowMapCascadeUpdateThreshold&&St%t.shadowMapCascadeUpdateModulo!==0)){var h=l.properties.shadowMap[c],d=l.properties.shadowCamera[c];Zt(d,l),l.shadowCascade?Qt(d,l,c,a):Yt(d,l),Jt(e,d,h)}}else if(l instanceof XG.PointLight||l instanceof XG.SphereLight)for(var c=0;6>c;c++){var h=l.properties.shadowMap[c],d=l.properties.shadowCamera[c];Zt(d,l),Yt(d,l),Jt(e,d,h)}}i?(r.autoClearColor=!0,Z.colorMask(!0,!0,!0,!0)):r.setClearColor(lt,ht)},ea=function(e,t){if(t.properties.gyro)var a=t.properties.nonGyroLight,r=t.properties.nonGyroTarget;else var a=t,r=t.target;e.position.copy(a.matrixWorld.getPosition()),t.target&&e.lookAt(r.matrixWorld.getPosition()),e.updateMatrixWorld(),e.matrixWorldInverse.getInverse(e.matrixWorld)},ta=function(e,t){e.near=t.textureCameraNear,e.far=t.textureCameraFar,t instanceof XG.PointLight||t instanceof XG.SphereLight?e.fov=90:t instanceof XG.SpotLight||t instanceof XG.AreaLight?e.fov=t.textureCameraFov:(t instanceof XG.DirectionalLight||t instanceof XG.DayLight||t instanceof XG.DayLightCube||t instanceof XG.AreaLight)&&(e.left=t.textureCameraLeft,e.right=t.textureCameraRight,e.top=t.textureCameraTop,e.bottom=t.textureCameraBottom),e.updateProjectionMatrix()},aa=function(e){var a=t.renderer;a.autoClearDepth=!1,a.autoClearStencil=!1,a.autoUpdateScene=!1,lt.copy(a.getClearColor()),ht=a.getClearAlpha(),a.setClearColor($,0);var r=e.properties.shadowCasters;if(t.particlesShadows){Ht(e);for(var i=0,o=r.length;o>i;i++){var n=r[i];if(n.castTransparentShadow&&(n instanceof XG.DirectionalLight||n instanceof XG.DayLight||n instanceof XG.DayLightCube||n instanceof XG.SpotLight)){var s=n.texture,l=n.properties.textureCamera;ea(l,n),ta(l,n),a.render(e,l,s,!0)}}}Ut(e);for(var i=0,o=r.length;o>i;i++){var n=r[i];if(n.castTransparentShadow&&(n instanceof XG.DirectionalLight||n instanceof XG.DayLight||n instanceof XG.DayLightCube||n instanceof XG.SpotLight)){var s=n.texture,l=n.properties.textureCamera;t.particlesShadows&&(ea(l,n),ta(l,n)),a.render(e,l,s,!t.particlesShadows)}}a.setClearColor(lt,ht)},ra=function(){var e=t.renderer,a=e.shadowMapUseDepthTextures;e.shadowMapEnabled=t.shadowMapEnabled,e.shadowMapAutoUpdate=!1,e.shadowMapUseDepthTextures=!0,Z.depthFunc(Z.LEQUAL),G.render(),e.shadowMapUseDepthTextures=a},ia=function(e,a){q.enabled=!1;var r=e.properties.mirrors;if(void 0!==r){var i=r.length;if(0!==i){var s=t.renderer;s.autoClearDepth=!0,Z.depthFunc(Z.LEQUAL),Ft(e,"forwardMaterials");var l=s.shadowMapUseDepthTextures;s.shadowMapEnabled=t.shadowMapEnabled,s.shadowMapAutoUpdate=!1,s.shadowMapUseDepthTextures=!0;for(var h=d?m.renderTarget2.colorTexture[4]:g.renderTarget2,c=0;i>c;c++){var u=r[c],f=u.material.uniforms,p=u.material.defines;f.refractionSampler.value=j,f.refractionDepthSampler.value=h,f.matProjInverse.value=a.projectionMatrixInverse,f.matViewInverse.value=a.matrixWorld,f.viewSize.value.set(o,n),p.USE_MRT=d,u.render(e,a)}q.enabled=!0,s.autoClearDepth=!1,s.shadowMapUseDepthTextures=l}}},oa=function(e){t.particlesOit?d?(Ot(e),x.render()):(kt(e),x.render(),Vt(e),M.render()):(Bt(e),x.render())},na=function(){var e=t.renderer;e.autoClearDepth=!0,Z.depthFunc(Z.LEQUAL),m.render()},sa=function(){var e=t.renderer;e.autoClearDepth=!0,Z.depthFunc(Z.LEQUAL),g.render()},la=function(){var e=t.renderer;e.autoClearDepth=!0,e.autoUpdateView=!1,v.render()},ha=function(e){e.projectionMatrixInverse.getInverse(e.projectionMatrix);for(var t=0,a=z.children.length;a>t;t++){var r=z.children[t];r.update(e)}for(var t=0,a=H.children.length;a>t;t++){var r=H.children[t];r.update(e)}},da=function(e,o){var n=t.renderer;if(n.autoUpdateView=!0,t.shadowMapEnabled&&t.shadowMapAutoUpdate&&$t(e,o),t.transparentShadows&&t.shadowMapAutoUpdate&&aa(e,o),t.ssaoEnabled){var s=o.far+o.near,l=o.far-o.near,h=2*o.near;R.uniforms.cameraCoef.value.set(s,l,h),I.uniforms.cameraCoef.value.set(s,l,h),B.uniforms.cameraCoef.value.set(s,l,h),R.uniforms.radius.value=i*t.ssaoRadius*15,I.uniforms.h.value=4*t.ssaoRadius/a,B.uniforms.v.value=2*t.ssaoRadius/r,X.render(),D.render()}n.autoClearDepth=!1,n.autoUpdateScene=!0,n.autoUpdateObjects=!0,ha(o),Z.depthFunc(Z.GEQUAL),S.render()},ca=function(){l&&t.dofEnabled?(F.enabled=!0,U.enabled=!0,t.dofFancy?(U.renderToScreen=!1,E.renderToScreen=!1,F.renderToScreen=!1,N.renderToScreen=!0):(E.renderToScreen=!1,F.renderToScreen=!1,U.renderToScreen=!0,N.renderToScreen=!1)):l&&!t.dofEnabled?(F.enabled=!0,U.enabled=!1,U.renderToScreen=!1,E.renderToScreen=!1,F.renderToScreen=!1,N.renderToScreen=!0):!l&&t.dofEnabled?(F.enabled=!1,U.enabled=!0,N.renderToScreen=!1,t.dofFancy?(U.renderToScreen=!1,E.renderToScreen=!0,F.renderToScreen=!1):(E.renderToScreen=!1,F.renderToScreen=!1,U.renderToScreen=!0)):(F.enabled=!1,U.enabled=!1,E.renderToScreen=!0,F.renderToScreen=!1,U.renderToScreen=!1,N.renderToScreen=!1)},ua=function(){var e=E.material,t=e.defines;switch(t.TONEMAP_SIMPLE=!1,t.TONEMAP_LINEAR=!1,t.TONEMAP_REINHARD=!1,t.TONEMAP_FILMIC=!1,t.TONEMAP_FILMIC_2015=!1,t.TONEMAP_UNCHARTED=!1,t.TONEMAP_REINHARD_LUMA=!1,t.TONEMAP_REINHARD_WHITE=!1,t.TONEMAP_PHOTOGRAPHIC=!1,s){case XG.SimpleOperator:t.TONEMAP_SIMPLE=!0;break;case XG.LinearOperator:t.TONEMAP_LINEAR=!0;break;case XG.ReinhardOperator:t.TONEMAP_REINHARD=!0;break;case XG.FilmicOperator:t.TONEMAP_FILMIC=!0;break;case XG.Filmic2015Operator:t.TONEMAP_FILMIC_2015=!0;break;case XG.UnchartedOperator:t.TONEMAP_UNCHARTED=!0;break;case XG.LumaReinhardOperator:t.TONEMAP_REINHARD_LUMA=!0;break;case XG.WhitePreservingReinhardOperator:t.TONEMAP_REINHARD_WHITE=!0;break;case XG.PhotographicOperator:t.TONEMAP_PHOTOGRAPHIC=!0}t.TONEMAPPING=!0,e.needsUpdate=!0,V.material.needsUpdate=!0},fa=function(){var e=E.material,t=e.defines;t.DITHERING_ENABLED=h,e.needsUpdate=!0},pa=function(e){var t={isES3:u,hasFloatsNearest:e.supportsFloatTextures(),hasFloatsLinear:e.supportsFloatTexturesLinear(),hasHalfFloatsNearest:e.supportsHalfFloatTextures(),hasHalfFloatsLinear:e.supportsHalfFloatTexturesLinear(),hasRGBFloatRenderTarget:e.supportsRGBFloatRenderTarget(),hasRGBHalfFloatRenderTarget:e.supportsRGBHalfFloatRenderTarget(),hasRGBUbyteRenderTarget:e.supportsRGBUnsignedByteRenderTarget()};return t},ma=function(){if("webgl2"===c)var e={minFilter:XG.NearestFilter,magFilter:XG.LinearFilter,stencilBuffer:!1,format:XG.RGBAFormat,internalFormat:XG.RGBA32F,type:XG.FloatType},i={minFilter:XG.NearestFilter,magFilter:XG.NearestFilter,stencilBuffer:!1,format:XG.RGBAFormat,internalFormat:XG.RGBA32F,type:XG.FloatType},l={minFilter:XG.NearestFilter,magFilter:XG.LinearFilter,stencilBuffer:!1,format:XG.RGBAFormat,internalFormat:XG.RGBA16F,type:XG.HalfFloatType2},u={minFilter:XG.NearestFilter,magFilter:XG.NearestFilter,stencilBuffer:!1,format:XG.RGBAFormat,internalFormat:XG.RGBA16F,type:XG.HalfFloatType2},f={minFilter:XG.LinearFilter,magFilter:XG.LinearFilter,stencilBuffer:!1,format:XG.RGBFormat,internalFormat:XG.RGBFormat,type:XG.UnsignedByteType};
  else var e={minFilter:XG.NearestFilter,magFilter:XG.LinearFilter,stencilBuffer:!1,format:XG.RGBAFormat,internalFormat:XG.RGBAFormat,type:XG.FloatType},i={minFilter:XG.NearestFilter,magFilter:XG.NearestFilter,stencilBuffer:!1,format:XG.RGBAFormat,internalFormat:XG.RGBAFormat,type:XG.FloatType},l={minFilter:XG.NearestFilter,magFilter:XG.LinearFilter,stencilBuffer:!1,format:XG.RGBAFormat,internalFormat:XG.RGBAFormat,type:XG.HalfFloatType1},u={minFilter:XG.NearestFilter,magFilter:XG.NearestFilter,stencilBuffer:!1,format:XG.RGBAFormat,internalFormat:XG.RGBAFormat,type:XG.HalfFloatType1},f={minFilter:XG.LinearFilter,magFilter:XG.LinearFilter,stencilBuffer:!1,format:XG.RGBFormat,internalFormat:XG.RGBFormat,type:XG.UnsignedByteType};var p,H=pa(t.renderer);if(H.hasHalfFloatsLinear?p=l:H.hasHalfFloatsNearest?p=u:H.hasFloatsLinear?p=e:H.hasFloatsNearest?p=i:console.error("XG.DeferredRenderer: missing float or half float render targets support"),H.hasRGBUbyteRenderTarget||(f.format=XG.RGBAFormat,f.internalFormat=XG.RGBAFormat),d){var z=t.useDepthTexture?4:5,W={minFilter:XG.NearestFilter,magFilter:XG.NearestFilter,format:XG.RGBAFormat,internalFormat:XG.RGBAFormat,type:XG.UnsignedByteType,stencilBuffer:!1},K=new XG.RenderTargetArray(o,n,z,t.useDepthTexture,W);K.generateMipmaps=!1,w=new XG.RenderPass,w.clear=!0,w.clearColor=et,w.clearAlpha=1,m=new XG.EffectComposer(t.renderer,K),m.addPass(w);var Z=m.renderTarget2,Y=Z.colorTexture[3],Q=t.useDepthTexture?Z.depthTexture:Z.colorTexture[4]}else{var J=new XG.RenderTarget(o,n,i);J.generateMipmaps=!1;var tt=new XG.RenderTarget(o,n,i);tt.generateMipmaps=!1,C=new XG.RenderPass,C.clear=!0,C.clearColor=et,C.clearAlpha=1,g=new XG.EffectComposer(t.renderer,tt),g.addPass(C),A=new XG.RenderPass,A.clear=!0,v=new XG.EffectComposer(t.renderer,J),v.addPass(A),v.renderTarget2.shareDepthFrom=g.renderTarget2}var at=Math.max(1,Math.floor(o*t.ssaoScale)),rt=Math.max(1,Math.floor(n*t.ssaoScale)),it=new XG.RenderTarget(at,rt,f),ot=new XG.RenderTarget(o,n,f);it.generateMipmaps=!1,ot.generateMipmaps=!1,it.depthBuffer=!1,it.stencilBuffer=!1,ot.depthBuffer=!1,ot.stencilBuffer=!1,R=new XG.ShaderPass(XG.SSAOShader),R.clear=!1,R.uniforms.size.value.set(at,rt),R.uniforms.aoClamp.value=1.5,I=new XG.ShaderPass(XG.SSAOBilateralHorizontalBlurShader),B=new XG.ShaderPass(XG.SSAOBilateralVerticalBlurShader),I.uniforms.h.value=4*t.ssaoRadius/a,B.uniforms.v.value=2*t.ssaoRadius/r,R.material.blending=XG.NoBlending,R.material.depthTest=!1,R.material.depthWrite=!1,I.material.blending=XG.NoBlending,I.material.depthTest=!1,I.material.depthWrite=!1,B.material.blending=XG.NoBlending,B.material.depthTest=!1,B.material.depthWrite=!1,d?(R.uniforms.tDepth.value=Q,I.uniforms.tDepth.value=Q,B.uniforms.tDepth.value=Q,I.uniforms.tNormal.value=Y,B.uniforms.tNormal.value=Y):(R.uniforms.tDepth.value=g.renderTarget2,I.uniforms.tDepth.value=g.renderTarget2,B.uniforms.tDepth.value=g.renderTarget2);var st=bt(),lt=t.ssaoSamples;st.PREBAKED_SAMPLES=!0,st.NUM_PREBAKED_SAMPLES=lt,R.uniforms.samplePoints.value=XG.Math.generatePoissonDiscSamples(lt),R.material.defines=st,I.material.defines=st,B.material.defines=st,X=new XG.EffectComposer(t.renderer,it),X.addPass(R),I.textureID="dummy",I.uniforms.tDiffuse.value=X.renderTarget1,D=new XG.EffectComposer(t.renderer,ot),D.addPass(I),D.addPass(B);var ht=new XG.RenderTarget(o,n,p),ct=new XG.RenderTarget(o,n,f);ht.generateMipmaps=!1,ct.generateMipmaps=!1,ct.depthBuffer=!1,ct.stencilBuffer=!1,T=new XG.RenderPass,T.clear=!0,b=new XG.RenderPass,b.clear=!1,j=new XG.RenderTarget(o,n,f),q=new XG.SavePass(j),q.material.depthTest=!1,q.enabled=!1,S=new XG.EffectComposer(t.renderer,ht),S.addPass(T),S.addPass(b),S.addPass(q),S.renderTarget2.shareDepthFrom=d?m.renderTarget2:g.renderTarget2,P=new XG.RenderPass,P.clear=!1,G=new XG.EffectComposer(t.renderer,ht),G.addPass(P),G.renderTarget1=S.renderTarget1,G.renderTarget2=S.renderTarget2,G.renderTarget2.shareDepthFrom=d?m.renderTarget2:g.renderTarget2,L=new XG.RenderPass,L.clear=!0,L.clearColor=$,L.clearAlpha=1;var ut=Math.max(1,Math.floor(o*t.particlesOffscreenScale)),ft=Math.max(1,Math.floor(n*t.particlesOffscreenScale));if(t.particlesOit)if(d){var pt=new XG.RenderTargetArray(ut,ft,2,!1,p);pt.generateMipmaps=!1,x=new XG.EffectComposer(t.renderer,pt),x.addPass(L)}else{var mt=new XG.RenderTarget(ut,ft,p),vt=new XG.RenderTarget(ut,ft,p);mt.generateMipmaps=!1,vt.generateMipmaps=!1,x=new XG.EffectComposer(t.renderer,mt),x.addPass(L),M=new XG.EffectComposer(t.renderer,vt),M.addPass(L)}else{var gt=new XG.RenderTarget(ut,ft,p);gt.generateMipmaps=!1,x=new XG.EffectComposer(t.renderer,gt),x.addPass(L)}var St=Math.max(1,Math.floor(o*t.bloomScale)),Gt=Math.max(1,Math.floor(n*t.bloomScale)),xt=new XG.RenderTarget(St,Gt,f);xt.generateMipmaps=!1,xt.depthBuffer=!1,xt.stencilBuffer=!1,O=new XG.ShaderPass(XG.BloomHorizontalBlurShader),k=new XG.ShaderPass(XG.BloomVerticalBlurShader),V=new XG.ShaderPass(XG.BloomFilterShader),V.uniforms.tSource.value=S.renderTarget2,V.uniforms.threshold.value=t.bloomThreshold,V.uniforms.brightness.value=t.brightness,V.uniforms.whitePoint.value=t.whitePoint,O.uniforms.h.value=1/St,k.uniforms.v.value=1/Gt,O.material.blending=XG.NoBlending,O.material.depthTest=!1,O.material.depthWrite=!1,k.material.blending=XG.NoBlending,k.material.depthTest=!1,k.material.depthWrite=!1,V.material.blending=XG.NoBlending,V.material.depthTest=!1,V.material.depthWrite=!1,_=new XG.EffectComposer(t.renderer,xt),_.addPass(V),_.addPass(O),_.addPass(k),E=new XG.ShaderPass(nt),E.uniforms.brightness.value=t.brightness,E.uniforms.whitePoint.value=t.whitePoint,E.uniforms.samplerLight.value=S.renderTarget2,E.uniforms.samplerBloom.value=_.renderTarget1,E.uniforms.bloomStrength.value=t.bloomStrength,t.particlesOit?d?(E.uniforms.samplerParticles.value=x.renderTarget2.colorTexture[0],E.uniforms.samplerParticlesRevealage.value=x.renderTarget2.colorTexture[1]):(E.uniforms.samplerParticles.value=x.renderTarget2,E.uniforms.samplerParticlesRevealage.value=M.renderTarget2):E.uniforms.samplerParticles.value=x.renderTarget2;var Mt=bt();switch(t.fogEnabled&&(Mt.FOG_ENABLED=!0,E.uniforms.samplerDepth.value=d?Q:g.renderTarget2,dt.push({material:E.material,depth:"samplerDepth"})),h&&(Mt.DITHERING_ENABLED=!0),E.material.blending=XG.NoBlending,E.material.depthTest=!1,E.material.depthWrite=!1,E.clear=!0,s){case XG.SimpleOperator:Mt.TONEMAP_SIMPLE=!0;break;case XG.LinearOperator:Mt.TONEMAP_LINEAR=!0;break;case XG.ReinhardOperator:Mt.TONEMAP_REINHARD=!0;break;case XG.FilmicOperator:Mt.TONEMAP_FILMIC=!0;break;case XG.Filmic2015Operator:Mt.TONEMAP_FILMIC_2015=!0;break;case XG.UnchartedOperator:Mt.TONEMAP_UNCHARTED=!0;break;case XG.LumaReinhardOperator:Mt.TONEMAP_REINHARD_LUMA=!0;break;case XG.WhitePreservingReinhardOperator:Mt.TONEMAP_REINHARD_WHITE=!0;break;case XG.PhotographicOperator:Mt.TONEMAP_PHOTOGRAPHIC=!0}if(Mt.TONEMAPPING=!0,Mt.BLOOM_ENABLED=t.bloomEnabled,Mt.OFFSCREEN_PARTICLES=t.particlesOffscreen,Mt.PARTICLE_OIT=t.particlesOit,Mt.USE_MRT=d,Mt.FANCY_DOF=t.dofFancy&&t.dofEnabled,E.material.defines=Mt,V.material.defines=Mt,F=new XG.ShaderPass(XG.FXAAShader),F.material.blending=XG.NoBlending,F.material.depthTest=!1,F.material.depthWrite=!1,F.uniforms.resolution.value.set(1/o,1/n),t.dofFancy){var yt=.75;U=new XG.FancyDepthOfFieldPass(o,n,yt,H)}else U=new XG.DepthOfFieldPass(1024,512,H);U.defines=bt(),t.dofDebug&&(U.defines.DOF_DEBUG=1),t.dofPhysical&&(U.defines.DOF_PHYSICAL=1),U.depthInput=d?Q:g.renderTarget2,U.colorInput=S.renderTarget2,U.autoFocus=t.dofAutofocus,U.autoFocusPoint=t.dofAutofocusPoint,U.focusDistance=t.dofFocusDistance,U.focusRampStart=t.dofFocusWidth,U.focusRampEnd=t.dofFocusWidth+t.dofFocusRampWidth,U.maxBlur=t.dofMaxBlur,t.dofFancy&&t.dofPhysical&&(U.lensFstop=t.dofLensFstop,U.lensFocalLength=t.dofLensFocalLength,U.lensBlurScale=t.dofLensBlurScale,t.fogEnabled&&(U.defines.FOG_ENABLED=!0)),N=new XG.ShaderPass(XG.CopyShader),N.renderToScreen=!0,t.dofFancy?(E.uniforms.samplerBlur.value=U.renderTargetBlurPass2,E.uniforms.samplerBlurAmount.value=U.renderTargetBlurAmount,y=new XG.EffectComposer(t.renderer,ct),y.addPass(U),y.addPass(E),y.addPass(F),y.addPass(N)):(y=new XG.EffectComposer(t.renderer,ct),y.addPass(E),y.addPass(F),y.addPass(U),y.addPass(N)),ca()};this.getRenderingBackend=function(){return c},this.setAntialias=function(e){l=e,ca()},this.getAntialias=function(){return l},this.setDOF=function(e){this.dofEnabled=e,ca();var a=E.material,r=a.defines;r.FANCY_DOF=t.dofFancy&&t.dofEnabled,a.needsUpdate=!0},this.setTonemapping=function(e){s=e,K&&ua()},this.setDither=function(e){h=e,K&&fa()},this.setSSAOSamples=function(e){this.ssaoSamples=e;var t=bt();t.PREBAKED_SAMPLES=!0,t.NUM_PREBAKED_SAMPLES=e,R.uniforms.samplePoints.value=XG.Math.generatePoissonDiscSamples(e),R.material.defines=t,R.material.needsUpdate=!0},this.addEffect=function(e,a){if(e.material&&e.uniforms&&(e.properties={},a&&(a.normalDepthUniform||a.colorUniform||a.depthUniform))){var r={material:e.material,normalDepth:a.normalDepthUniform,color:a.colorUniform,depth:a.depthUniform};dt.push(r),e.properties.normalDepthUniform=a.normalDepthUniform,e.properties.colorUniform=a.colorUniform,e.properties.depthUniform=a.depthUniform,(a.normalDepthUniform||a.depthUniform)&&(e.material.defines=bt())}if(y){var i=t.dofFancy?-2:-3;y.insertPass(e,i)}else st.push(e)},this.setScale=function(e){if(i=e,this.renderer.setScale(i),o=Math.max(1,Math.floor(i*a)),n=Math.max(1,Math.floor(i*r)),o=Math.max(1,Math.floor(o*p)),n=Math.max(1,Math.floor(n*p)),K){var s=Math.max(1,Math.floor(o*t.ssaoScale)),l=Math.max(1,Math.floor(n*t.ssaoScale)),h=Math.max(1,Math.floor(o*t.bloomScale)),c=Math.max(1,Math.floor(n*t.bloomScale)),u=Math.max(1,Math.floor(o*t.particlesOffscreenScale)),f=Math.max(1,Math.floor(n*t.particlesOffscreenScale));S.setSize(o,n),y.setSize(o,n),x.setSize(u,f),M&&M.setSize(u,f),X.setSize(s,l),D.setSize(o,n),_.setSize(h,c),d?m.setSize(o,n):(g.setSize(o,n),v.setSize(o,n));for(var G=0,w=dt.length;w>G;G++){var A=dt[G],C=A.material,T=C.uniforms;T.viewSize&&T.viewSize.value.set(o,n),T.screenWidth&&(T.screenWidth.value=o)}for(var G=0,w=ct.length;w>G;G++){var b=ct[G];b.resize(o,n)}F.uniforms.resolution.value.set(1/o,1/n),U.resize(o,n),R.uniforms.size.value.set(s,l),O.uniforms.h.value=1/h,k.uniforms.v.value=1/c}},this.setSize=function(e,t){a=e,r=t,this.renderer.setSize(a,r),this.setScale(i)},this.getCombinedTarget=function(){return m.renderTarget2},this.getColorTarget=function(){return v.renderTarget2},this.getNormalDepthTarget=function(){return g.renderTarget2},this.getSSAOTarget=function(){return D.renderTarget2},this.getUseMultipleRenderTargets=function(){return d},this.prepareForwardPass=function(e){e.properties.deferredInitialized&&Ft(e,"forwardMaterials")},this.renderCube=function(e,t,a){e.properties.deferredInitialized&&Pt(e,"forwardMaterials"),this.renderer.autoClear=!0,this.renderer.renderCube(e,t,a),this.renderer.autoClear=!1},this.render=function(e,a){if(!K){ma();for(var r=t.dofFancy?-2:-3,i=0,o=st.length;o>i;i++){var n=st[i],s=n.properties;if(s){var l,h,c,u=s.normalDepthUniform,f=s.colorUniform,p=s.depthUniform;if(d){var S=m.renderTarget2;c=t.useDepthTexture?S.depthTexture:S.colorTexture[4],h=S.colorTexture[0]}else l=g.renderTarget2,h=v.renderTarget2,c=g.renderTarget2;u&&(n.uniforms[u].value=l),f&&(n.uniforms[f].value=h),p&&(n.uniforms[p].value=c)}y.insertPass(n,r)}K=!0}var G=t.renderer,x=e.properties;if(x.deferredInitialized||(x.lightSceneGeometry=new XG.Scene,x.lightSceneFullscreen=new XG.Scene,x.shadowCasters=[],x.deferredInitialized=!0),z=x.lightSceneGeometry,H=x.lightSceneFullscreen,W=e,d?(w.camera=a,w.scene=e):(A.camera=a,A.scene=e,C.camera=a,C.scene=e),b.camera=a,b.scene=z,T.camera=XG.EffectComposer.camera,T.scene=H,P.camera=a,P.scene=e,L.camera=a,L.scene=e,G.autoUpdateObjects=!1,G.initWebGLObjects(e),G.initWebGLObjects(XG.EffectComposer.scene),At(e),G.autoUpdateScene=!1,e.updateMatrixWorld(),T.clear=!0,d?(w.clear=!0,Pt(e,"combinedMaterials"),na(e,a),da(e,a),w.clear=!1):(A.clear=!0,C.clear=!0,Pt(e,"normalDepthMaterials"),sa(e,a),Pt(e,"colorMaterials"),la(e,a),da(e,a),A.clear=!1,C.clear=!1),T.clear=!1,ia(e,a),G.autoUpdateScene=!1,G.autoUpdateObjects=!1,Et(e,"forwardMaterials"),ra(e,a),Lt(e,"forwardMaterials"),ra(e,a),t.particlesOffscreen&&oa(e,a),t.bloomEnabled&&(V.uniforms.threshold.value=t.bloomThreshold,V.uniforms.brightness.value=t.brightness,V.uniforms.whitePoint.value=t.whitePoint,_.render()),G.autoUpdateObjects=!0,G.autoUpdateScene=!0,G.autoClearDepth=!0,Z.depthFunc(Z.LEQUAL),t.bloomEnabled){var M=E.uniforms;M.bloomStrength.value=t.bloomStrength,M.brightness.value=t.brightness,M.whitePoint.value=t.whitePoint}if(t.dofEnabled&&(U.cameraNear=a.near,U.cameraFar=a.far,U.autoFocus=t.dofAutofocus,U.autoFocusPoint=t.dofAutofocusPoint,U.focusDistance=t.dofFocusDistance,U.focusRampStart=t.dofFocusWidth,U.focusRampEnd=t.dofFocusWidth+t.dofFocusRampWidth,U.maxBlur=t.dofMaxBlur,t.dofFancy&&t.dofPhysical&&(U.lensFstop=t.dofLensFstop,U.lensFocalLength=t.dofLensFocalLength,U.lensBlurScale=t.dofLensBlurScale,U.lensMaxCoc=t.dofLensMaxCoc,U.lensApertureSides=t.dofLensApertureSides)),t.fogEnabled){var X=E.uniforms;if(X.fogColor.value.copy(t.fogColor),X.fogStrength.value=t.fogStrength,X.fogStart.value=t.fogStart,X.cameraNearFar.value.set(a.near,a.far),t.dofFancy&&t.dofPhysical){var D=U.blurAmountUniforms;D.fogColor.value.copy(t.fogColor),D.fogStrength.value=t.fogStrength,D.fogStart.value=t.fogStart}}E.uniforms.brightness.value=t.brightness,E.uniforms.whitePoint.value=t.whitePoint,y.render(.1),St+=1}},XG.ShadowMapPlugin=function(){function e(e,t){var a=new XG.DirectionalLight;a.isVirtual=!0,a.onlyShadow=!0,a.castShadow=!0,a.shadowCameraNear=e.shadowCameraNear,a.shadowCameraFar=e.shadowCameraFar,a.shadowCameraLeft=e.shadowCameraLeft,a.shadowCameraRight=e.shadowCameraRight,a.shadowCameraBottom=e.shadowCameraBottom,a.shadowCameraTop=e.shadowCameraTop,a.shadowCameraVisible=e.shadowCameraVisible,a.shadowDarkness=e.shadowDarkness,a.shadowBias=e.shadowCascadeBias[t],a.shadowMapWidth=e.shadowCascadeWidth[t],a.shadowMapHeight=e.shadowCascadeHeight[t],a.properties.pointsWorld=[],a.properties.pointsFrustum=[];for(var r=a.properties.pointsWorld,i=a.properties.pointsFrustum,o=0;8>o;o++)r[o]=new XG.Vector3,i[o]=new XG.Vector3;var n=e.shadowCascadeNearZ[t],s=e.shadowCascadeFarZ[t];return i[0].set(-1,-1,n),i[1].set(1,-1,n),i[2].set(-1,1,n),i[3].set(1,1,n),i[4].set(-1,-1,s),i[5].set(1,-1,s),i[6].set(-1,1,s),i[7].set(1,1,s),a}function t(e,t){var a=e.shadowCascadeArray[t];a.position.copy(e.position),a.target.position.copy(e.target.position),a.lookAt(a.target.position),a.shadowCameraVisible=e.shadowCameraVisible,a.shadowDarkness=e.shadowDarkness,a.shadowBias=e.shadowCascadeBias[t];var r=e.shadowCascadeNearZ[t],i=e.shadowCascadeFarZ[t],o=a.properties.pointsFrustum;o[0].setZ(r),o[1].setZ(r),o[2].setZ(r),o[3].setZ(r),o[4].setZ(i),o[5].setZ(i),o[6].setZ(i),o[7].setZ(i)}function a(e,t){var a=t.properties,r=a.shadowCamera,i=a.pointsFrustum,o=a.pointsWorld;m.set(1/0,1/0,1/0),v.set(-1/0,-1/0,-1/0);for(var n=m.data,s=v.data,l=XG.ShadowMapPlugin.__projector,h=0;8>h;h++){var d=o[h],c=d.data;d.copy(i[h]),l.unprojectVector(d,e),r.matrixWorldInverse.multiplyVector3(d),c[0]<n[0]&&(n[0]=c[0]),c[0]>s[0]&&(s[0]=c[0]),c[1]<n[1]&&(n[1]=c[1]),c[1]>s[1]&&(s[1]=c[1]),c[2]<n[2]&&(n[2]=c[2]),c[2]>s[2]&&(s[2]=c[2])}r.left=n[0],r.right=s[0],r.top=s[1],r.bottom=n[1],r.updateProjectionMatrix()}var r,i,o,n,s,l,h,d,c,u,f=new XG.Frustum,p=new XG.Matrix4,m=new XG.Vector3,v=new XG.Vector3,g=[new XG.Vector3(0,-1,0),new XG.Vector3(0,-1,0),new XG.Vector3(0,0,1),new XG.Vector3(0,0,-1),new XG.Vector3(0,-1,0),new XG.Vector3(0,-1,0)],S=[new XG.Vector3(1,0,0),new XG.Vector3(-1,0,0),new XG.Vector3(0,1,0),new XG.Vector3(0,-1,0),new XG.Vector3(0,0,1),new XG.Vector3(0,0,-1)],G={},x={};this.init=function(e){r=e.context,i=e;var t=XG.ShaderLib.depthRGBA;u=XG.UniformsUtils.clone(t.uniforms),u.slopeScale.value=i.shadowMapSlopeScale,u.slopeBias.value=i.shadowMapSlopeBias,u.slopeMax.value=i.shadowMapSlopeMax;var a=i.shadowMapSlopeDepthBias&&i.supportsStandardDerivatives(),f={SLOPE_DEPTH_BIAS:a},p={SLOPE_DEPTH_BIAS:a,SPRITE:!0,SDF:!0},m=i.supportsVertexTextures(),v={SLOPE_DEPTH_BIAS:a,USE_DISPLACEMENTMAP:m,DISPLACE_BY_NORMAL:!0},g={SLOPE_DEPTH_BIAS:a,USE_DISPLACEMENTMAP:m,DISPLACE_BY_POSITION:!0},S={OES_standard_derivatives:a},G={OES_standard_derivatives:!0},x=t.fragmentShader,M=t.vertexShader;o=new XG.ShaderMaterial({fragmentShader:x,vertexShader:M,uniforms:u,defines:f,extensions:S}),n=new XG.ShaderMaterial({fragmentShader:x,vertexShader:M,uniforms:u,defines:f,extensions:S,morphTargets:!0}),s=new XG.ShaderMaterial({fragmentShader:x,vertexShader:M,uniforms:u,defines:f,extensions:S,skinning:!0}),l=new XG.ShaderMaterial({fragmentShader:x,vertexShader:M,uniforms:u,defines:f,extensions:S,morphTargets:!0,skinning:!0}),h=new XG.ShaderMaterial({fragmentShader:x,vertexShader:M,uniforms:u,defines:p,extensions:G}),d=new XG.ShaderMaterial({fragmentShader:x,vertexShader:M,uniforms:u,defines:v,extensions:S}),c=new XG.ShaderMaterial({fragmentShader:x,vertexShader:M,uniforms:u,defines:g,extensions:S}),o._shadowPass=!0,n._shadowPass=!0,s._shadowPass=!0,l._shadowPass=!0,h._shadowPass=!0,d._shadowPass=!0,c._shadowPass=!0},this.render=function(e,t){i.shadowMapEnabled&&i.shadowMapAutoUpdate&&this.update(e,t)},this.update=function(m,v){var M,y,X,D,_,w,A,C,T,b,P,L,E,F,R,U=[],N=0,I=null,B=null,O=i.supportsDepthTextures()&&i.shadowMapUseDepthTextures;r.clearColor(1,1,1,1),r.disable(r.BLEND);var k;for(k=i.shadowMapCullFace===XG.CullFaceFront?XG.BackSide:i.shadowMapCullFace===XG.CullFaceBack?XG.FrontSide:XG.DoubleSide,i.setDepthTest(!0),O&&r.colorMask(!1,!1,!1,!1),M=0,y=m.__lights.length;y>M;M++)if(E=m.__lights[M],E.castShadow)if((E instanceof XG.DirectionalLight||E instanceof XG.DayLight||E instanceof XG.DayLightCube)&&E.shadowCascade)for(_=0;_<E.shadowCascadeCount;_++){var V;if(E.shadowCascadeArray[_])V=E.shadowCascadeArray[_];else{V=e(E,_),V.originalCamera=v;var H=new XG.Gyroscope;H.position=E.shadowCascadeOffset,H.add(V),H.add(V.target),v.add(H),E.shadowCascadeArray[_]=V,console.log("Created virtualLight",V)}t(E,_),U[N]=V,N++}else U[N]=E,N++;for(i.shadowMapSlopeDepthBias&&(O?i.setPolygonOffset(!0,1.5,10):(u.slopeScale.value=i.shadowMapSlopeScale,u.slopeBias.value=i.shadowMapSlopeBias,u.slopeMax.value=i.shadowMapSlopeMax)),M=0,y=U.length;y>M;M++){if(E=U[M],F=E.properties,!F.shadowMap){var z=!i.supportsDepthOnlyRenderTarget(),W=i.supportsLuminanceFloatRenderTarget()?XG.LuminanceFormat:i.supportsRGBFloatRenderTarget()?XG.RGBFormat:XG.RGBAFormat,j="webgl2"===i.getRenderingBackend(),q={minFilter:XG.NearestFilter,magFilter:XG.NearestFilter,stencilBuffer:!1,format:XG.RGBAFormat,type:XG.UnsignedByteType};if(j)var K={minFilter:XG.LinearFilter,magFilter:XG.LinearFilter,useColorTexture:z,stencilBuffer:!1,format:W,useDepthTexture:!0,depthTextureType:i.shadowMapDepthTextureType};else var K={minFilter:XG.NearestFilter,magFilter:XG.NearestFilter,useColorTexture:z,stencilBuffer:!1,format:W,useDepthTexture:!0,depthTextureType:i.shadowMapDepthTextureType};var Z=O?K:q;F.shadowMap=new XG.RenderTarget(E.shadowMapWidth,E.shadowMapHeight,Z),F.shadowMap.generateMipmaps=!1,F.shadowMapPars=new XG.Vector4(E.shadowMapWidth,E.shadowMapHeight,E.shadowDarkness,E.shadowBias),F.shadowMatrixForward=new XG.Matrix4}if(!F.shadowCamera){var Y=E.shadowMapWidth/E.shadowMapHeight;if(E instanceof XG.SpotLight)C=new XG.PerspectiveCamera(E.shadowCameraFov,Y,E.shadowCameraNear,E.shadowCameraFar);else if(E instanceof XG.DirectionalLight||E instanceof XG.DayLight||E instanceof XG.DayLightCube)C=new XG.OrthographicCamera(E.shadowCameraLeft,E.shadowCameraRight,E.shadowCameraTop,E.shadowCameraBottom,E.shadowCameraNear,E.shadowCameraFar);else if(E instanceof XG.AreaLight)C=E.shadowCameraOrtho?new XG.OrthographicCamera(E.shadowCameraLeft,E.shadowCameraRight,E.shadowCameraTop,E.shadowCameraBottom,E.shadowCameraNear,E.shadowCameraFar):new XG.PerspectiveCamera(E.shadowCameraFov,Y,E.shadowCameraNear,E.shadowCameraFar);else{if(!(E instanceof XG.SphereLight)){console.error("XG:ShadowMapPlugin: Unsupported light type for shadow");continue}C=[];for(var Q=0;6>Q;Q++){var J=new XG.PerspectiveCamera(90,Y,E.shadowCameraNear,E.shadowCameraFar);J.up.copy(g[Q]),J.lookAt(S[Q]),C[Q]=J}}F.shadowCamera=C,E instanceof XG.SphereLight||(m.add(C),i.autoUpdateScene&&m.updateMatrixWorld())}if(w=F.shadowMap,C=F.shadowCamera,A=F.shadowMatrixForward,F.shadowCamera instanceof Array&&void 0!==E.forwardShadowSide){var $=E.forwardShadowSide;C=F.shadowCamera[$],C.position.copy(E.matrixWorld.getPosition())}else C.position.copy(E.matrixWorld.getPosition()),C.lookAt(E.target.matrixWorld.getPosition());for(C.updateMatrixWorld(),C.matrixWorldInverse.getInverse(C.matrixWorld),E.isVirtual&&V.originalCamera==v&&a(v,E),E.cameraHelper&&(E.cameraHelper.visible=E.shadowCameraVisible),E.shadowCameraVisible&&E.cameraHelper.update(),A.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),A.multiplySelf(C.projectionMatrix),A.multiplySelf(C.matrixWorldInverse),p.multiply(C.projectionMatrix,C.matrixWorldInverse),f.setFromMatrix(p),i.setRenderTarget(w),i.clear(),R=m.__webglObjects,X=0,D=R.length;D>X;X++)P=R[X],L=P.object,T=P.geometry,P.render=!1,L.visible&&L.castShadow&&((L instanceof XG.Mesh||L instanceof XG.Particles)&&L.frustumCulled&&!f.contains(L,T)||(L._modelViewMatrix.multiply(C.matrixWorldInverse,L.matrixWorld),P.render=!0));var et,tt,at,rt,it,ot;for(X=0,D=R.length;D>X;X++)if(P=R[X],P.render&&(L=P.object,T=P.geometry,rt=T instanceof XG.SpriteGeometry,et=rt||P.transparent&&P.transparent.forceShadow?P.transparent:P.opaque,et&&et.visible)){if(tt=T.morphTargets.length>0&&et.morphTargets,at=L instanceof XG.SkinnedMesh&&et.skinning,it=et.displacementMap,ot=et.instances,L.customDepthMaterial)b=L.customDepthMaterial;else if(it){b=et.displacementDirection===XG.DisplaceByNormal?d:c;var nt=b.uniforms,st=et.uniforms;nt.displacementMap.value=et.displacementMap,nt.displacementScaleBias.value.set(et.displacementScale,et.displacementBias),nt.displacementNormalScale.value=et.displacementNormalScale,nt.offsetRepeat.value.copy(st.offsetRepeat.value)}else if(at)void 0===G[et.id]&&(b=tt?l:s,G[et.id]=b.clone(),G[et.id]._shadowPass=!0),b=G[et.id];else if(tt)b=n;else if(rt){b=h;var nt=b.uniforms,st=et.uniforms;nt.map.value=st.map.value,nt.alphaTest.value=st.alphaTest.value,nt.epsilon.value=st.epsilon.value}else b=o;ot&&(void 0===x[et.id]&&(x[et.id]=b.clone(),x[et.id]._shadowPass=!0,x[et.id].instances=!0),b=x[et.id],T.instanceCulled&&(i.cullInstances(L,T,f),i.setBuffers(T))),b.side=rt?XG.DoubleSide:k,i.setMaterialFaces(b),i.setProgram(C,m.__lights,I,B,b,L,T),i.renderGeometry(b,T,L)}for(R=m.__webglObjectsImmediate,X=0,D=R.length;D>X;X++)P=R[X],L=P.object,L.visible&&L.castShadow&&(f.contains(L,L)||!L.frustumCulled)&&(L._modelViewMatrix.multiply(C.matrixWorldInverse,L.matrixWorld),i.renderImmediateObject(C,m.__lights,I,o,L))}var lt=i.getClearColor(),ht=i.getClearAlpha();r.clearColor(lt.r,lt.g,lt.b,ht),r.enable(r.BLEND),O&&r.colorMask(!0,!0,!0,!0)}},XG.ShadowMapPlugin.__projector=new XG.Projector,XG.EffectComposer=function(e,t){if(e?e instanceof XG.DeferredRenderer&&console.warn("XG.EffectComposer: passed deferred renderer parameter, probably not what you intended"):console.warn("XG.EffectComposer: undefined renderer"),this.renderer=e,void 0===t){var a=window.innerWidth||1,r=window.innerHeight||1,i={minFilter:XG.LinearFilter,magFilter:XG.LinearFilter,format:XG.RGBAFormat,internalFormat:XG.RGBAFormat,type:XG.UnsignedByteType,stencilBuffer:!1};t=new XG.RenderTarget(a,r,i)}this.renderTarget1=t,this.renderTarget2=t.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.passes=[],this.copyPass=new XG.ShaderPass(XG.CopyShader)},XG.EffectComposer.prototype={swapBuffers:function(){var e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e},addPass:function(e){this.passes.push(e)},insertPass:function(e,t){this.passes.splice(t,0,e)},render:function(e){this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2;var t,a,r=!1,i=this.passes.length;for(a=0;i>a;a++)if(t=this.passes[a],t.enabled){if(t.render(this.renderer,this.writeBuffer,this.readBuffer,e,r),t.needsSwap){if(r){var o=this.renderer.context;o.stencilFunc(o.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),o.stencilFunc(o.EQUAL,1,4294967295)}this.swapBuffers()}t instanceof XG.MaskPass?r=!0:t instanceof XG.ClearMaskPass&&(r=!1)}},setSize:function(e,t){this.renderTarget1.setSize(e,t),this.renderTarget2.setSize(e,t)}},XG.EffectComposer.camera=new XG.OrthographicCamera(-1,1,1,-1,0,1),XG.EffectComposer.quad=new XG.Mesh(new XG.TriangleGeometry([[-1,-3,0],[3,1,0],[-1,1,0]],[[0,-1],[2,1],[0,1]]),null),XG.EffectComposer.scene=new XG.Scene,XG.EffectComposer.scene.add(XG.EffectComposer.quad),XG.TexturePass=function(e,t){var a=XG.CopyShader;this.uniforms=XG.UniformsUtils.clone(a.uniforms),this.uniforms.opacity.value=void 0!==t?t:1,this.uniforms.tDiffuse.value=e,this.material=new XG.ShaderMaterial({uniforms:this.uniforms,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader}),this.enabled=!0,this.needsSwap=!1},XG.TexturePass.prototype={render:function(e,t,a){XG.EffectComposer.quad.materials[0]=this.material,e.render(XG.EffectComposer.scene,XG.EffectComposer.camera,a)}},XG.ShaderPass=function(e,t){this.textureID=void 0!==t?t:"tDiffuse",this.uniforms=XG.UniformsUtils.clone(e.uniforms),this.material=new XG.ShaderMaterial({uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader,defines:XG.UniformsUtils.cloneDefines(e.defines)}),this.renderToScreen=!1,this.enabled=!0,this.needsSwap=!0,this.clear=!1},XG.ShaderPass.prototype={render:function(e,t,a){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=a),XG.EffectComposer.quad.materials[0]=this.material,this.renderToScreen?e.render(XG.EffectComposer.scene,XG.EffectComposer.camera):e.render(XG.EffectComposer.scene,XG.EffectComposer.camera,t,this.clear)}},XG.SavePass=function(e){var t=XG.CopyShader;this.textureID="tDiffuse",this.uniforms=XG.UniformsUtils.clone(t.uniforms),this.material=new XG.ShaderMaterial({uniforms:this.uniforms,vertexShader:t.vertexShader,fragmentShader:t.fragmentShader}),this.renderTarget=e,void 0===this.renderTarget&&(this.renderTargetParameters={minFilter:XG.LinearFilter,magFilter:XG.LinearFilter,format:XG.RGBAFormat,stencilBuffer:!1},this.renderTarget=new XG.RenderTarget(window.innerWidth,window.innerHeight,this.renderTargetParameters)),this.enabled=!0,this.needsSwap=!1,this.clear=!1},XG.SavePass.prototype={render:function(e,t,a){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=a),XG.EffectComposer.quad.materials[0]=this.material,e.render(XG.EffectComposer.scene,XG.EffectComposer.camera,this.renderTarget,this.clear)}},XG.RenderPass=function(e,t,a,r){this.scene=e,this.camera=t,this.clearColor=a,this.clearAlpha=void 0!==r?r:1,this.oldClearColor=new XG.Color,this.oldClearAlpha=1,this.enabled=!0,this.clear=!0,this.needsSwap=!1},XG.RenderPass.prototype={render:function(e,t,a){this.clearColor&&(this.oldClearColor.copy(e.getClearColor()),this.oldClearAlpha=e.getClearAlpha(),e.setClearColor(this.clearColor,this.clearAlpha)),e.render(this.scene,this.camera,a,this.clear),this.clearColor&&e.setClearColor(this.oldClearColor,this.oldClearAlpha)}},XG.MaskPass=function(e,t){this.scene=e,this.camera=t,this.enabled=!0,this.clear=!0,this.needsSwap=!1,this.inverse=!1},XG.MaskPass.prototype={render:function(e,t,a){var r=e.context;r.colorMask(!1,!1,!1,!1),r.depthMask(!1);var i,o;this.inverse?(i=0,o=1):(i=1,o=0),r.enable(r.STENCIL_TEST),r.stencilOp(r.REPLACE,r.REPLACE,r.REPLACE),r.stencilFunc(r.ALWAYS,i,4294967295),r.clearStencil(o),e.render(this.scene,this.camera,a,this.clear),e.render(this.scene,this.camera,t,this.clear),r.colorMask(!0,!0,!0,!0),r.depthMask(!0),r.stencilFunc(r.EQUAL,1,4294967295),r.stencilOp(r.KEEP,r.KEEP,r.KEEP)}},XG.ClearMaskPass=function(){this.enabled=!0},XG.ClearMaskPass.prototype={render:function(e){var t=e.context;t.disable(t.STENCIL_TEST)}},XG.BloomPass=function(e,t,a,r){e=void 0!==e?e:1,t=void 0!==t?t:25,a=void 0!==a?a:4,r=void 0!==r?r:256;var i={minFilter:XG.LinearFilter,magFilter:XG.LinearFilter,format:XG.RGBAFormat};this.renderTargetX=new XG.RenderTarget(r,r,i),this.renderTargetY=new XG.RenderTarget(r,r,i);var o=XG.CopyShader;this.copyUniforms=XG.UniformsUtils.clone(o.uniforms),this.copyUniforms.opacity.value=e,this.materialCopy=new XG.ShaderMaterial({uniforms:this.copyUniforms,vertexShader:o.vertexShader,fragmentShader:o.fragmentShader,blending:XG.AdditiveBlending,transparent:!0});var n=XG.ConvolutionShader;this.convolutionUniforms=XG.UniformsUtils.clone(n.uniforms),this.convolutionUniforms.uImageIncrement.value=XG.BloomPass.blurx,this.convolutionUniforms.cKernel.value=XG.ConvolutionShader.buildKernel(a),this.materialConvolution=new XG.ShaderMaterial({uniforms:this.convolutionUniforms,vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,defines:{KERNEL_SIZE_FLOAT:t.toFixed(1),KERNEL_SIZE_INT:t.toFixed(0)}}),this.enabled=!0,this.needsSwap=!1,this.clear=!1},XG.BloomPass.prototype={render:function(e,t,a,r,i){i&&e.context.disable(e.context.STENCIL_TEST),XG.EffectComposer.quad.materials[0]=this.materialConvolution,this.convolutionUniforms.tDiffuse.value=a,this.convolutionUniforms.uImageIncrement.value=XG.BloomPass.blurX,e.render(XG.EffectComposer.scene,XG.EffectComposer.camera,this.renderTargetX,!0),this.convolutionUniforms.tDiffuse.value=this.renderTargetX,this.convolutionUniforms.uImageIncrement.value=XG.BloomPass.blurY,e.render(XG.EffectComposer.scene,XG.EffectComposer.camera,this.renderTargetY,!0),XG.EffectComposer.quad.materials[0]=this.materialCopy,this.copyUniforms.tDiffuse.value=this.renderTargetY,i&&e.context.enable(e.context.STENCIL_TEST),e.render(XG.EffectComposer.scene,XG.EffectComposer.camera,a,this.clear)}},XG.BloomPass.blurX=new XG.Vector2(.001953125,0),XG.BloomPass.blurY=new XG.Vector2(0,.001953125),XG.DepthOfFieldPass=function(e,t,a){e=void 0!==e?e:1024,t=void 0!==t?t:512;var r=a.isES3?XG.RGBA32F:XG.RGBAFormat,i={minFilter:XG.NearestFilter,magFilter:XG.NearestFilter,format:XG.RGBAFormat,internalFormat:r,type:XG.FloatType},o={minFilter:XG.LinearMipMapLinearFilter,magFilter:XG.LinearFilter,format:XG.RGBAFormat};this.renderTargetBlur=new XG.RenderTarget(e,t,o),this.renderTargetBlur.generateMipmaps=!0,this.renderTargetDistance1=new XG.RenderTarget(2,2,i),this.renderTargetDistance1.generateMipmaps=!1,this.renderTargetDistance2=this.renderTargetDistance1.clone(),this.renderTargetDistanceRead=this.renderTargetDistance1,this.renderTargetDistanceWrite=this.renderTargetDistance2;var n=XG.CopyShader;this.copyUniforms=XG.UniformsUtils.clone(n.uniforms),this.materialCopy=new XG.ShaderMaterial({uniforms:this.copyUniforms,vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,blending:XG.NoBlending,depthTest:!1,depthWrite:!1});var s=XG.DistanceShader;this.distanceUniforms=XG.UniformsUtils.clone(s.uniforms),this.materialDistance=new XG.ShaderMaterial({uniforms:this.distanceUniforms,vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,blending:XG.NoBlending,depthTest:!1,depthWrite:!1});var l=XG.DepthOfFieldShader;this.dofUniforms=XG.UniformsUtils.clone(l.uniforms),this.materialDOF=new XG.ShaderMaterial({uniforms:this.dofUniforms,vertexShader:l.vertexShader,fragmentShader:l.fragmentShader,blending:XG.NoBlending,depthTest:!1,depthWrite:!1}),this.dofUniforms.tBlur.value=this.renderTargetBlur,this.dofUniforms.blurSize.value.set(e,t),this.depthInput=null,this.colorInput=null,this.cameraNear=null,this.cameraFar=null,this.autoFocus=null,this.autoFocusPoint=null,this.focusDistance=null,this.focusRampStart=null,this.focusRampEnd=null,this.maxBlur=null,this.defines=null,this.enabled=!0,this.needsSwap=!0,this.clear=!1},XG.DepthOfFieldPass.prototype={resize:function(){},render:function(e,t,a){var r=this.dofUniforms,i=this.copyUniforms,o=this.distanceUniforms,n=this.renderTargetDistanceRead;
  this.renderTargetDistanceRead=this.renderTargetDistanceWrite,this.renderTargetDistanceWrite=n,r.tDepth.value=this.depthInput,o.tDepth.value=this.depthInput,r.autoFocus.value=this.autoFocus,r.autoFocusPoint.value.copy(this.autoFocusPoint),r.focusDistance.value=this.focusDistance,r.focusRampStart.value=this.focusRampStart,r.focusRampEnd.value=this.focusRampEnd,r.maxBlur.value=this.maxBlur,r.cameraNearFar.value.set(this.cameraNear,this.cameraFar),o.cameraNearFar.value.set(this.cameraNear,this.cameraFar),o.samplePoint.value.copy(this.autoFocusPoint),i.tDiffuse.value=a,r.tDiffuse.value=a,r.tDistance.value=this.renderTargetDistanceRead,o.tDistance.value=this.renderTargetDistanceRead,this.materialDistance.defines=this.defines,this.materialDOF.defines=this.defines,XG.EffectComposer.quad.materials[0]=this.materialCopy,e.render(XG.EffectComposer.scene,XG.EffectComposer.camera,this.renderTargetBlur,!0),XG.EffectComposer.quad.materials[0]=this.materialDOF,this.renderToScreen?e.render(XG.EffectComposer.scene,XG.EffectComposer.camera):e.render(XG.EffectComposer.scene,XG.EffectComposer.camera,t,this.clear),XG.EffectComposer.quad.materials[0]=this.materialDistance,e.render(XG.EffectComposer.scene,XG.EffectComposer.camera,this.renderTargetDistanceWrite,!1)}},XG.FancyDepthOfFieldPass=function(e,t,a,r){this.blurScale=void 0!==a?a:.75;var i,o,n,s=Math.max(1,Math.floor(this.blurScale*e)),l=Math.max(1,Math.floor(this.blurScale*t));r.isES3?(i=XG.RGBA32F,o=XG.RGBA16F,n=XG.HalfFloatType2):(i=XG.RGBAFormat,o=XG.RGBAFormat,n=XG.HalfFloatType1);var h,d,c,u={minFilter:XG.NearestFilter,magFilter:XG.NearestFilter,stencilBuffer:!1,format:XG.RGBAFormat,internalFormat:i,type:XG.FloatType},f={minFilter:XG.NearestFilter,magFilter:XG.NearestFilter,stencilBuffer:!1,format:XG.RGBAFormat,internalFormat:o,type:n},p={minFilter:XG.NearestFilter,magFilter:XG.LinearFilter,stencilBuffer:!1,format:XG.RGBAFormat,internalFormat:i,type:XG.FloatType},m={minFilter:XG.NearestFilter,magFilter:XG.NearestFilter,stencilBuffer:!1,format:XG.RGBAFormat,internalFormat:i,type:XG.FloatType},v={minFilter:XG.NearestFilter,magFilter:XG.LinearFilter,stencilBuffer:!1,format:XG.RGBAFormat,internalFormat:o,type:n},g={minFilter:XG.NearestFilter,magFilter:XG.NearestFilter,stencilBuffer:!1,format:XG.RGBAFormat,internalFormat:o,type:n},S={minFilter:XG.NearestFilter,magFilter:XG.LinearFilter,stencilBuffer:!1,format:XG.RGBAFormat,type:XG.UnsignedByteType};r.hasHalfFloatsLinear?(h=v,c=f,d=v):r.hasHalfFloatsNearest?(h=g,c=f,d=g):r.hasFloatsLinear?(h=p,c=u,d=p):r.hasFloatsNearest?(h=m,c=u,d=m):(h=S,c=S,d=S),this.renderTargetBlurAmount=new XG.RenderTarget(s,l,d),this.renderTargetBlurAmount.generateMipmaps=!1,this.renderTargetBlurPass1=new XG.RenderTarget(s,l,h),this.renderTargetBlurPass1.generateMipmaps=!1,this.renderTargetBlurPass2=new XG.RenderTarget(s,l,h),this.renderTargetBlurPass2.generateMipmaps=!1,this.renderTargetDistance1=new XG.RenderTarget(2,2,c),this.renderTargetDistance1.generateMipmaps=!1,this.renderTargetDistance2=this.renderTargetDistance1.clone(),this.renderTargetDistanceRead=this.renderTargetDistance1,this.renderTargetDistanceWrite=this.renderTargetDistance2;var G=XG.DOFBlurAmountShader;this.blurAmountUniforms=XG.UniformsUtils.clone(G.uniforms),this.materialBlurAmount=new XG.ShaderMaterial({uniforms:this.blurAmountUniforms,vertexShader:G.vertexShader,fragmentShader:G.fragmentShader,blending:XG.NoBlending,depthTest:!1,depthWrite:!1});var x=XG.DistanceShader;this.distanceUniforms=XG.UniformsUtils.clone(x.uniforms),this.materialDistance=new XG.ShaderMaterial({uniforms:this.distanceUniforms,vertexShader:x.vertexShader,fragmentShader:x.fragmentShader,blending:XG.NoBlending,depthTest:!1,depthWrite:!1});var M=XG.DOFBlurPass1Shader;this.dofPass1Uniforms=XG.UniformsUtils.clone(M.uniforms),this.materialDOFPass1=new XG.ShaderMaterial({uniforms:this.dofPass1Uniforms,vertexShader:M.vertexShader,fragmentShader:M.fragmentShader,blending:XG.NoBlending,depthTest:!1,depthWrite:!1});var y=XG.DOFBlurPass2Shader;this.dofPass2Uniforms=XG.UniformsUtils.clone(y.uniforms),this.materialDOFPass2=new XG.ShaderMaterial({uniforms:this.dofPass2Uniforms,vertexShader:y.vertexShader,fragmentShader:y.fragmentShader,blending:XG.NoBlending,depthTest:!1,depthWrite:!1}),this.depthInput=null,this.colorInput=null,this.cameraNear=null,this.cameraFar=null,this.autoFocus=null,this.autoFocusPoint=null,this.focusDistance=null,this.focusRampStart=null,this.focusRampEnd=null,this.maxBlur=null,this.lensFstop=null,this.lensFocalLength=null,this.lensBlurScale=null,this.lensMaxCoc=null,this.lensApertureSides=null,this.defines=null,this.oldLensApertureSides=null,this.enabled=!0,this.needsSwap=!0,this.clear=!1},XG.FancyDepthOfFieldPass.prototype={setLensApertureSides:function(e){(void 0===e||3>e)&&(e=3),this.dofPass1Uniforms.samplePoints1.value=XG.Math.generateConcentricCircleSamples(7,e),this.dofPass1Uniforms.samplePoints2.value=XG.Math.generateConcentricCircleSamples(3,e),this.dofPass2Uniforms.samplePoints.value=XG.Math.generateConcentricCircleSamples(3,e)},resize:function(e,t){var a=Math.max(1,Math.floor(this.blurScale*e)),r=Math.max(1,Math.floor(this.blurScale*t));this.renderTargetBlurAmount.setSize(a,r),this.renderTargetBlurPass1.setSize(a,r),this.renderTargetBlurPass2.setSize(a,r)},render:function(e){var t=this.dofPass1Uniforms,a=this.dofPass2Uniforms,r=this.blurAmountUniforms,i=(this.blurCompositeUniforms,this.distanceUniforms),o=this.renderTargetDistanceRead;if(this.renderTargetDistanceRead=this.renderTargetDistanceWrite,this.renderTargetDistanceWrite=o,this.lensApertureSides!==this.oldLensApertureSides){var n=XG.Math.generateConcentricCircleSamples(7,this.lensApertureSides),s=XG.Math.generateConcentricCircleSamples(3,this.lensApertureSides);t.samplePoints1.value=n,t.samplePoints2.value=s,a.samplePoints.value=s,this.oldLensApertureSides=this.lensApertureSides}r.tDepth.value=this.depthInput,i.tDepth.value=this.depthInput,t.tDiffuse.value=this.colorInput,t.resolution.value.set(this.colorInput.width,this.colorInput.height),r.tDiffuse.value=this.colorInput,r.resolution.value.set(this.colorInput.width,this.colorInput.height),r.cameraNearFar.value.set(this.cameraNear,this.cameraFar),r.autoFocus.value=this.autoFocus,r.autoFocusPoint.value.copy(this.autoFocusPoint),r.focusDistance.value=this.focusDistance,r.focusRampStart.value=this.focusRampStart,r.focusRampEnd.value=this.focusRampEnd,r.maxBlur.value=this.maxBlur,r.lensAperture.value=this.lensFocalLength/this.lensFstop,r.lensFocalLength.value=this.lensFocalLength,r.lensBlurScale.value=this.lensBlurScale,r.lensMaxCoc.value=this.lensMaxCoc,i.cameraNearFar.value.set(this.cameraNear,this.cameraFar),i.samplePoint.value.copy(this.autoFocusPoint),t.tBlurAmount.value=this.renderTargetBlurAmount,a.tBlurAmount.value=this.renderTargetBlurAmount,r.tDistance.value=this.renderTargetDistanceRead,i.tDistance.value=this.renderTargetDistanceRead,a.tDiffuse.value=this.renderTargetBlurPass1,a.resolution.value.set(this.colorInput.width,this.colorInput.height),this.materialBlurAmount.defines=this.defines,this.materialDistance.defines=this.defines,this.materialDOFPass1.defines=this.defines,this.materialDOFPass2.defines=this.defines,XG.EffectComposer.quad.materials[0]=this.materialBlurAmount,e.render(XG.EffectComposer.scene,XG.EffectComposer.camera,this.renderTargetBlurAmount,!0),XG.EffectComposer.quad.materials[0]=this.materialDOFPass1,e.render(XG.EffectComposer.scene,XG.EffectComposer.camera,this.renderTargetBlurPass1,!0),XG.EffectComposer.quad.materials[0]=this.materialDOFPass2,e.render(XG.EffectComposer.scene,XG.EffectComposer.camera,this.renderTargetBlurPass2,!0),XG.EffectComposer.quad.materials[0]=this.materialDistance,e.render(XG.EffectComposer.scene,XG.EffectComposer.camera,this.renderTargetDistanceWrite,!1)}},XG.PhysicsSimulation=function(e){var t=this,a=void 0!==e.useTransferables?e.useTransferables:!1,r=void 0!==e.workerUrl?e.workerUrl:"js/ammo/ammo.worker.js";this.currentFrame=0,this.currentFPS=0,this.allFPS=0,this.callbackIdle=null,this.callbackInitialized=null;var i,o=6,n=7,s=new Float32Array(0),l=[],h=[],d=[],c=[],u=[],f=function(e){for(var t=0,a=e.length;a>t;t++)for(var r=e[t].wheels,i=0,o=r.length;o>i;i++){var n=r[i],s=h.length;h.push(n.mesh),n.mesh=s}},p=function(e,t){for(var a=(e.length-t)/n,r=l.length,i=Math.min(a,r),o=0;i>o;o++){var s=l[o],h=s.position.data,d=s.quaternion.data;e[t]=h[0],e[t+1]=h[1],e[t+2]=h[2],e[t+3]=d[0],e[t+4]=d[1],e[t+5]=d[2],e[t+6]=d[3],t+=n}},m=function(e,t,a){var r=l.length,i=Math.min(a,r);a!==r&&console.warn("Number of physics bodies = ",a," while number of rendering bodies = ",r);for(var o=0;i>o;o++){var s=l[o],h=s.position.data,d=s.quaternion.data;h[0]=e[t],h[1]=e[t+1],h[2]=e[t+2],d[0]=e[t+3],d[1]=e[t+4],d[2]=e[t+5],d[3]=e[t+6],t+=n}return t},v=function(e,t,a){var r=h.length,i=Math.min(a,r);a!==r&&console.warn("Number of physics wheels = ",a," while number of rendering wheels = ",r);for(var o=0;i>o;o++){var s=h[o],l=s.position.data,d=s.quaternion.data;l[0]=e[t],l[1]=e[t+1],l[2]=e[t+2],d[0]=e[t+3],d[1]=e[t+4],d[2]=e[t+5],d[3]=e[t+6],t+=n}return t},g=function(e,t,a){var r=u.length,i=Math.min(a,r);a!==r&&console.warn("Number of physics vehicles = ",a," while number of local vehicles = ",r);for(var o=0;i>o;o++){var n=u[o],s=e[t];n.speed=s,t+=1}return t},S=function(e){var r,n=!1;a&&(e instanceof Float32Array?(r=e.buffer,0===e.length&&r.byteLength>0&&(e=new Float32Array(r))):e instanceof ArrayBuffer&&(r=e,e=new Float32Array(r),n=!0));var s=0,l=e[0];if(l>=t.currentFrame){t.currentFrame=l,t.currentFPS=e[1],t.allFPS=e[2];var h=e[3],d=e[4],c=e[5];s+=o,s=m(e,s,h),s=v(e,s,c),s=g(e,s,d)}else console.warn("Physics simulation frames received out of order");a&&(n?i.postMessage(e,[e.buffer]):i.postMessage(e.buffer,[e.buffer]))},G=function(e){var a=e.data;if(a instanceof Float32Array||a instanceof ArrayBuffer&&a.byteLength>1)S(a);else{var r=a;"simulationIdle"===r.type?t.callbackIdle&&t.callbackIdle():"simulationInitialized"===r.type?t.callbackInitialized&&t.callbackInitialized():"debug"===r.type&&console.log(r.content)}};this.loadPhysicsVehicle=function(e){var t,a,r,i,o,n=e.chassisUrl,s=e.wheelUrl,l=e.scale,h=e.position,d=e.chassisOffset,c=e.chassisShape,u=e.chassisPhysicsProperties,f=e.vehiclePhysicsProperties,p=e.wheels,m=e.callback,v=e.debugPhysicsShapes,g=[],S=0,G=function(){if(S+=1,2===S){var e=[t];e=e.concat(g),f.wheels=[];for(var n=0,s=p.length;s>n;n++){var h=p[n],d={mesh:g[n],isFrontWheel:h.isFrontWheel,wheelRadius:h.wheelRadius,suspensionRestLength:h.suspensionRestLength,connectionPoint:h.connectionPoint,wheelDirection:h.wheelDirection,wheelAxle:h.wheelAxle,tuning:h.tuning};f.wheels.push(d)}t.properties.physics=u;var v={chassisGeometries:a,wheelGeometries:r,chassisMaterials:i,wheelMaterials:o,parts:e,chassisShape:c,vehiclePhysicsProperties:f,scale:l};m(v)}},x=new XG.UTF8Loader;x.load(n,function(e,r){if(a=e,i=r,XG.GeometryUtils.center(e),d){var o=new XG.Matrix4,n=new XG.Vector3(d[0],d[1],d[2]);o.makeTranslation(n);for(var s=0;s<e.length;s++){var u=e[s];u.applyMatrix(o)}}if(t=new XG.Mesh(e,r),t.scale.multiplyScalar(l),t.position.set(h[0],h[1],h[2]),t.useQuaternion=!0,t.castShadow=!0,t.receiveShadow=!0,t.visible=!1,v)for(var f=[16711680,16755200,16711935,65280,16776960],p=new XG.Vector3(1,1,1).multiplyScalar(1/l),m=new XG.Vector3,g=new XG.Matrix4,S=new XG.Matrix4,s=0,x=c.children.length;x>s;s++){var M=new XG.EmissiveMaterial({color:f[s%f.length],transparent:!0,opacity:.8}),y=c.children[s],X=y.position;m.set(X[0],X[1],X[2]),S.makeScale(p),g.makeTranslation(m);var D=new XG.BoxGeometry(2*y.sx,2*y.sy,2*y.sz);D.applyMatrix(g),D.applyMatrix(S),D.computeBoundingSphere(),e.push(D),r.push(M)}G()}),x.load(s,function(e,t){r=e,o=t,XG.GeometryUtils.center(e);for(var a=0,i=p.length;i>a;a++){var n=p[a],s=new XG.Mesh(e,t);s.castShadow=!0,s.receiveShadow=!0,s.visible=!1;var d;n.mirrored?(s.rotation.y=Math.PI,d=new XG.Node,d.add(s)):d=s,d.useQuaternion=!0,d.scale.multiplyScalar(l),d.position.set(h[0],h[1],h[2]),g.push(d)}G()})},this.applyEngineForce=function(e,t,a){if(i){var r={type:"applyEngineForce",force:e,vehicleId:t,wheelId:a};i.postMessage(r)}},this.setSteering=function(e,t,a){if(i){var r={type:"setSteering",steering:e,vehicleId:t,wheelId:a};i.postMessage(r)}},this.setBrake=function(e,t,a){if(i){var r={type:"setBrake",brake:e,vehicleId:t,wheelId:a};i.postMessage(r)}},this.setGravity=function(e,t,a){if(i){var r={type:"setGravity",value:[e,t,a]};i.postMessage(r)}},this.resetTransforms=function(){if(i){var e=l.length,t=e*n;s.length<t&&(s=new Float32Array(t)),p(s,0);var a={type:"resetTransforms",nObjects:e,transforms:s};i.postMessage(a)}},this.startPhysics=function(e){l=e.objects,d=e.shapes,void 0!==e.constraints&&(c=e.constraints),void 0!==e.vehicles&&(u=e.vehicles,f(e.vehicles));for(var t=[],a=0,o=l.length;o>a;a++){var h=l[a],m=h.properties.physics,v=a,g=m.shapeId,S=void 0!==m.mass?m.mass:1,x=void 0!==m.linearSleepThreshold?m.linearSleepThreshold:.8,M=void 0!==m.angularSleepThreshold?m.angularSleepThreshold:1,y={bodyId:v,shapeId:g,mass:S,linearSleepThreshold:x,angularSleepThreshold:M};t.push(y)}var X=l.length,D=X*n;s.length<D&&(s=new Float32Array(D)),p(s,0),i=new Worker(r),i.onmessage=G;var _=void 0!==e.gravity?e.gravity:[0,-9.81,0],w=void 0!==e.floorEnabled?e.floorEnabled:!0,A={type:"init",nObjects:X,transforms:s,objectsData:t,shapesData:d,constraintsData:c,vehiclesData:u,floorEnabled:w,floorSize:.5*e.floorSize,floorHeight:e.floorHeight,gravity:_};i.postMessage(A)}};var Detector={canvas:!!window.CanvasRenderingContext2D,webgl:function(){try{var e=document.createElement("canvas");return!(!window.WebGLRenderingContext||!e.getContext("webgl")&&!e.getContext("experimental-webgl"))}catch(t){return!1}}(),webgl2:function(){try{var e=document.createElement("canvas");return!(!window.WebGL2RenderingContext||!e.getContext("webgl2")&&!e.getContext("experimental-webgl2"))}catch(t){return!1}}(),workers:!!window.Worker,fileapi:window.File&&window.FileReader&&window.FileList&&window.Blob,isMobile:!!(navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/webOS/i)||navigator.userAgent.match(/iPhone/i)||navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/iPod/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/Windows Phone/i)),isOpenGL:function(){try{var e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl"),a=t.getExtension("WEBGL_debug_renderer_info"),r="";a&&(r=t.getParameter(a.UNMASKED_RENDERER_WEBGL),r=r.toLowerCase());var i=r.indexOf("angle")>=0&&r.indexOf("opengl")<0,o=navigator.userAgent.toLowerCase().indexOf("trident")>=0,n=!(o||i);return n}catch(s){return!0}}(),supportsTransferables:function(){var e=!1;try{var t=new ArrayBuffer(1),a=window.URL||window.webkitURL,r=new Blob([""],{type:"application/x-javascript"}),i=a.createObjectURL(r),o=new Worker(i);o.postMessage(t,[t]),e=0===t.byteLength}catch(n){console.error(n)}return e},deferredCapable:function(){function e(e,t,a){var r=e.createFramebuffer(),i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.texImage2D(e.TEXTURE_2D,0,t,2,2,0,t,a,null),e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0);var o=e.checkFramebufferStatus(e.FRAMEBUFFER);return e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindTexture(e.TEXTURE_2D,null),o===e.FRAMEBUFFER_COMPLETE}try{var t=document.createElement("canvas"),a=t.getContext("webgl")||t.getContext("experimental-webgl"),r=a.getExtension("OES_texture_float"),i=a.getExtension("WEBGL_draw_buffers"),o=r&&e(a,a.RGBA,a.FLOAT);return o||!!i}catch(n){return!1}}(),getWebGLErrorMessage:function(e){var t=window.innerHeight,a=(window.screen.availHeight,50),r=4,i=0;451>t&&(r=1,a=75);var o=document.createElement("div");o.style.border="solid 0px #f00",o.style.color="#eee",o.style.width="100%",o.style.height=t-i+"px",o.style.position="absolute",o.style.top="0px",o.style.left="0px",o.style.margin="0",o.style.padding="0",o.style.paddingBottom=i+"px",o.style.display="block",o.style.backgroundSize="auto 100%",e&&(o.style.background="url('"+e+"') no-repeat center");var n=document.createElement("div");n.style.fontFamily="Avenir, Helvetica, Arial, sans-serif",n.style.fontWeight="bold",n.style.textAlign="center",n.style.lineHeight="1.5em",n.style.background="#000",n.style.opacity="0.75",n.style.padding="1em",n.style.margin="0 auto 0",n.style.marginTop=r+"em",n.style.width=a+"%",n.style.border="solid 0px #fff";var s="",l=["<b>THIS DEMO REQUIRES WEBGL</b><br/><br/>",'Your graphics card does not seem to support <a href="http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation" target="_top">WebGL</a>.<br/>','Find out how to get WebGL working <a href="http://get.webgl.org/" target="_top">here</a> or try visiting with a different browser or computer.'].join("\n"),h=["<b>THIS DEMO REQUIRES WEBGL</b><br/><br/>",'Your browser does not seem to support <a href="http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation" target="_top">WebGL</a>.<br/>','Find out how to get browser with WebGL support <a href="http://get.webgl.org/" target="_top">here</a>.'].join("\n"),d=["<b>THIS DEMO REQUIRES ADVANCED WEBGL FEATURES</b><br/><br/>",'Your graphics card or browser does not seem to support rendering into <a href="https://www.khronos.org/registry/webgl/extensions/WEBGL_draw_buffers/" target="_top">Multiple-Render-Targets</a>',' or <a href="https://www.khronos.org/registry/webgl/extensions/OES_texture_float/" target="_top">Floating Point Render-Targets</a>.<br/><br/>',"Try visiting on a different browser or different computer (try desktop PC or notebook, only very few phones or tablets support required features)."].join("\n");return this.webgl?this.deferredCapable||(s=d):s=window.WebGLRenderingContext?l:h,n.innerHTML=s,o.appendChild(n),o},addGetWebGLMessage:function(e){e=e||{};var t=void 0!==e.parent?e.parent:document.body,a=void 0!==e.id?e.id:"oldie",r=void 0!==e.fallbackImg?e.fallbackImg:null,i=Detector.getWebGLErrorMessage(r);i.id=a;var o=0,n=function(){var e=(document.body,document.documentElement,window.innerHeight);i.style.height=e-o+"px"};window.addEventListener("resize",n,!1),t.appendChild(i)}},GPUDetector=function(){var e=void 0,t={},a=[["Nvidia","GeForce","GTX Titan X SLI",28274,!0,!0],["Nvidia","GeForce","GTX 980 Ti SLI",26966,!0,!0],["Nvidia","GeForce","GTX 980 notebook SLI",23351,!1,!0],["AMD","Radeon","R9 295X2",22073,!0,!0],["Nvidia","GeForce","GTX 980M SLI",18632,!1,!0],["Nvidia","GeForce","GTX Titan Z",17851,!0,!0],["Nvidia","GeForce","GTX Titan X",17470,!0,!1],["Nvidia","Quadro","M6000",16993,!0,!1],["Nvidia","GeForce","GTX 980 Ti",16978,!0,!1],["AMD","Radeon","R9 Fury X",16096,!0,!1],["Nvidia","GeForce","GTX 970M SLI",14873,!1,!0],["AMD","Radeon","R9 Fury",14580,!0,!1],["AMD","Radeon","R9 Nano",13888,!0,!1],["Nvidia","GeForce","GTX 980",13386,!0,!1],["Nvidia","GeForce","GTX 980 notebook",13340,!1,!1],["AMD","Radeon","R9 390X",12855,!0,!1],["AMD","Radeon","R9 390",12044,!0,!1],["AMD","Radeon","R9 290X",11862,!0,!1],["Nvidia","GeForce","GTX 880M SLI",11817,!1,!0],["Nvidia","GeForce","GTX 690",11713,!0,!0],["Nvidia","GeForce","GTX Titan Black",11494,!0,!1],["Nvidia","GeForce","GTX 780 Ti",11275,!0,!1],["Nvidia","Quadro","M5000",10467,!0,!1],["Nvidia","GeForce","GTX 780M SLI",10091,!1,!0],["Nvidia","GeForce","GTX 970",10282,!0,!1],["AMD","Radeon","R9 290",10019,!0,!1],["Nvidia","GeForce","GTX Titan",9913,!0,!1],["Nvidia","GeForce","GTX 980M",9741,!1,!1],["Nvidia","Quadro","K6000",9717,!0,!1],["Nvidia","GeForce","GTX 780",9471,!0,!1],["AMD","Radeon","R9 380X",9250,!0,!1],["Nvidia","Quadro","M5000M",9103,!1,!1],["AMD","Radeon","R9 280X",8402,!0,!1],["AMD","Radeon","R9 380",8334,!0,!1],["AMD","FirePro","W8100",8159,!0,!1],["AMD","Radeon","R9 285",7951,!0,!1],["AMD","Radeon","HD 7970",7852,!0,!1],["Nvidia","Quadro","M4000",7710,!0,!1],["Nvidia","GeForce","GTX 770",7707,!0,!1],["Nvidia","GeForce","GTX 970M",7615,!1,!1],["Nvidia","GeForce","GTX 960",7542,!0,!1],["AMD","Radeon","R9 280",7223,!0,!1],["Nvidia","GeForce","GTX 680",7001,!0,!1],["AMD","FirePro","W7170M",6935,!1,!1],["AMD","Radeon","R9 M395X",6859,!1,!1],["AMD","Radeon","R9 M395",6819,!1,!1],["Nvidia","GeForce","GTX 950",6764,!0,!1],["AMD","FirePro","D700",6764,!0,!1],["AMD","Radeon","R9 M295X",6590,!1,!1],["Nvidia","Quadro","M3000M",6415,!1,!1],["AMD","Radeon","HD 7950",6410,!0,!1],["Nvidia","GeForce","GTX 670",6286,!0,!1],["Nvidia","GeForce","GTX 965M Ti",6160,!1,!1],["Nvidia","GeForce","GTX 880M",6101,!1,!1],["Nvidia","GeForce","GTX 860M SLI",5941,!1,!0],["AMD","Radeon","R9 270X",5954,!0,!1],["Nvidia","GeForce","GTX 760",5906,!0,!1],["Nvidia","GeForce","GTX 660 Ti",5720,!0,!1],["AMD","Radeon","R9 270",5716,!0,!1],["Nvidia","GeForce","GTX 965M",5394,!1,!1],["AMD","Radeon","HD 7870",5295,!0,!1],["AMD","Radeon","R9 M290X",5294,!1,!1],["Nvidia","GeForce","GTX 780M",5244,!1,!1],["Nvidia","GeForce","GTX 580",5045,!0,!0],["AMD","Radeon","R9 370",5041,!0,!1],["AMD","Radeon","HD 8970M",5038,!1,!1],["Nvidia","Quadro","K5000",5007,!0,!1],["AMD","Radeon","R7 265",4948,!0,!1],["AMD","FirePro","D300",4899,!0,!1],["Nvidia","Quadro","K5100M",4776,!1,!1],["Nvidia","GeForce","GTX 680MX",4758,!1,!1],["Nvidia","GeForce","GTX 870M",4694,!1,!1],["AMD","Radeon","HD 7970M",4694,!1,!1],["AMD","FirePro","D500",4556,!0,!1],["Nvidia","GeForce","GTX 660",4524,!0,!1],["Nvidia","GeForce","GTX 960M",4365,!1,!1],["Nvidia","GeForce","GTX 570",4336,!0,!1],["Nvidia","Quadro","M2000M",4224,!1,!1],["AMD","Radeon","HD 7850",4224,!0,!1],["Nvidia","GeForce","GTX 750 Ti",4211,!0,!1],["Nvidia","GeForce","GT 755M SLI",4106,!1,!0],["Nvidia","GeForce","GTX 680M",4049,!1,!1],["AMD","Radeon","R9 260X",4016,!0,!1],["AMD","Radeon","HD 6970",3995,!0,!1],["Nvidia","GeForce","GTX 860M",3919,!1,!1],["AMD","Radeon","R7 260",3885,!0,!1],["AMD","Radeon","R9 360",3839,!0,!1],["AMD","FirePro","M6100",3837,!1,!1],["Nvidia","GeForce","GTX 750",3810,!0,!1],["AMD","Radeon","HD 7790",3759,!0,!1],["Nvidia","GeForce","GT 750M SLI",3703,!1,!0],["Nvidia","Quadro","K4100M",3654,!1,!1],["AMD","Radeon","HD 5870",3613,!0,!1],["Nvidia","GeForce","GTX 950M",3568,!1,!1],["AMD","Radeon","HD 6950",3553,!0,!1],["Nvidia","Quadro","M1000M",3517,!1,!1],["Nvidia","GeForce","GTX 480",3480,!0,!1],["AMD","Radeon","R9 M385X",3352,!1,!1],["AMD","Radeon","R9 M280X",3349,!1,!1],["Nvidia","GeForce","GTX 770M",3347,!1,!1],["Nvidia","GeForce","GTX 560 Ti",3256,!0,!1],["Nvidia","GeForce","GTX 650 Ti",3329,!0,!1],["Nvidia","Quadro","K4000",3229,!0,!1],["AMD","Radeon","HD 6870",3204,!0,!1],["Nvidia","GeForce","GTX 850M",3118,!1,!1],["AMD","Radeon","HD 5850",3037,!0,!1],["AMD","Radeon","HD 7770",3016,!0,!1],["Nvidia","GeForce","GTX 560",2886,!0,!1],["Nvidia","GeForce","945M",2884,!1,!1],["Nvidia","GeForce","GTX 675MX",2831,!0,!1],["Nvidia","GeForce","GTX 470",2802,!0,!1],["Nvidia","Quadro","K5000M",2797,!1,!1],["AMD","Radeon","HD 5830",2778,!0,!1],["Nvidia","GeForce","GTX 460",2762,!0,!1],["AMD","Radeon","HD 6850",2707,!0,!1],["Nvidia","Quadro","6000",2563,!0,!1],["AMD","Radeon","HD 6990M",2560,!1,!1],["Nvidia","GeForce","GTX 580M",2509,!1,!1],["Nvidia","GeForce","GTX 765M",2479,!1,!1],["AMD","Radeon","HD 7870M",2478,!1,!1],["AMD","Radeon","R9 M370X",2419,!1,!1],["Nvidia","Quadro","K620",2381,!0,!1],["Nvidia","Quadro","K3100M",2381,!1,!1],["Nvidia","GeForce","845M",2362,!1,!1],["Nvidia","GeForce","GTX 745",2349,!0,!1],["Nvidia","GeForce","GTX 675M",2331,!1,!1],["Nvidia","GeForce","GTX 485M",2330,!1,!1],["AMD","FirePro","M6000",2398,!1,!1],["AMD","FirePro","M5100",2327,!1,!1],["Nvidia","GeForce","GTX 760M",2271,!1,!1],["Nvidia","GeForce","GTX 465",2253,!0,!1],["AMD","Radeon","HD 7750",2215,!0,!1],["Nvidia","Quadro","K4000M",2199,!1,!1],["AMD","Radeon","HD 6970M",2186,!1,!1],["AMD","Radeon","HD 8870M",2168,!1,!1],["AMD","Radeon","R7 250",2147,!0,!1],["Nvidia","GeForce","GT 755M",2105,!1,!1],["AMD","Radeon","HD 5770",2072,!0,!1],["Nvidia","GeForce","GT 740",2042,!0,!1],["Nvidia","GeForce","Surface Book",2031,!1,!1],["Nvidia","GeForce","GTX 570M",2020,!1,!0],["Nvidia","GeForce","GTX 650",2002,!0,!1],["AMD","Radeon","R9 M265X",1997,!1,!1],["AMD","Radeon","HD 6770",1951,!0,!1],["Nvidia","GeForce","GTX 670M",1950,!1,!1],["AMD","Radeon","R7 M275DX",1931,!1,!0],["AMD","Radeon","R9 M275",1885,!1,!1],["Nvidia","GeForce","GTX 550 Ti",1881,!0,!1],["Nvidia","Quadro","5000",1873,!0,!1],["AMD","Radeon","HD 8850M",1845,!1,!1],["Intel","Iris Pro","6200",1773,!1,!1],["AMD","FirePro","W4170M",1766,!1,!1],["AMD","Radeon","R7 M370",1760,!1,!1],["Nvidia","GeForce","GTX 660M",1751,!1,!1],["Nvidia","GeForce","GT 640",1735,!0,!1],["AMD","Radeon","HD 8790M",1727,!1,!1],["Nvidia","GeForce","GTS 450",1724,!0,!1],["AMD","Radeon","R8 M365DX",1716,!1,!0],["AMD","FirePro","M4000",1713,!1,!1],["AMD","Radeon","HD 7730",1689,!0,!1],["AMD","Radeon","R9 M375",1679,!1,!1],["AMD","FirePro","W4100",1665,!0,!1],["Nvidia","GeForce","GTX 470M",1664,!1,!1],["Nvidia","Quadro","4000M",1663,!1,!1],["Nvidia","Quadro","K620M",1621,!1,!1],["Nvidia","Quadro","K2100M",1609,!1,!1],["AMD","Radeon","HD 6750",1594,!0,!1],["Nvidia","GeForce","940M",1582,!1,!1],["Nvidia","GeForce","GT 730",1582,!0,!1],["Nvidia","GeForce","GT 750M",1574,!1,!1],["Nvidia","GeForce","840M",1563,!1,!1],["Nvidia","GeForce","GT 745M",1549,!1,!1],["Nvidia","GeForce","GTX 480M",1541,!1,!1],["Intel","Iris Pro","5200",1536,!1,!1],["Nvidia","GeForce","930M",1442,!1,!1],["Nvidia","GeForce","GTX 560M",1435,!1,!1],["Nvidia","GeForce","GT 650M",1420,!1,!1],["Nvidia","GeForce","830M",1403,!1,!1],["AMD","Radeon","R7 M260X",1396,!1,!1],["Nvidia","Quadro","4000",1366,!0,!1],["Nvidia","Quadro","K2000M",1344,!1,!1],["AMD","Radeon","R7 M265",1329,!1,!1],["Nvidia","Quadro","K1100M",1326,!1,!1],["AMD","Radeon","HD 8750M",1276,!1,!1],["Nvidia","Quadro","2000",1272,!0,!1],["Nvidia","Quadro","3000M",1269,!1,!1],["AMD","Radeon","HD 6670",1240,!0,!1],["Nvidia","GeForce","GT 640M ",1225,!1,!1],["AMD","Radeon","R7 M340",1212,!1,!1],["AMD","Radeon","HD 8690M",1210,!1,!1],["Intel","HD Graphics","530",1202,!1,!1],["AMD","Radeon","R7 M270",1184,!1,!1],["Nvidia","GeForce","GTX 460M",1162,!1,!1],["Nvidia","GeForce","920M",1161,!1,!1],["AMD","Radeon","R7 240",1153,!0,!1],["Nvidia","GeForce","GT 645M",1151,!1,!1],["Nvidia","GeForce","GT 740M",1151,!1,!1],["AMD","Radeon","HD 8730M",1150,!1,!1],["Nvidia","GeForce","825M",1150,!1,!1],["AMD","Radeon","R7 M360",1122,!1,!1],["AMD","Radeon","R6 M255DX",1115,!1,!0],["AMD","FirePro","W2100",1085,!0,!1],["Nvidia","Quadro","2000M",1076,!1,!1],["AMD","Radeon","R5 M255",1064,!1,!1],["Nvidia","GeForce","GT 730M",1061,!1,!1],["AMD","Radeon","R7 M260",1057,!1,!1],["AMD","Radeon","HD 8650M",1050,!1,!1],["Intel","HD Graphics","6000",1033,!1,!1],["Nvidia","GeForce","GT 735M",1023,!1,!1],["Intel","Iris Graphics","6100",1020,!1,!1],["Intel","HD Graphics","5600",991,!1,!1],["Nvidia","GeForce","GT 555M",922,!1,!1],["AMD","Radeon","R5 M240",921,!1,!1],["AMD","Radeon","R5 M335",911,!1,!1],["AMD","Radeon","HD 8650G",905,!1,!1],["Nvidia","Quadro","K600",900,!0,!1],["Intel","Iris Graphics","5100",878,!1,!1],["AMD","Radeon","HD 6570",864,!0,!1],["AMD","FirePro","M4100",857,!1,!1],["Nvidia","Quadro","K1000M",857,!1,!1],["Nvidia","GeForce","GT 635M",851,!1,!1],["AMD","Radeon","R7 Kaveri",851,!1,!1],["AMD","Radeon","R5 M330",848,!1,!1],["Intel","HD Graphics","520",844,!1,!1],["Nvidia","GeForce","820M",829,!1,!1],["AMD","Radeon","HD 8670M",829,!1,!1],["Nvidia","GeForce","GT 625M",827,!1,!1],["AMD","Radeon","HD 7670M",824,!1,!1],["Nvidia","GeForce","GT 720M",822,!1,!1],["Nvidia","GeForce","GT 720",811,!0,!1],["Nvidia","GeForce","GT 550M",796,!1,!1],["AMD","Radeon","HD 8550G",792,!1,!1],["AMD","Radeon","HD 7560D",791,!0,!1],["AMD","Radeon","HD 8570M",790,!1,!1],["Nvidia","GeForce","GT 620",772,!0,!1],["AMD","Radeon","R5 M230",771,!1,!1],["AMD","Radeon","R6 Kaveri",770,!1,!1],["Nvidia","GeForce","710M",768,!1,!1],["Nvidia","Quadro","K610M",755,!1,!1],["Nvidia","Quadro","1000M",751,!1,!1],["Intel","HD Graphics","515",748,!1,!1],["Nvidia","GeForce","GT 620M",737,!1,!1],["Nvidia","GeForce","GT 430",735,!0,!1],["Intel","HD Graphics","5000",734,!1,!1],["Nvidia","GeForce","GT 540M",728,!1,!1],["Nvidia","GeForce","GT 630M",719,!1,!1],["AMD","Radeon","HD 7620G",716,!1,!1],["Nvidia","Quadro","600",710,!0,!1],["Nvidia","NVS","5200M",704,!1,!1],["AMD","Radeon","HD 8470D",670,!0,!1],["Nvidia","GeForce","GT 630",665,!0,!1],["Intel","HD Graphics","5500",663,!1,!1],["Intel","HD Graphics","4600",635,!1,!1],["AMD","Radeon","HD 7610M",605,!1,!1],["AMD","Radeon","R5 Kaveri",572,!1,!1],["Intel","HD Graphics","4400",571,!1,!1],["AMD","Radeon","HD 7570M",569,!1,!1],["AMD","Radeon","HD 7550M",569,!1,!1],["Nvidia","GeForce","GT 525M",545,!1,!1],["AMD","Radeon","R5 Beema",524,!1,!1],["AMD","Radeon","HD 7500G",512,!1,!1],["AMD","Radeon","R4 Beema",494,!1,!1],["Intel","HD Graphics","4000",480,!1,!1],["Intel","HD Graphics","5300",478,!1,!1],["AMD","Radeon","HD 8610G",475,!1,!1],["AMD","Radeon","HD 8450G",464,!1,!1],["AMD","Radeon","HD 6530D",452,!0,!1],["AMD","Radeon","HD 6450",450,!0,!1],["AMD","Radeon","HD 7480D",445,!0,!1],["AMD","Radeon","R3 Beema",432,!1,!1],["AMD","Radeon","HD 6480G",416,!1,!1],["Nvidia","GeForce","GT 520M",413,!1,!1],["Nvidia","GeForce","GT 610",406,!0,!1],["AMD","Radeon","HD 8400",401,!0,!1],["Intel","HD Graphics","4200",395,!1,!1],["Nvidia","GeForce","GT 520",389,!0,!1],["AMD","Radeon","HD 8350G",388,!1,!1],["AMD","Radeon","HD 7470M",384,!1,!1],["Intel","HD Graphics","Haswell",355,!1,!1],["AMD","Radeon","HD 8330",352,!0,!1],["AMD","Radeon","HD 7420G",343,!0,!1],["AMD","Radeon","HD 8280",328,!0,!1],["AMD","Radeon","HD 7400G",328,!0,!1],["Intel","HD Graphics","2500",318,!1,!1],["AMD","Radeon","HD 8240",290,!0,!1],["Intel","HD Graphics","Ivy Bridge",285,!1,!1],["AMD","Radeon","HD 8250",253,!0,!1],["Intel","HD Graphics","Braswell",233,!1,!1],["AMD","Radeon","HD 8210",227,!0,!1],["AMD","Radeon","HD 7340",224,!1,!1],["AMD","Radeon","HD 7310",192,!1,!1],["Intel","HD Graphics","Bay Trail",150,!1,!1],["AMD","Radeon","HD 8180",145,!0,!1]],r=function(){for(var e=0,r=a.length;r>e;e++){var i=a[e],s=i[0],l=i[1],h=i[2],d=i[3],c=i[4],u=s+" "+l+" "+h,f=h,p=" (notebook)";c&&(p=" (desktop)"),("Intel"===s||"NVS"===l||"FirePro"===l||"Quadro"===l)&&(f=l+" "+h);var m=o(u);t[m]={rawScore:d,formattedScore:n(d),fullName:u,shortName:f,type:p,vendor:s.toLowerCase()}}},i=function(e){var t=e.replace(/\((R|TM)\)/,"");return t=t.replace("ANGLE","").replace("Corporation ","").replace(/Direct3D\w*/,"").replace(/vs_\w*/,"").replace(/ps_\w*/,"").replace(/[\(\)]/g,""),t=t.replace("/PCIe/SSE2",""),t=t.replace(/OpenGL \d*\.\d* compatibility/,""),t.trim()},o=function(e){return e.toUpperCase()},n=function(e){for(var t=e.toString(),a=[],r=0,i=0,o=t.length;o>r;r++,i++){var n=t[o-1-r];a[i]=n,r%3===2&&o-1>r&&(i+=1,a[i]=",")}return a.reverse().join("")};this.detectGPU=function(){var a=null;if(void 0===e){e="";try{if(void 0!==window.WebGLRenderingContext){var r=document.createElement("canvas"),n=r.getContext("webgl")||r.getContext("experimental-webgl");if(void 0!==n){var s=n.getExtension("WEBGL_debug_renderer_info");if(void 0!==s){var l=n.getParameter(s.UNMASKED_RENDERER_WEBGL),h=i(l);!(h.toLowerCase().indexOf("geforce")>=0||h.toLowerCase().indexOf("quadro")>=0)||h.toLowerCase().indexOf("nvidia")>=0||(h="NVIDIA "+h),e=h}}}}catch(d){}}if(""!==e){var c=o(e);void 0!==t[c]&&(a=t[c])}return a},r()};!function(){for(var e=0,t=["ms","moz","webkit","o"],a=0;a<t.length&&!window.requestAnimationFrame;++a)window.requestAnimationFrame=window[t[a]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[t[a]+"CancelAnimationFrame"]||window[t[a]+"CancelRequestAnimationFrame"];void 0===window.requestAnimationFrame&&(window.requestAnimationFrame=function(t){var a=Date.now(),r=Math.max(0,16-(a-e)),i=window.setTimeout(function(){t(a+r)},r);return e=a+r,i}),window.cancelAnimationFrame=window.cancelAnimationFrame||function(e){window.clearTimeout(e)}}(),self.console=self.console||{info:function(){},log:function(){},debug:function(){},warn:function(){},error:function(){}},self.Int32Array=self.Int32Array||Array,self.Float32Array=self.Float32Array||Array,String.prototype.startsWith=String.prototype.startsWith||function(e){return this.slice(0,e.length)===e
  },String.prototype.endsWith=String.prototype.endsWith||function(e){var t=String(e),a=this.lastIndexOf(t);return(a>-1&&a)===this.length-t.length},String.prototype.trim=String.prototype.trim||function(){return this.replace(/^\s+|\s+$/g,"")},function(e,t,a,r,i,o){function n(e){var t,a=e.length,i=this,o=0,n=i.i=i.j=0,s=i.S=[];for(a||(e=[a++]);r>o;)s[o]=o++;for(o=0;r>o;o++)s[o]=s[n=p&n+e[o%a]+(t=s[o])],s[n]=t;(i.g=function(e){for(var t,a=0,o=i.i,n=i.j,s=i.S;e--;)t=s[o=p&o+1],a=a*r+s[p&(s[o]=s[n=p&n+t])+(s[n]=t)];return i.i=o,i.j=n,a})(r)}function s(e,t){var a,r=[],i=(typeof e)[0];if(t&&"o"==i)for(a in e)try{r.push(s(e[a],t-1))}catch(o){}return r.length?r:"s"==i?e:e+"\x00"}function l(e,t){for(var a,r=e+"",i=0;i<r.length;)t[p&i]=p&(a^=19*t[p&i])+r.charCodeAt(i++);return d(t)}function h(a){try{return e.crypto.getRandomValues(a=new Uint8Array(r)),d(a)}catch(i){return[+new Date,e,e.navigator.plugins,e.screen,d(t)]}}function d(e){return String.fromCharCode.apply(0,e)}var c=a.pow(r,i),u=a.pow(2,o),f=2*u,p=r-1;a.seedrandom=function(e,o){var p=[],m=l(s(o?[e,d(t)]:0 in arguments?e:h(),3),p),v=new n(p);return l(d(v.S),t),a.srandom=function(){for(var e=v.g(i),t=c,a=0;u>e;)e=(e+a)*r,t*=r,a=v.g(1);for(;e>=f;)e/=2,t/=2,a>>>=1;return(e+a)/t},m},l(a.random(),t)}(this,[],Math,256,6,52),XG.CubeSimulationShader={uniforms:{tOldSim:{type:"t",value:null},resolution:{type:"v2",value:new XG.Vector2(512,512)},mouse:{type:"v2",value:new XG.Vector2(0,0)},mouseDelta:{type:"v2",value:new XG.Vector2(0,0)},timeDelta:{type:"f",value:0},time:{type:"f",value:0},radius:{type:"f",value:.2}},vertexShader:XG.ShaderChunk.vertexShaderFullscreenTriangleUV,fragmentShader:["uniform sampler2D tOldSim;","uniform vec2 resolution;","uniform vec2 mouse;","uniform vec2 mouseDelta;","uniform float time;","uniform float timeDelta;","uniform float radius;","varying vec2 vUv;","void main() {","const float dampingFactor1 = 0.995;","const float dampingFactor2 = 0.064;","vec2 texelSize = vec2( 2.0 / resolution );","vec4 simState = texture2D( tOldSim, vUv );","vec2 du = vec2( texelSize.x, 0.0 );","vec2 dv = vec2( 0.0, texelSize.y );","float xx = length( ( mouse - vUv ) * vec2( resolution.x/resolution.y, 1.0 ) );","float activeArea = 0.25 * exp( - 100.1 * ( xx * xx ) );","simState.xy += activeArea * mouseDelta * 4.0;","simState.xy *= dampingFactor1;","simState.zw += simState.xy * dampingFactor2;","simState.zw = 0.075 * ( texture2D( tOldSim, vUv + du ).zw","+ texture2D( tOldSim, vUv - du ).zw","+ texture2D( tOldSim, vUv + dv ).zw","+ texture2D( tOldSim, vUv - dv ).zw ) + 0.7 * simState.zw;","du *= 3.0;","dv *= 3.0;","simState.zw = 0.05 * ( texture2D( tOldSim, vUv + du ).zw","+ texture2D( tOldSim, vUv - du ).zw","+ texture2D( tOldSim, vUv + dv ).zw","+ texture2D( tOldSim, vUv - dv ).zw ) + 0.8 * simState.zw;","mgl_FragColor = simState;","}"].join("\n")};
  // footer
  
  XG.BUILD_NUMBER = 532;
  XG.BUILD_DATE = '2016-02-18';
  
  console.log( 'XG [version ' + XG.VERSION + " | build " + XG.BUILD_NUMBER + " | " + XG.BUILD_DATE + "]" );
  