var BABYLON;(function(BABYLON){var Color3=(function(){function Color3(r,g,b){if(typeof r==="undefined"){r=0;}if(typeof g==="undefined"){g=0;}if(typeof b==="undefined"){b=0;}this.r=r;this.g=g;this.b=b;}Color3.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}";};Color3.prototype.toArray=function(array,index){if(index===undefined){index=0;}array[index]=this.r;array[index+1]=this.g;array[index+2]=this.b;};Color3.prototype.asArray=function(){var result=[];this.toArray(result,0);return result;};Color3.prototype.multiply=function(otherColor){return new Color3(this.r*otherColor.r,this.g*otherColor.g,this.b*otherColor.b);};Color3.prototype.multiplyToRef=function(otherColor,result){result.r=this.r*otherColor.r;result.g=this.g*otherColor.g;result.b=this.b*otherColor.b;};Color3.prototype.equals=function(otherColor){return otherColor&&this.r===otherColor.r&&this.g===otherColor.g&&this.b===otherColor.b;};Color3.prototype.scale=function(scale){return new Color3(this.r*scale,this.g*scale,this.b*scale);};Color3.prototype.scaleToRef=function(scale,result){result.r=this.r*scale;result.g=this.g*scale;result.b=this.b*scale;};Color3.prototype.add=function(otherColor){return new Color3(this.r+otherColor.r,this.g+otherColor.g,this.b+otherColor.b);};Color3.prototype.addToRef=function(otherColor,result){result.r=this.r+otherColor.r;result.g=this.g+otherColor.g;result.b=this.b+otherColor.b;};Color3.prototype.subtract=function(otherColor){return new Color3(this.r-otherColor.r,this.g-otherColor.g,this.b-otherColor.b);};Color3.prototype.subtractToRef=function(otherColor,result){result.r=this.r-otherColor.r;result.g=this.g-otherColor.g;result.b=this.b-otherColor.b;};Color3.prototype.clone=function(){return new Color3(this.r,this.g,this.b);};Color3.prototype.copyFrom=function(source){this.r=source.r;this.g=source.g;this.b=source.b;};Color3.prototype.copyFromFloats=function(r,g,b){this.r=r;this.g=g;this.b=b;};Color3.FromArray=function(array){return new Color3(array[0],array[1],array[2]);};Color3.FromInts=function(r,g,b){return new Color3(r/255.0,g/255.0,b/255.0);};Color3.Lerp=function(start,end,amount){var r=start.r+((end.r-start.r)*amount);var g=start.g+((end.g-start.g)*amount);var b=start.b+((end.b-start.b)*amount);return new Color3(r,g,b);};Color3.Red=function(){return new Color3(1,0,0);};Color3.Green=function(){return new Color3(0,1,0);};Color3.Blue=function(){return new Color3(0,0,1);};Color3.Black=function(){return new Color3(0,0,0);};Color3.White=function(){return new Color3(1,1,1);};Color3.Purple=function(){return new Color3(0.5,0,0.5);};Color3.Magenta=function(){return new Color3(1,0,1);};Color3.Yellow=function(){return new Color3(1,1,0);};Color3.Gray=function(){return new Color3(0.5,0.5,0.5);};return Color3;})();BABYLON.Color3=Color3;var Color4=(function(){function Color4(r,g,b,a){this.r=r;this.g=g;this.b=b;this.a=a;}Color4.prototype.addInPlace=function(right){this.r+=right.r;this.g+=right.g;this.b+=right.b;this.a+=right.a;};Color4.prototype.asArray=function(){var result=[];this.toArray(result,0);return result;};Color4.prototype.toArray=function(array,index){if(index===undefined){index=0;}array[index]=this.r;array[index+1]=this.g;array[index+2]=this.b;array[index+3]=this.a;};Color4.prototype.add=function(right){return new Color4(this.r+right.r,this.g+right.g,this.b+right.b,this.a+right.a);};Color4.prototype.subtract=function(right){return new Color4(this.r-right.r,this.g-right.g,this.b-right.b,this.a-right.a);};Color4.prototype.subtractToRef=function(right,result){result.r=this.r-right.r;result.g=this.g-right.g;result.b=this.b-right.b;result.a=this.a-right.a;};Color4.prototype.scale=function(scale){return new Color4(this.r*scale,this.g*scale,this.b*scale,this.a*scale);};Color4.prototype.scaleToRef=function(scale,result){result.r=this.r*scale;result.g=this.g*scale;result.b=this.b*scale;result.a=this.a*scale;};Color4.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}";};Color4.prototype.clone=function(){return new Color4(this.r,this.g,this.b,this.a);};Color4.Lerp=function(left,right,amount){var result=new Color4(0,0,0,0);BABYLON.Color4.LerpToRef(left,right,amount,result);return result;};Color4.LerpToRef=function(left,right,amount,result){result.r=left.r+(right.r-left.r)*amount;result.g=left.g+(right.g-left.g)*amount;result.b=left.b+(right.b-left.b)*amount;result.a=left.a+(right.a-left.a)*amount;};Color4.FromArray=function(array,offset){if(typeof offset==="undefined"){offset=0;}return new Color4(array[offset],array[offset+1],array[offset+2],array[offset+3]);};Color4.FromInts=function(r,g,b,a){return new Color4(r/255.0,g/255.0,b/255.0,a/255.0);};return Color4;})();BABYLON.Color4=Color4;var Vector2=(function(){function Vector2(x,y){this.x=x;this.y=y;}Vector2.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+"}";};Vector2.prototype.toArray=function(array,index){if(index===undefined){index=0;}array[index]=this.x;array[index+1]=this.y;};Vector2.prototype.asArray=function(){var result=[];this.toArray(result,0);return result;};Vector2.prototype.copyFrom=function(source){this.x=source.x;this.y=source.y;};Vector2.prototype.add=function(otherVector){return new Vector2(this.x+otherVector.x,this.y+otherVector.y);};Vector2.prototype.subtract=function(otherVector){return new Vector2(this.x-otherVector.x,this.y-otherVector.y);};Vector2.prototype.negate=function(){return new Vector2(-this.x,-this.y);};Vector2.prototype.scaleInPlace=function(scale){this.x*=scale;this.y*=scale;};Vector2.prototype.scale=function(scale){return new Vector2(this.x*scale,this.y*scale);};Vector2.prototype.equals=function(otherVector){return otherVector&&this.x===otherVector.x&&this.y===otherVector.y;};Vector2.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y);};Vector2.prototype.lengthSquared=function(){return(this.x*this.x+this.y*this.y);};Vector2.prototype.normalize=function(){var len=this.length();if(len===0)return;var num=1.0/len;this.x*=num;this.y*=num;};Vector2.prototype.clone=function(){return new Vector2(this.x,this.y);};Vector2.Zero=function(){return new Vector2(0,0);};Vector2.FromArray=function(array,offset){if(!offset){offset=0;}return new Vector2(array[offset],array[offset+1]);};Vector2.CatmullRom=function(value1,value2,value3,value4,amount){var squared=amount*amount;var cubed=amount*squared;var x=0.5*((((2.0*value2.x)+((-value1.x+value3.x)*amount))+(((((2.0*value1.x)-(5.0*value2.x))+(4.0*value3.x))-value4.x)*squared))+((((-value1.x+(3.0*value2.x))-(3.0*value3.x))+value4.x)*cubed));var y=0.5*((((2.0*value2.y)+((-value1.y+value3.y)*amount))+(((((2.0*value1.y)-(5.0*value2.y))+(4.0*value3.y))-value4.y)*squared))+((((-value1.y+(3.0*value2.y))-(3.0*value3.y))+value4.y)*cubed));return new Vector2(x,y);};Vector2.Clamp=function(value,min,max){var x=value.x;x=(x>max.x)?max.x:x;x=(xmax.y)?max.y:y;y=(yright.x)?left.x:right.x;var y=(left.y>right.y)?left.y:right.y;return new Vector2(x,y);};Vector2.Transform=function(vector,transformation){var x=(vector.x*transformation.m[0])+(vector.y*transformation.m[4]);var y=(vector.x*transformation.m[1])+(vector.y*transformation.m[5]);return new Vector2(x,y);};Vector2.Distance=function(value1,value2){return Math.sqrt(Vector2.DistanceSquared(value1,value2));};Vector2.DistanceSquared=function(value1,value2){var x=value1.x-value2.x;var y=value1.y-value2.y;return(x*x)+(y*y);};return Vector2;})();BABYLON.Vector2=Vector2;var Vector3=(function(){function Vector3(x,y,z){this.x=x;this.y=y;this.z=z;}Vector3.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+"}";};Vector3.prototype.asArray=function(){var result=[];this.toArray(result,0);return result;};Vector3.prototype.toArray=function(array,index){if(index===undefined){index=0;}array[index]=this.x;array[index+1]=this.y;array[index+2]=this.z;};Vector3.prototype.addInPlace=function(otherVector){this.x+=otherVector.x;this.y+=otherVector.y;this.z+=otherVector.z;};Vector3.prototype.add=function(otherVector){return new Vector3(this.x+otherVector.x,this.y+otherVector.y,this.z+otherVector.z);};Vector3.prototype.addToRef=function(otherVector,result){result.x=this.x+otherVector.x;result.y=this.y+otherVector.y;result.z=this.z+otherVector.z;};Vector3.prototype.subtractInPlace=function(otherVector){this.x-=otherVector.x;this.y-=otherVector.y;this.z-=otherVector.z;};Vector3.prototype.subtract=function(otherVector){return new Vector3(this.x-otherVector.x,this.y-otherVector.y,this.z-otherVector.z);};Vector3.prototype.subtractToRef=function(otherVector,result){result.x=this.x-otherVector.x;result.y=this.y-otherVector.y;result.z=this.z-otherVector.z;};Vector3.prototype.subtractFromFloats=function(x,y,z){return new Vector3(this.x-x,this.y-y,this.z-z);};Vector3.prototype.subtractFromFloatsToRef=function(x,y,z,result){result.x=this.x-x;result.y=this.y-y;result.z=this.z-z;};Vector3.prototype.negate=function(){return new Vector3(-this.x,-this.y,-this.z);};Vector3.prototype.scaleInPlace=function(scale){this.x*=scale;this.y*=scale;this.z*=scale;};Vector3.prototype.scale=function(scale){return new Vector3(this.x*scale,this.y*scale,this.z*scale);};Vector3.prototype.scaleToRef=function(scale,result){result.x=this.x*scale;result.y=this.y*scale;result.z=this.z*scale;};Vector3.prototype.equals=function(otherVector){return otherVector&&this.x===otherVector.x&&this.y===otherVector.y&&this.z===otherVector.z;};Vector3.prototype.equalsWithEpsilon=function(otherVector){return Math.abs(this.x-otherVector.x)this.x)this.x=other.x;if(other.y>this.y)this.y=other.y;if(other.z>this.z)this.z=other.z;};Vector3.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);};Vector3.prototype.lengthSquared=function(){return(this.x*this.x+this.y*this.y+this.z*this.z);};Vector3.prototype.normalize=function(){var len=this.length();if(len===0)return;var num=1.0/len;this.x*=num;this.y*=num;this.z*=num;};Vector3.prototype.clone=function(){return new Vector3(this.x,this.y,this.z);};Vector3.prototype.copyFrom=function(source){this.x=source.x;this.y=source.y;this.z=source.z;};Vector3.prototype.copyFromFloats=function(x,y,z){this.x=x;this.y=y;this.z=z;};Vector3.FromArray=function(array,offset){if(!offset){offset=0;}return new Vector3(array[offset],array[offset+1],array[offset+2]);};Vector3.FromArrayToRef=function(array,offset,result){result.x=array[offset];result.y=array[offset+1];result.z=array[offset+2];};Vector3.FromFloatArrayToRef=function(array,offset,result){result.x=array[offset];result.y=array[offset+1];result.z=array[offset+2];};Vector3.FromFloatsToRef=function(x,y,z,result){result.x=x;result.y=y;result.z=z;};Vector3.Zero=function(){return new Vector3(0,0,0);};Vector3.Up=function(){return new Vector3(0,1.0,0);};Vector3.TransformCoordinates=function(vector,transformation){var result=Vector3.Zero();Vector3.TransformCoordinatesToRef(vector,transformation,result);return result;};Vector3.TransformCoordinatesToRef=function(vector,transformation,result){var x=(vector.x*transformation.m[0])+(vector.y*transformation.m[4])+(vector.z*transformation.m[8])+transformation.m[12];var y=(vector.x*transformation.m[1])+(vector.y*transformation.m[5])+(vector.z*transformation.m[9])+transformation.m[13];var z=(vector.x*transformation.m[2])+(vector.y*transformation.m[6])+(vector.z*transformation.m[10])+transformation.m[14];var w=(vector.x*transformation.m[3])+(vector.y*transformation.m[7])+(vector.z*transformation.m[11])+transformation.m[15];result.x=x/w;result.y=y/w;result.z=z/w;};Vector3.TransformCoordinatesFromFloatsToRef=function(x,y,z,transformation,result){var rx=(x*transformation.m[0])+(y*transformation.m[4])+(z*transformation.m[8])+transformation.m[12];var ry=(x*transformation.m[1])+(y*transformation.m[5])+(z*transformation.m[9])+transformation.m[13];var rz=(x*transformation.m[2])+(y*transformation.m[6])+(z*transformation.m[10])+transformation.m[14];var rw=(x*transformation.m[3])+(y*transformation.m[7])+(z*transformation.m[11])+transformation.m[15];result.x=rx/rw;result.y=ry/rw;result.z=rz/rw;};Vector3.TransformNormal=function(vector,transformation){var result=Vector3.Zero();Vector3.TransformNormalToRef(vector,transformation,result);return result;};Vector3.TransformNormalToRef=function(vector,transformation,result){result.x=(vector.x*transformation.m[0])+(vector.y*transformation.m[4])+(vector.z*transformation.m[8]);result.y=(vector.x*transformation.m[1])+(vector.y*transformation.m[5])+(vector.z*transformation.m[9]);result.z=(vector.x*transformation.m[2])+(vector.y*transformation.m[6])+(vector.z*transformation.m[10]);};Vector3.TransformNormalFromFloatsToRef=function(x,y,z,transformation,result){result.x=(x*transformation.m[0])+(y*transformation.m[4])+(z*transformation.m[8]);result.y=(x*transformation.m[1])+(y*transformation.m[5])+(z*transformation.m[9]);result.z=(x*transformation.m[2])+(y*transformation.m[6])+(z*transformation.m[10]);};Vector3.CatmullRom=function(value1,value2,value3,value4,amount){var squared=amount*amount;var cubed=amount*squared;var x=0.5*((((2.0*value2.x)+((-value1.x+value3.x)*amount))+(((((2.0*value1.x)-(5.0*value2.x))+(4.0*value3.x))-value4.x)*squared))+((((-value1.x+(3.0*value2.x))-(3.0*value3.x))+value4.x)*cubed));var y=0.5*((((2.0*value2.y)+((-value1.y+value3.y)*amount))+(((((2.0*value1.y)-(5.0*value2.y))+(4.0*value3.y))-value4.y)*squared))+((((-value1.y+(3.0*value2.y))-(3.0*value3.y))+value4.y)*cubed));var z=0.5*((((2.0*value2.z)+((-value1.z+value3.z)*amount))+(((((2.0*value1.z)-(5.0*value2.z))+(4.0*value3.z))-value4.z)*squared))+((((-value1.z+(3.0*value2.z))-(3.0*value3.z))+value4.z)*cubed));return new Vector3(x,y,z);};Vector3.Clamp=function(value,min,max){var x=value.x;x=(x>max.x)?max.x:x;x=(xmax.y)?max.y:y;y=(ymax.z)?max.z:z;z=(z0.499){yaw=2.0*Math.atan2(qx,qw);roll=0;}else if(gimbaLockTest<-0.499){yaw=-2.0*Math.atan2(qx,qw);roll=0;}return new Vector3(pitch,yaw,roll);};Quaternion.prototype.toRotationMatrix=function(result){var xx=this.x*this.x;var yy=this.y*this.y;var zz=this.z*this.z;var xy=this.x*this.y;var zw=this.z*this.w;var zx=this.z*this.x;var yw=this.y*this.w;var yz=this.y*this.z;var xw=this.x*this.w;result.m[0]=1.0-(2.0*(yy+zz));result.m[1]=2.0*(xy+zw);result.m[2]=2.0*(zx-yw);result.m[3]=0;result.m[4]=2.0*(xy-zw);result.m[5]=1.0-(2.0*(zz+xx));result.m[6]=2.0*(yz+xw);result.m[7]=0;result.m[8]=2.0*(zx+yw);result.m[9]=2.0*(yz-xw);result.m[10]=1.0-(2.0*(yy+xx));result.m[11]=0;result.m[12]=0;result.m[13]=0;result.m[14]=0;result.m[15]=1.0;};Quaternion.prototype.fromRotationMatrix=function(matrix){var data=matrix.m;var m11=data[0],m12=data[4],m13=data[8];var m21=data[1],m22=data[5],m23=data[9];var m31=data[2],m32=data[6],m33=data[10];var trace=m11+m22+m33;var s;if(trace>0){s=0.5/Math.sqrt(trace+1.0);this.w=0.25/s;this.x=(m32-m23)*s;this.y=(m13-m31)*s;this.z=(m21-m12)*s;return;}if(m11>m22&&m11>m33){s=2.0*Math.sqrt(1.0+m11-m22-m33);this.w=(m32-m23)/s;this.x=0.25*s;this.y=(m12+m21)/s;this.z=(m13+m31)/s;return;}if(m22>m33){s=2.0*Math.sqrt(1.0+m22-m11-m33);this.w=(m13-m31)/s;this.x=(m12+m21)/s;this.y=0.25*s;this.z=(m23+m32)/s;return;}s=2.0*Math.sqrt(1.0+m33-m11-m22);this.w=(m21-m12)/s;this.x=(m13+m31)/s;this.y=(m23+m32)/s;this.z=0.25*s;};Quaternion.RotationAxis=function(axis,angle){var result=new Quaternion();var sin=Math.sin(angle/2);result.w=Math.cos(angle/2);result.x=axis.x*sin;result.y=axis.y*sin;result.z=axis.z*sin;return result;};Quaternion.FromArray=function(array,offset){if(!offset){offset=0;}return new Quaternion(array[offset],array[offset+1],array[offset+2],array[offset+3]);};Quaternion.RotationYawPitchRoll=function(yaw,pitch,roll){var result=new Quaternion();Quaternion.RotationYawPitchRollToRef(yaw,pitch,roll,result);return result;};Quaternion.RotationYawPitchRollToRef=function(yaw,pitch,roll,result){var halfRoll=roll*0.5;var halfPitch=pitch*0.5;var halfYaw=yaw*0.5;var sinRoll=Math.sin(halfRoll);var cosRoll=Math.cos(halfRoll);var sinPitch=Math.sin(halfPitch);var cosPitch=Math.cos(halfPitch);var sinYaw=Math.sin(halfYaw);var cosYaw=Math.cos(halfYaw);result.x=(cosYaw*sinPitch*cosRoll)+(sinYaw*cosPitch*sinRoll);result.y=(sinYaw*cosPitch*cosRoll)-(cosYaw*sinPitch*sinRoll);result.z=(cosYaw*cosPitch*sinRoll)-(sinYaw*sinPitch*cosRoll);result.w=(cosYaw*cosPitch*cosRoll)+(sinYaw*sinPitch*sinRoll);};Quaternion.Slerp=function(left,right,amount){var num2;var num3;var num=amount;var num4=(((left.x*right.x)+(left.y*right.y))+(left.z*right.z))+(left.w*right.w);var flag=false;if(num4<0){flag=true;num4=-num4;}if(num4>0.999999){num3=1-num;num2=flag?-num:num;}else{var num5=Math.acos(num4);var num6=(1.0/Math.sin(num5));num3=(Math.sin((1.0-num)*num5))*num6;num2=flag?((-Math.sin(num*num5))*num6):((Math.sin(num*num5))*num6);}return new Quaternion((num3*left.x)+(num2*right.x),(num3*left.y)+(num2*right.y),(num3*left.z)+(num2*right.z),(num3*left.w)+(num2*right.w));};return Quaternion;})();BABYLON.Quaternion=Quaternion;var Matrix=(function(){function Matrix(){this.m=new Float32Array(16);}Matrix.prototype.isIdentity=function(){if(this.m[0]!=1.0||this.m[5]!=1.0||this.m[10]!=1.0||this.m[15]!=1.0)return false;if(this.m[1]!=0.0||this.m[2]!=0.0||this.m[3]!=0.0||this.m[4]!=0.0||this.m[6]!=0.0||this.m[7]!=0.0||this.m[8]!=0.0||this.m[9]!=0.0||this.m[11]!=0.0||this.m[12]!=0.0||this.m[13]!=0.0||this.m[14]!=0.0)return false;return true;};Matrix.prototype.determinant=function(){var temp1=(this.m[10]*this.m[15])-(this.m[11]*this.m[14]);var temp2=(this.m[9]*this.m[15])-(this.m[11]*this.m[13]);var temp3=(this.m[9]*this.m[14])-(this.m[10]*this.m[13]);var temp4=(this.m[8]*this.m[15])-(this.m[11]*this.m[12]);var temp5=(this.m[8]*this.m[14])-(this.m[10]*this.m[12]);var temp6=(this.m[8]*this.m[13])-(this.m[9]*this.m[12]);return((((this.m[0]*(((this.m[5]*temp1)-(this.m[6]*temp2))+(this.m[7]*temp3)))-(this.m[1]*(((this.m[4]*temp1)-(this.m[6]*temp4))+(this.m[7]*temp5))))+(this.m[2]*(((this.m[4]*temp2)-(this.m[5]*temp4))+(this.m[7]*temp6))))-(this.m[3]*(((this.m[4]*temp3)-(this.m[5]*temp5))+(this.m[6]*temp6))));};Matrix.prototype.toArray=function(){return this.m;};Matrix.prototype.asArray=function(){return this.toArray();};Matrix.prototype.invert=function(){this.invertToRef(this);};Matrix.prototype.invertToRef=function(other){var l1=this.m[0];var l2=this.m[1];var l3=this.m[2];var l4=this.m[3];var l5=this.m[4];var l6=this.m[5];var l7=this.m[6];var l8=this.m[7];var l9=this.m[8];var l10=this.m[9];var l11=this.m[10];var l12=this.m[11];var l13=this.m[12];var l14=this.m[13];var l15=this.m[14];var l16=this.m[15];var l17=(l11*l16)-(l12*l15);var l18=(l10*l16)-(l12*l14);var l19=(l10*l15)-(l11*l14);var l20=(l9*l16)-(l12*l13);var l21=(l9*l15)-(l11*l13);var l22=(l9*l14)-(l10*l13);var l23=((l6*l17)-(l7*l18))+(l8*l19);var l24=-(((l5*l17)-(l7*l20))+(l8*l21));var l25=((l5*l18)-(l6*l20))+(l8*l22);var l26=-(((l5*l19)-(l6*l21))+(l7*l22));var l27=1.0/((((l1*l23)+(l2*l24))+(l3*l25))+(l4*l26));var l28=(l7*l16)-(l8*l15);var l29=(l6*l16)-(l8*l14);var l30=(l6*l15)-(l7*l14);var l31=(l5*l16)-(l8*l13);var l32=(l5*l15)-(l7*l13);var l33=(l5*l14)-(l6*l13);var l34=(l7*l12)-(l8*l11);var l35=(l6*l12)-(l8*l10);var l36=(l6*l11)-(l7*l10);var l37=(l5*l12)-(l8*l9);var l38=(l5*l11)-(l7*l9);var l39=(l5*l10)-(l6*l9);other.m[0]=l23*l27;other.m[4]=l24*l27;other.m[8]=l25*l27;other.m[12]=l26*l27;other.m[1]=-(((l2*l17)-(l3*l18))+(l4*l19))*l27;other.m[5]=(((l1*l17)-(l3*l20))+(l4*l21))*l27;other.m[9]=-(((l1*l18)-(l2*l20))+(l4*l22))*l27;other.m[13]=(((l1*l19)-(l2*l21))+(l3*l22))*l27;other.m[2]=(((l2*l28)-(l3*l29))+(l4*l30))*l27;other.m[6]=-(((l1*l28)-(l3*l31))+(l4*l32))*l27;other.m[10]=(((l1*l29)-(l2*l31))+(l4*l33))*l27;other.m[14]=-(((l1*l30)-(l2*l32))+(l3*l33))*l27;other.m[3]=-(((l2*l34)-(l3*l35))+(l4*l36))*l27;other.m[7]=(((l1*l34)-(l3*l37))+(l4*l38))*l27;other.m[11]=-(((l1*l35)-(l2*l37))+(l4*l39))*l27;other.m[15]=(((l1*l36)-(l2*l38))+(l3*l39))*l27;};Matrix.prototype.setTranslation=function(vector3){this.m[12]=vector3.x;this.m[13]=vector3.y;this.m[14]=vector3.z;};Matrix.prototype.multiply=function(other){var result=new Matrix();this.multiplyToRef(other,result);return result;};Matrix.prototype.copyFrom=function(other){for(var index=0;index<16;index++){this.m[index]=other.m[index];}};Matrix.prototype.copyToArray=function(array,offset){if(typeof offset==="undefined"){offset=0;}for(var index=0;index<16;index++){array[offset+index]=this.m[index];}};Matrix.prototype.multiplyToRef=function(other,result){this.multiplyToArray(other,result.m,0);};Matrix.prototype.multiplyToArray=function(other,result,offset){var tm0=this.m[0];var tm1=this.m[1];var tm2=this.m[2];var tm3=this.m[3];var tm4=this.m[4];var tm5=this.m[5];var tm6=this.m[6];var tm7=this.m[7];var tm8=this.m[8];var tm9=this.m[9];var tm10=this.m[10];var tm11=this.m[11];var tm12=this.m[12];var tm13=this.m[13];var tm14=this.m[14];var tm15=this.m[15];var om0=other.m[0];var om1=other.m[1];var om2=other.m[2];var om3=other.m[3];var om4=other.m[4];var om5=other.m[5];var om6=other.m[6];var om7=other.m[7];var om8=other.m[8];var om9=other.m[9];var om10=other.m[10];var om11=other.m[11];var om12=other.m[12];var om13=other.m[13];var om14=other.m[14];var om15=other.m[15];result[offset]=tm0*om0+tm1*om4+tm2*om8+tm3*om12;result[offset+1]=tm0*om1+tm1*om5+tm2*om9+tm3*om13;result[offset+2]=tm0*om2+tm1*om6+tm2*om10+tm3*om14;result[offset+3]=tm0*om3+tm1*om7+tm2*om11+tm3*om15;result[offset+4]=tm4*om0+tm5*om4+tm6*om8+tm7*om12;result[offset+5]=tm4*om1+tm5*om5+tm6*om9+tm7*om13;result[offset+6]=tm4*om2+tm5*om6+tm6*om10+tm7*om14;result[offset+7]=tm4*om3+tm5*om7+tm6*om11+tm7*om15;result[offset+8]=tm8*om0+tm9*om4+tm10*om8+tm11*om12;result[offset+9]=tm8*om1+tm9*om5+tm10*om9+tm11*om13;result[offset+10]=tm8*om2+tm9*om6+tm10*om10+tm11*om14;result[offset+11]=tm8*om3+tm9*om7+tm10*om11+tm11*om15;result[offset+12]=tm12*om0+tm13*om4+tm14*om8+tm15*om12;result[offset+13]=tm12*om1+tm13*om5+tm14*om9+tm15*om13;result[offset+14]=tm12*om2+tm13*om6+tm14*om10+tm15*om14;result[offset+15]=tm12*om3+tm13*om7+tm14*om11+tm15*om15;};Matrix.prototype.equals=function(value){return value&&(this.m[0]===value.m[0]&&this.m[1]===value.m[1]&&this.m[2]===value.m[2]&&this.m[3]===value.m[3]&&this.m[4]===value.m[4]&&this.m[5]===value.m[5]&&this.m[6]===value.m[6]&&this.m[7]===value.m[7]&&this.m[8]===value.m[8]&&this.m[9]===value.m[9]&&this.m[10]===value.m[10]&&this.m[11]===value.m[11]&&this.m[12]===value.m[12]&&this.m[13]===value.m[13]&&this.m[14]===value.m[14]&&this.m[15]===value.m[15]);};Matrix.prototype.clone=function(){return Matrix.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15]);};Matrix.FromArray=function(array,offset){var result=new Matrix();if(!offset){offset=0;}Matrix.FromArrayToRef(array,offset,result);return result;};Matrix.FromArrayToRef=function(array,offset,result){for(var index=0;index<16;index++){result.m[index]=array[index+offset];}};Matrix.FromValuesToRef=function(initialM11,initialM12,initialM13,initialM14,initialM21,initialM22,initialM23,initialM24,initialM31,initialM32,initialM33,initialM34,initialM41,initialM42,initialM43,initialM44,result){result.m[0]=initialM11;result.m[1]=initialM12;result.m[2]=initialM13;result.m[3]=initialM14;result.m[4]=initialM21;result.m[5]=initialM22;result.m[6]=initialM23;result.m[7]=initialM24;result.m[8]=initialM31;result.m[9]=initialM32;result.m[10]=initialM33;result.m[11]=initialM34;result.m[12]=initialM41;result.m[13]=initialM42;result.m[14]=initialM43;result.m[15]=initialM44;};Matrix.FromValues=function(initialM11,initialM12,initialM13,initialM14,initialM21,initialM22,initialM23,initialM24,initialM31,initialM32,initialM33,initialM34,initialM41,initialM42,initialM43,initialM44){var result=new Matrix();result.m[0]=initialM11;result.m[1]=initialM12;result.m[2]=initialM13;result.m[3]=initialM14;result.m[4]=initialM21;result.m[5]=initialM22;result.m[6]=initialM23;result.m[7]=initialM24;result.m[8]=initialM31;result.m[9]=initialM32;result.m[10]=initialM33;result.m[11]=initialM34;result.m[12]=initialM41;result.m[13]=initialM42;result.m[14]=initialM43;result.m[15]=initialM44;return result;};Matrix.Identity=function(){return Matrix.FromValues(1.0,0,0,0,0,1.0,0,0,0,0,1.0,0,0,0,0,1.0);};Matrix.IdentityToRef=function(result){Matrix.FromValuesToRef(1.0,0,0,0,0,1.0,0,0,0,0,1.0,0,0,0,0,1.0,result);};Matrix.Zero=function(){return Matrix.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);};Matrix.RotationX=function(angle){var result=new Matrix();Matrix.RotationXToRef(angle,result);return result;};Matrix.RotationXToRef=function(angle,result){var s=Math.sin(angle);var c=Math.cos(angle);result.m[0]=1.0;result.m[15]=1.0;result.m[5]=c;result.m[10]=c;result.m[9]=-s;result.m[6]=s;result.m[1]=0;result.m[2]=0;result.m[3]=0;result.m[4]=0;result.m[7]=0;result.m[8]=0;result.m[11]=0;result.m[12]=0;result.m[13]=0;result.m[14]=0;};Matrix.RotationY=function(angle){var result=new Matrix();Matrix.RotationYToRef(angle,result);return result;};Matrix.RotationYToRef=function(angle,result){var s=Math.sin(angle);var c=Math.cos(angle);result.m[5]=1.0;result.m[15]=1.0;result.m[0]=c;result.m[2]=-s;result.m[8]=s;result.m[10]=c;result.m[1]=0;result.m[3]=0;result.m[4]=0;result.m[6]=0;result.m[7]=0;result.m[9]=0;result.m[11]=0;result.m[12]=0;result.m[13]=0;result.m[14]=0;};Matrix.RotationZ=function(angle){var result=new Matrix();Matrix.RotationZToRef(angle,result);return result;};Matrix.RotationZToRef=function(angle,result){var s=Math.sin(angle);var c=Math.cos(angle);result.m[10]=1.0;result.m[15]=1.0;result.m[0]=c;result.m[1]=s;result.m[4]=-s;result.m[5]=c;result.m[2]=0;result.m[3]=0;result.m[6]=0;result.m[7]=0;result.m[8]=0;result.m[9]=0;result.m[11]=0;result.m[12]=0;result.m[13]=0;result.m[14]=0;};Matrix.RotationAxis=function(axis,angle){var s=Math.sin(-angle);var c=Math.cos(-angle);var c1=1-c;axis.normalize();var result=Matrix.Zero();result.m[0]=(axis.x*axis.x)*c1+c;result.m[1]=(axis.x*axis.y)*c1-(axis.z*s);result.m[2]=(axis.x*axis.z)*c1+(axis.y*s);result.m[3]=0.0;result.m[4]=(axis.y*axis.x)*c1+(axis.z*s);result.m[5]=(axis.y*axis.y)*c1+c;result.m[6]=(axis.y*axis.z)*c1-(axis.x*s);result.m[7]=0.0;result.m[8]=(axis.z*axis.x)*c1-(axis.y*s);result.m[9]=(axis.z*axis.y)*c1+(axis.x*s);result.m[10]=(axis.z*axis.z)*c1+c;result.m[11]=0.0;result.m[15]=1.0;return result;};Matrix.RotationYawPitchRoll=function(yaw,pitch,roll){var result=new Matrix();Matrix.RotationYawPitchRollToRef(yaw,pitch,roll,result);return result;};Matrix.RotationYawPitchRollToRef=function(yaw,pitch,roll,result){Quaternion.RotationYawPitchRollToRef(yaw,pitch,roll,this._tempQuaternion);this._tempQuaternion.toRotationMatrix(result);};Matrix.Scaling=function(x,y,z){var result=Matrix.Zero();Matrix.ScalingToRef(x,y,z,result);return result;};Matrix.ScalingToRef=function(x,y,z,result){result.m[0]=x;result.m[1]=0;result.m[2]=0;result.m[3]=0;result.m[4]=0;result.m[5]=y;result.m[6]=0;result.m[7]=0;result.m[8]=0;result.m[9]=0;result.m[10]=z;result.m[11]=0;result.m[12]=0;result.m[13]=0;result.m[14]=0;result.m[15]=1.0;};Matrix.Translation=function(x,y,z){var result=Matrix.Identity();Matrix.TranslationToRef(x,y,z,result);return result;};Matrix.TranslationToRef=function(x,y,z,result){Matrix.FromValuesToRef(1.0,0,0,0,0,1.0,0,0,0,0,1.0,0,x,y,z,1.0,result);};Matrix.LookAtLH=function(eye,target,up){var result=Matrix.Zero();Matrix.LookAtLHToRef(eye,target,up,result);return result;};Matrix.LookAtLHToRef=function(eye,target,up,result){target.subtractToRef(eye,this._zAxis);this._zAxis.normalize();Vector3.CrossToRef(up,this._zAxis,this._xAxis);this._xAxis.normalize();Vector3.CrossToRef(this._zAxis,this._xAxis,this._yAxis);this._yAxis.normalize();var ex=-Vector3.Dot(this._xAxis,eye);var ey=-Vector3.Dot(this._yAxis,eye);var ez=-Vector3.Dot(this._zAxis,eye);return Matrix.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,ex,ey,ez,1,result);};Matrix.OrthoLH=function(width,height,znear,zfar){var hw=2.0/width;var hh=2.0/height;var id=1.0/(zfar-znear);var nid=znear/(znear-zfar);return Matrix.FromValues(hw,0,0,0,0,hh,0,0,0,0,id,0,0,0,nid,1);};Matrix.OrthoOffCenterLH=function(left,right,bottom,top,znear,zfar){var matrix=Matrix.Zero();Matrix.OrthoOffCenterLHToRef(left,right,bottom,top,znear,zfar,matrix);return matrix;};Matrix.OrthoOffCenterLHToRef=function(left,right,bottom,top,znear,zfar,result){result.m[0]=2.0/(right-left);result.m[1]=result.m[2]=result.m[3]=0;result.m[5]=2.0/(top-bottom);result.m[4]=result.m[6]=result.m[7]=0;result.m[10]=-1.0/(znear-zfar);result.m[8]=result.m[9]=result.m[11]=0;result.m[12]=(left+right)/(left-right);result.m[13]=(top+bottom)/(bottom-top);result.m[14]=znear/(znear-zfar);result.m[15]=1.0;};Matrix.PerspectiveLH=function(width,height,znear,zfar){var matrix=Matrix.Zero();matrix.m[0]=(2.0*znear)/width;matrix.m[1]=matrix.m[2]=matrix.m[3]=0.0;matrix.m[5]=(2.0*znear)/height;matrix.m[4]=matrix.m[6]=matrix.m[7]=0.0;matrix.m[10]=-zfar/(znear-zfar);matrix.m[8]=matrix.m[9]=0.0;matrix.m[11]=1.0;matrix.m[12]=matrix.m[13]=matrix.m[15]=0.0;matrix.m[14]=(znear*zfar)/(znear-zfar);return matrix;};Matrix.PerspectiveFovLH=function(fov,aspect,znear,zfar){var matrix=Matrix.Zero();Matrix.PerspectiveFovLHToRef(fov,aspect,znear,zfar,matrix);return matrix;};Matrix.PerspectiveFovLHToRef=function(fov,aspect,znear,zfar,result){var tan=1.0/(Math.tan(fov*0.5));result.m[0]=tan/aspect;result.m[1]=result.m[2]=result.m[3]=0.0;result.m[5]=tan;result.m[4]=result.m[6]=result.m[7]=0.0;result.m[8]=result.m[9]=0.0;result.m[10]=-zfar/(znear-zfar);result.m[11]=1.0;result.m[12]=result.m[13]=result.m[15]=0.0;result.m[14]=(znear*zfar)/(znear-zfar);};Matrix.GetFinalMatrix=function(viewport,world,view,projection,zmin,zmax){var cw=viewport.width;var ch=viewport.height;var cx=viewport.x;var cy=viewport.y;var viewportMatrix=Matrix.FromValues(cw/2.0,0,0,0,0,-ch/2.0,0,0,0,0,zmax-zmin,0,cx+cw/2.0,ch/2.0+cy,zmin,1);return world.multiply(view).multiply(projection).multiply(viewportMatrix);};Matrix.Transpose=function(matrix){var result=new Matrix();result.m[0]=matrix.m[0];result.m[1]=matrix.m[4];result.m[2]=matrix.m[8];result.m[3]=matrix.m[12];result.m[4]=matrix.m[1];result.m[5]=matrix.m[5];result.m[6]=matrix.m[9];result.m[7]=matrix.m[13];result.m[8]=matrix.m[2];result.m[9]=matrix.m[6];result.m[10]=matrix.m[10];result.m[11]=matrix.m[14];result.m[12]=matrix.m[3];result.m[13]=matrix.m[7];result.m[14]=matrix.m[11];result.m[15]=matrix.m[15];return result;};Matrix.Reflection=function(plane){var matrix=new Matrix();Matrix.ReflectionToRef(plane,matrix);return matrix;};Matrix.ReflectionToRef=function(plane,result){plane.normalize();var x=plane.normal.x;var y=plane.normal.y;var z=plane.normal.z;var temp=-2*x;var temp2=-2*y;var temp3=-2*z;result.m[0]=(temp*x)+1;result.m[1]=temp2*x;result.m[2]=temp3*x;result.m[3]=0.0;result.m[4]=temp*y;result.m[5]=(temp2*y)+1;result.m[6]=temp3*y;result.m[7]=0.0;result.m[8]=temp*z;result.m[9]=temp2*z;result.m[10]=(temp3*z)+1;result.m[11]=0.0;result.m[12]=temp*plane.d;result.m[13]=temp2*plane.d;result.m[14]=temp3*plane.d;result.m[15]=1.0;};Matrix._tempQuaternion=new Quaternion();Matrix._xAxis=Vector3.Zero();Matrix._yAxis=Vector3.Zero();Matrix._zAxis=Vector3.Zero();return Matrix;})();BABYLON.Matrix=Matrix;var Plane=(function(){function Plane(a,b,c,d){this.normal=new Vector3(a,b,c);this.d=d;}Plane.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d];};Plane.prototype.clone=function(){return new Plane(this.normal.x,this.normal.y,this.normal.z,this.d);};Plane.prototype.normalize=function(){var norm=(Math.sqrt((this.normal.x*this.normal.x)+(this.normal.y*this.normal.y)+(this.normal.z*this.normal.z)));var magnitude=0;if(norm!=0){magnitude=1.0/norm;}this.normal.x*=magnitude;this.normal.y*=magnitude;this.normal.z*=magnitude;this.d*=magnitude;};Plane.prototype.transform=function(transformation){var transposedMatrix=BABYLON.Matrix.Transpose(transformation);var x=this.normal.x;var y=this.normal.y;var z=this.normal.z;var d=this.d;var normalX=(((x*transposedMatrix.m[0])+(y*transposedMatrix.m[1]))+(z*transposedMatrix.m[2]))+(d*transposedMatrix.m[3]);var normalY=(((x*transposedMatrix.m[4])+(y*transposedMatrix.m[5]))+(z*transposedMatrix.m[6]))+(d*transposedMatrix.m[7]);var normalZ=(((x*transposedMatrix.m[8])+(y*transposedMatrix.m[9]))+(z*transposedMatrix.m[10]))+(d*transposedMatrix.m[11]);var finalD=(((x*transposedMatrix.m[12])+(y*transposedMatrix.m[13]))+(z*transposedMatrix.m[14]))+(d*transposedMatrix.m[15]);return new BABYLON.Plane(normalX,normalY,normalZ,finalD);};Plane.prototype.dotCoordinate=function(point){return((((this.normal.x*point.x)+(this.normal.y*point.y))+(this.normal.z*point.z))+this.d);};Plane.prototype.copyFromPoints=function(point1,point2,point3){var x1=point2.x-point1.x;var y1=point2.y-point1.y;var z1=point2.z-point1.z;var x2=point3.x-point1.x;var y2=point3.y-point1.y;var z2=point3.z-point1.z;var yz=(y1*z2)-(z1*y2);var xz=(z1*x2)-(x1*z2);var xy=(x1*y2)-(y1*x2);var pyth=(Math.sqrt((yz*yz)+(xz*xz)+(xy*xy)));var invPyth;if(pyth!=0){invPyth=1.0/pyth;}else{invPyth=0;}this.normal.x=yz*invPyth;this.normal.y=xz*invPyth;this.normal.z=xy*invPyth;this.d=-((this.normal.x*point1.x)+(this.normal.y*point1.y)+(this.normal.z*point1.z));};Plane.prototype.isFrontFacingTo=function(direction,epsilon){var dot=Vector3.Dot(this.normal,direction);return(dot<=epsilon);};Plane.prototype.signedDistanceTo=function(point){return Vector3.Dot(point,this.normal)+this.d;};Plane.FromArray=function(array){return new BABYLON.Plane(array[0],array[1],array[2],array[3]);};Plane.FromPoints=function(point1,point2,point3){var result=new BABYLON.Plane(0,0,0,0);result.copyFromPoints(point1,point2,point3);return result;};Plane.FromPositionAndNormal=function(origin,normal){var result=new BABYLON.Plane(0,0,0,0);normal.normalize();result.normal=normal;result.d=-(normal.x*origin.x+normal.y*origin.y+normal.z*origin.z);return result;};Plane.SignedDistanceToPlaneFromPositionAndNormal=function(origin,normal,point){var d=-(normal.x*origin.x+normal.y*origin.y+normal.z*origin.z);return Vector3.Dot(point,normal)+d;};return Plane;})();BABYLON.Plane=Plane;var Viewport=(function(){function Viewport(x,y,width,height){this.x=x;this.y=y;this.width=width;this.height=height;}Viewport.prototype.toGlobal=function(engine){var width=engine.getRenderWidth();var height=engine.getRenderHeight();return new Viewport(this.x*width,this.y*height,this.width*width,this.height*height);};return Viewport;})();BABYLON.Viewport=Viewport;var Frustum=(function(){function Frustum(){}Frustum.GetPlanes=function(transform){var frustumPlanes=[];for(var index=0;index<6;index++){frustumPlanes.push(new Plane(0,0,0,0));}Frustum.GetPlanesToRef(transform,frustumPlanes);return frustumPlanes;};Frustum.GetPlanesToRef=function(transform,frustumPlanes){frustumPlanes[0].normal.x=transform.m[3]+transform.m[2];frustumPlanes[0].normal.y=transform.m[7]+transform.m[6];frustumPlanes[0].normal.z=transform.m[10]+transform.m[10];frustumPlanes[0].d=transform.m[15]+transform.m[14];frustumPlanes[0].normalize();frustumPlanes[1].normal.x=transform.m[3]-transform.m[2];frustumPlanes[1].normal.y=transform.m[7]-transform.m[6];frustumPlanes[1].normal.z=transform.m[11]-transform.m[10];frustumPlanes[1].d=transform.m[15]-transform.m[14];frustumPlanes[1].normalize();frustumPlanes[2].normal.x=transform.m[3]+transform.m[0];frustumPlanes[2].normal.y=transform.m[7]+transform.m[4];frustumPlanes[2].normal.z=transform.m[11]+transform.m[8];frustumPlanes[2].d=transform.m[15]+transform.m[12];frustumPlanes[2].normalize();frustumPlanes[3].normal.x=transform.m[3]-transform.m[0];frustumPlanes[3].normal.y=transform.m[7]-transform.m[4];frustumPlanes[3].normal.z=transform.m[11]-transform.m[8];frustumPlanes[3].d=transform.m[15]-transform.m[12];frustumPlanes[3].normalize();frustumPlanes[4].normal.x=transform.m[3]-transform.m[1];frustumPlanes[4].normal.y=transform.m[7]-transform.m[5];frustumPlanes[4].normal.z=transform.m[11]-transform.m[9];frustumPlanes[4].d=transform.m[15]-transform.m[13];frustumPlanes[4].normalize();frustumPlanes[5].normal.x=transform.m[3]+transform.m[1];frustumPlanes[5].normal.y=transform.m[7]+transform.m[5];frustumPlanes[5].normal.z=transform.m[11]+transform.m[9];frustumPlanes[5].d=transform.m[15]+transform.m[13];frustumPlanes[5].normalize();};return Frustum;})();BABYLON.Frustum=Frustum;var Ray=(function(){function Ray(origin,direction){this.origin=origin;this.direction=direction;}Ray.prototype.intersectsBoxMinMax=function(minimum,maximum){var d=0.0;var maxValue=Number.MAX_VALUE;if(Math.abs(this.direction.x)<0.0000001){if(this.origin.xmaximum.x){return false;}}else{var inv=1.0/this.direction.x;var min=(minimum.x-this.origin.x)*inv;var max=(maximum.x-this.origin.x)*inv;if(min>max){var temp=min;min=max;max=temp;}d=Math.max(min,d);maxValue=Math.min(max,maxValue);if(d>maxValue){return false;}}if(Math.abs(this.direction.y)<0.0000001){if(this.origin.ymaximum.y){return false;}}else{inv=1.0/this.direction.y;min=(minimum.y-this.origin.y)*inv;max=(maximum.y-this.origin.y)*inv;if(min>max){temp=min;min=max;max=temp;}d=Math.max(min,d);maxValue=Math.min(max,maxValue);if(d>maxValue){return false;}}if(Math.abs(this.direction.z)<0.0000001){if(this.origin.zmaximum.z){return false;}}else{inv=1.0/this.direction.z;min=(minimum.z-this.origin.z)*inv;max=(maximum.z-this.origin.z)*inv;if(min>max){temp=min;min=max;max=temp;}d=Math.max(min,d);maxValue=Math.min(max,maxValue);if(d>maxValue){return false;}}return true;};Ray.prototype.intersectsBox=function(box){return this.intersectsBoxMinMax(box.minimum,box.maximum);};Ray.prototype.intersectsSphere=function(sphere){var x=sphere.center.x-this.origin.x;var y=sphere.center.y-this.origin.y;var z=sphere.center.z-this.origin.z;var pyth=(x*x)+(y*y)+(z*z);var rr=sphere.radius*sphere.radius;if(pyth<=rr){return true;}var dot=(x*this.direction.x)+(y*this.direction.y)+(z*this.direction.z);if(dot<0.0){return false;}var temp=pyth-(dot*dot);return temp<=rr;};Ray.prototype.intersectsTriangle=function(vertex0,vertex1,vertex2){if(!this._edge1){this._edge1=BABYLON.Vector3.Zero();this._edge2=BABYLON.Vector3.Zero();this._pvec=BABYLON.Vector3.Zero();this._tvec=BABYLON.Vector3.Zero();this._qvec=BABYLON.Vector3.Zero();}vertex1.subtractToRef(vertex0,this._edge1);vertex2.subtractToRef(vertex0,this._edge2);BABYLON.Vector3.CrossToRef(this.direction,this._edge2,this._pvec);var det=Vector3.Dot(this._edge1,this._pvec);if(det===0){return null;}var invdet=1/det;this.origin.subtractToRef(vertex0,this._tvec);var bu=Vector3.Dot(this._tvec,this._pvec)*invdet;if(bu<0||bu>1.0){return null;}Vector3.CrossToRef(this._tvec,this._edge1,this._qvec);var bv=Vector3.Dot(this.direction,this._qvec)*invdet;if(bv<0||bu+bv>1.0){return null;}return new BABYLON.IntersectionInfo(bu,bv,Vector3.Dot(this._edge2,this._qvec)*invdet);};Ray.CreateNew=function(x,y,viewportWidth,viewportHeight,world,view,projection){var start=BABYLON.Vector3.Unproject(new BABYLON.Vector3(x,y,0),viewportWidth,viewportHeight,world,view,projection);var end=BABYLON.Vector3.Unproject(new BABYLON.Vector3(x,y,1),viewportWidth,viewportHeight,world,view,projection);var direction=end.subtract(start);direction.normalize();return new Ray(start,direction);};Ray.Transform=function(ray,matrix){var newOrigin=BABYLON.Vector3.TransformCoordinates(ray.origin,matrix);var newDirection=BABYLON.Vector3.TransformNormal(ray.direction,matrix);return new Ray(newOrigin,newDirection);};return Ray;})();BABYLON.Ray=Ray;(function(Space){Space[Space["LOCAL"]=0]="LOCAL";Space[Space["WORLD"]=1]="WORLD";})(BABYLON.Space||(BABYLON.Space={}));var Space=BABYLON.Space;var Axis=(function(){function Axis(){}Axis.X=new BABYLON.Vector3(1,0,0);Axis.Y=new BABYLON.Vector3(0,1,0);Axis.Z=new BABYLON.Vector3(0,0,1);return Axis;})();BABYLON.Axis=Axis;;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var screenshotCanvas;var fpsRange=60;var previousFramesDuration=[];var fps=60;var deltaTime=0;var cloneValue=function(source,destinationObject){if(!source)return null;if(source instanceof BABYLON.Mesh){return null;}if(source instanceof BABYLON.SubMesh){return source.clone(destinationObject);}else if(source.clone){return source.clone();}return null;};var Tools=(function(){function Tools(){}Tools.GetFilename=function(path){var index=path.lastIndexOf("/");if(index<0)return path;return path.substring(index+1);};Tools.GetDOMTextContent=function(element){var result="";var child=element.firstChild;while(child){if(child.nodeType==3){result+=child.textContent;}child=child.nextSibling;}return result;};Tools.ToDegrees=function(angle){return angle*180/Math.PI;};Tools.ToRadians=function(angle){return angle*Math.PI/180;};Tools.ExtractMinAndMaxIndexed=function(positions,indices,indexStart,indexCount){var minimum=new BABYLON.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);var maximum=new BABYLON.Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(var index=indexStart;indexmax.x)max.x=v.x;if(v.y>max.y)max.y=v.y;if(v.z>max.z)max.z=v.z;};Tools.WithinEpsilon=function(a,b){var num=a-b;return-1.401298E-45<=num&&num<=1.401298E-45;};Tools.DeepCopy=function(source,destination,doNotCopyList,mustCopyList){for(var prop in source){if(prop[0]==="_"&&(!mustCopyList||mustCopyList.indexOf(prop)===-1)){continue;}if(doNotCopyList&&doNotCopyList.indexOf(prop)!==-1){continue;}var sourceValue=source[prop];var typeOfSourceValue=typeof sourceValue;if(typeOfSourceValue=="function"){continue;}if(typeOfSourceValue=="object"){if(sourceValue instanceof Array){destination[prop]=[];if(sourceValue.length>0){if(typeof sourceValue[0]=="object"){for(var index=0;index=2){deltaTime=previousFramesDuration[length-1]-previousFramesDuration[length-2];}if(length>=fpsRange){if(length>fpsRange){previousFramesDuration.splice(0,1);length=previousFramesDuration.length;}var sum=0;for(var id=0;id0){return true;}else if(dataType===1){return false;}}if(dataType&2){var tgaHeader=BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);if(tgaHeader.width&&tgaHeader.height&&tgaHeader.width>0&&tgaHeader.height>0){return true;}else if(dataType===2){return false;}}if(dataType&4){var ddsHeader=new Uint8Array(xhr.response,0,3);if(ddsHeader[0]==68&&ddsHeader[1]==68&&ddsHeader[2]==83){return true;}else{return false;}}}catch(e){}return false;};Object.defineProperty(Tools,"NoneLogLevel",{get:function(){return Tools._NoneLogLevel;},enumerable:true,configurable:true});Object.defineProperty(Tools,"MessageLogLevel",{get:function(){return Tools._MessageLogLevel;},enumerable:true,configurable:true});Object.defineProperty(Tools,"WarningLogLevel",{get:function(){return Tools._WarningLogLevel;},enumerable:true,configurable:true});Object.defineProperty(Tools,"ErrorLogLevel",{get:function(){return Tools._ErrorLogLevel;},enumerable:true,configurable:true});Object.defineProperty(Tools,"AllLogLevel",{get:function(){return Tools._MessageLogLevel|Tools._WarningLogLevel|Tools._ErrorLogLevel;},enumerable:true,configurable:true});Tools._FormatMessage=function(message){var padStr=function(i){return(i<10)?"0"+i:""+i;};var date=new Date();return"BJS - ["+padStr(date.getHours())+":"+padStr(date.getMinutes())+":"+padStr(date.getSeconds())+"]: "+message;};Tools._LogDisabled=function(message){};Tools._LogEnabled=function(message){console.log(Tools._FormatMessage(message));};Tools._WarnDisabled=function(message){};Tools._WarnEnabled=function(message){console.warn(Tools._FormatMessage(message));};Tools._ErrorDisabled=function(message){};Tools._ErrorEnabled=function(message){console.error(Tools._FormatMessage(message));};Object.defineProperty(Tools,"LogLevels",{set:function(level){if((level&Tools.MessageLogLevel)===Tools.MessageLogLevel){Tools.Log=Tools._LogEnabled;}else{Tools.Log=Tools._LogDisabled;}if((level&Tools.WarningLogLevel)===Tools.WarningLogLevel){Tools.Warn=Tools._WarnEnabled;}else{Tools.Warn=Tools._WarnDisabled;}if((level&Tools.ErrorLogLevel)===Tools.ErrorLogLevel){Tools.Error=Tools._ErrorEnabled;}else{Tools.Error=Tools._ErrorDisabled;}},enumerable:true,configurable:true});Tools.BaseUrl="";Tools._NoneLogLevel=0;Tools._MessageLogLevel=1;Tools._WarningLogLevel=2;Tools._ErrorLogLevel=4;Tools.Log=Tools._LogEnabled;Tools.Warn=Tools._WarnEnabled;Tools.Error=Tools._ErrorEnabled;return Tools;})();BABYLON.Tools=Tools;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var compileShader=function(gl,source,type,defines){var shader=gl.createShader(type==="vertex"?gl.VERTEX_SHADER:gl.FRAGMENT_SHADER);gl.shaderSource(shader,(defines?defines+"\n":"")+source);gl.compileShader(shader);if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS)){throw new Error(gl.getShaderInfoLog(shader));}return shader;};var getSamplingParameters=function(samplingMode,generateMipMaps,gl){var magFilter=gl.NEAREST;var minFilter=gl.NEAREST;if(samplingMode===BABYLON.Texture.BILINEAR_SAMPLINGMODE){magFilter=gl.LINEAR;if(generateMipMaps){minFilter=gl.LINEAR_MIPMAP_NEAREST;}else{minFilter=gl.LINEAR;}}else if(samplingMode===BABYLON.Texture.TRILINEAR_SAMPLINGMODE){magFilter=gl.LINEAR;if(generateMipMaps){minFilter=gl.LINEAR_MIPMAP_LINEAR;}else{minFilter=gl.LINEAR;}}else if(samplingMode===BABYLON.Texture.NEAREST_SAMPLINGMODE){magFilter=gl.NEAREST;if(generateMipMaps){minFilter=gl.NEAREST_MIPMAP_LINEAR;}else{minFilter=gl.NEAREST;}}return{min:minFilter,mag:magFilter};};var getExponantOfTwo=function(value,max){var count=1;do{count*=2;}while(countmax)count=max;return count;};var prepareWebGLTexture=function(texture,gl,scene,width,height,invertY,noMipmap,isCompressed,processFunction,samplingMode){if(typeof samplingMode==="undefined"){samplingMode=BABYLON.Texture.TRILINEAR_SAMPLINGMODE;}var engine=scene.getEngine();var potWidth=getExponantOfTwo(width,engine.getCaps().maxTextureSize);var potHeight=getExponantOfTwo(height,engine.getCaps().maxTextureSize);gl.bindTexture(gl.TEXTURE_2D,texture);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,invertY===undefined?1:(invertY?1:0));processFunction(potWidth,potHeight);var filters=getSamplingParameters(samplingMode,!noMipmap,gl);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,filters.mag);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,filters.min);if(!noMipmap&&!isCompressed){gl.generateMipmap(gl.TEXTURE_2D);}gl.bindTexture(gl.TEXTURE_2D,null);engine._activeTexturesCache=[];texture._baseWidth=width;texture._baseHeight=height;texture._width=potWidth;texture._height=potHeight;texture.isReady=true;scene._removePendingData(texture);};var cascadeLoad=function(rootUrl,index,loadedImages,scene,onfinish,extensions){var img;var onload=function(){loadedImages.push(img);scene._removePendingData(img);if(index!=extensions.length-1){cascadeLoad(rootUrl,index+1,loadedImages,scene,onfinish,extensions);}else{onfinish(loadedImages);}};var onerror=function(){scene._removePendingData(img);};img=BABYLON.Tools.LoadImage(rootUrl+extensions[index],onload,onerror,scene.database);scene._addPendingData(img);};var EngineCapabilities=(function(){function EngineCapabilities(){}return EngineCapabilities;})();BABYLON.EngineCapabilities=EngineCapabilities;var Engine=(function(){function Engine(canvas,antialias,options){var _this=this;this.isFullscreen=false;this.isPointerLock=false;this.forceWireframe=false;this.cullBackFaces=true;this.renderEvenInBackground=true;this.scenes=new Array();this._windowIsBackground=false;this._runningLoop=false;this._loadedTexturesCache=new Array();this._activeTexturesCache=new Array();this._compiledEffects={};this._depthMask=false;this._renderingCanvas=canvas;this._canvasClientRect=this._renderingCanvas.getBoundingClientRect();options=options||{};options.antialias=antialias;try{this._gl=canvas.getContext("webgl",options)||canvas.getContext("experimental-webgl",options);}catch(e){throw new Error("WebGL not supported");}if(!this._gl){throw new Error("WebGL not supported");}this._onBlur=function(){_this._windowIsBackground=true;};this._onFocus=function(){_this._windowIsBackground=false;};window.addEventListener("blur",this._onBlur);window.addEventListener("focus",this._onFocus);this._workingCanvas=document.createElement("canvas");this._workingContext=this._workingCanvas.getContext("2d");this._hardwareScalingLevel=1.0/(window.devicePixelRatio||1.0);this.resize();this._caps=new EngineCapabilities();this._caps.maxTexturesImageUnits=this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);this._caps.maxTextureSize=this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);this._caps.maxCubemapTextureSize=this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);this._caps.maxRenderTextureSize=this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);this._caps.standardDerivatives=(this._gl.getExtension('OES_standard_derivatives')!==null);this._caps.s3tc=this._gl.getExtension('WEBGL_compressed_texture_s3tc');this._caps.textureFloat=(this._gl.getExtension('OES_texture_float')!==null);this._caps.textureAnisotropicFilterExtension=this._gl.getExtension('EXT_texture_filter_anisotropic')||this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic')||this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0;this._caps.instancedArrays=this._gl.getExtension('ANGLE_instanced_arrays');this.setDepthBuffer(true);this.setDepthFunctionToLessOrEqual();this.setDepthWrite(true);this._onFullscreenChange=function(){if(document.fullscreen!==undefined){_this.isFullscreen=document.fullscreen;}else if(document.mozFullScreen!==undefined){_this.isFullscreen=document.mozFullScreen;}else if(document.webkitIsFullScreen!==undefined){_this.isFullscreen=document.webkitIsFullScreen;}else if(document.msIsFullScreen!==undefined){_this.isFullscreen=document.msIsFullScreen;}if(_this.isFullscreen&&_this._pointerLockRequested){canvas.requestPointerLock=canvas.requestPointerLock||canvas.msRequestPointerLock||canvas.mozRequestPointerLock||canvas.webkitRequestPointerLock;if(canvas.requestPointerLock){canvas.requestPointerLock();}}};document.addEventListener("fullscreenchange",this._onFullscreenChange,false);document.addEventListener("mozfullscreenchange",this._onFullscreenChange,false);document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,false);document.addEventListener("msfullscreenchange",this._onFullscreenChange,false);this._onPointerLockChange=function(){_this.isPointerLock=(document.mozPointerLockElement===canvas||document.webkitPointerLockElement===canvas||document.msPointerLockElement===canvas||document.pointerLockElement===canvas);};document.addEventListener("pointerlockchange",this._onPointerLockChange,false);document.addEventListener("mspointerlockchange",this._onPointerLockChange,false);document.addEventListener("mozpointerlockchange",this._onPointerLockChange,false);document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,false);}Object.defineProperty(Engine,"ALPHA_DISABLE",{get:function(){return Engine._ALPHA_DISABLE;},enumerable:true,configurable:true});Object.defineProperty(Engine,"ALPHA_ADD",{get:function(){return Engine._ALPHA_ADD;},enumerable:true,configurable:true});Object.defineProperty(Engine,"ALPHA_COMBINE",{get:function(){return Engine._ALPHA_COMBINE;},enumerable:true,configurable:true});Object.defineProperty(Engine,"DELAYLOADSTATE_NONE",{get:function(){return Engine._DELAYLOADSTATE_NONE;},enumerable:true,configurable:true});Object.defineProperty(Engine,"DELAYLOADSTATE_LOADED",{get:function(){return Engine._DELAYLOADSTATE_LOADED;},enumerable:true,configurable:true});Object.defineProperty(Engine,"DELAYLOADSTATE_LOADING",{get:function(){return Engine._DELAYLOADSTATE_LOADING;},enumerable:true,configurable:true});Object.defineProperty(Engine,"DELAYLOADSTATE_NOTLOADED",{get:function(){return Engine._DELAYLOADSTATE_NOTLOADED;},enumerable:true,configurable:true});Object.defineProperty(Engine,"Version",{get:function(){return"1.13.0";},enumerable:true,configurable:true});Engine.prototype.getAspectRatio=function(camera){var viewport=camera.viewport;return(this.getRenderWidth()*viewport.width)/(this.getRenderHeight()*viewport.height);};Engine.prototype.getRenderWidth=function(){if(this._currentRenderTarget){return this._currentRenderTarget._width;}return this._renderingCanvas.width;};Engine.prototype.getRenderHeight=function(){if(this._currentRenderTarget){return this._currentRenderTarget._height;}return this._renderingCanvas.height;};Engine.prototype.getRenderingCanvas=function(){return this._renderingCanvas;};Engine.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas.getBoundingClientRect();};Engine.prototype.setHardwareScalingLevel=function(level){this._hardwareScalingLevel=level;this.resize();};Engine.prototype.getHardwareScalingLevel=function(){return this._hardwareScalingLevel;};Engine.prototype.getLoadedTexturesCache=function(){return this._loadedTexturesCache;};Engine.prototype.getCaps=function(){return this._caps;};Engine.prototype.setDepthFunctionToGreater=function(){this._gl.depthFunc(this._gl.GREATER);};Engine.prototype.setDepthFunctionToGreaterOrEqual=function(){this._gl.depthFunc(this._gl.GEQUAL);};Engine.prototype.setDepthFunctionToLess=function(){this._gl.depthFunc(this._gl.LESS);};Engine.prototype.setDepthFunctionToLessOrEqual=function(){this._gl.depthFunc(this._gl.LEQUAL);};Engine.prototype.stopRenderLoop=function(){this._renderFunction=null;this._runningLoop=false;};Engine.prototype._renderLoop=function(){var _this=this;var shouldRender=true;if(!this.renderEvenInBackground&&this._windowIsBackground){shouldRender=false;}if(shouldRender){this.beginFrame();if(this._renderFunction){this._renderFunction();}this.endFrame();}if(this._runningLoop){BABYLON.Tools.QueueNewFrame(function(){_this._renderLoop();});}};Engine.prototype.runRenderLoop=function(renderFunction){var _this=this;this._runningLoop=true;this._renderFunction=renderFunction;BABYLON.Tools.QueueNewFrame(function(){_this._renderLoop();});};Engine.prototype.switchFullscreen=function(requestPointerLock){if(this.isFullscreen){BABYLON.Tools.ExitFullscreen();}else{this._pointerLockRequested=requestPointerLock;BABYLON.Tools.RequestFullscreen(this._renderingCanvas);}};Engine.prototype.clear=function(color,backBuffer,depthStencil){this._gl.clearColor(color.r,color.g,color.b,color.a!==undefined?color.a:1.0);if(this._depthMask){this._gl.clearDepth(1.0);}var mode=0;if(backBuffer)mode|=this._gl.COLOR_BUFFER_BIT;if(depthStencil&&this._depthMask)mode|=this._gl.DEPTH_BUFFER_BIT;this._gl.clear(mode);};Engine.prototype.setViewport=function(viewport,requiredWidth,requiredHeight){var width=requiredWidth||this._renderingCanvas.width;var height=requiredHeight||this._renderingCanvas.height;var x=viewport.x||0;var y=viewport.y||0;this._cachedViewport=viewport;this._gl.viewport(x*width,y*height,width*viewport.width,height*viewport.height);};Engine.prototype.setDirectViewport=function(x,y,width,height){this._cachedViewport=null;this._gl.viewport(x,y,width,height);};Engine.prototype.beginFrame=function(){BABYLON.Tools._MeasureFps();};Engine.prototype.endFrame=function(){this.flushFramebuffer();};Engine.prototype.resize=function(){this._renderingCanvas.width=this._renderingCanvas.clientWidth/this._hardwareScalingLevel;this._renderingCanvas.height=this._renderingCanvas.clientHeight/this._hardwareScalingLevel;this._canvasClientRect=this._renderingCanvas.getBoundingClientRect();};Engine.prototype.bindFramebuffer=function(texture){this._currentRenderTarget=texture;var gl=this._gl;gl.bindFramebuffer(gl.FRAMEBUFFER,texture._framebuffer);this._gl.viewport(0,0,texture._width,texture._height);this.wipeCaches();};Engine.prototype.unBindFramebuffer=function(texture){this._currentRenderTarget=null;if(texture.generateMipMaps){var gl=this._gl;gl.bindTexture(gl.TEXTURE_2D,texture);gl.generateMipmap(gl.TEXTURE_2D);gl.bindTexture(gl.TEXTURE_2D,null);}this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,null);};Engine.prototype.flushFramebuffer=function(){this._gl.flush();};Engine.prototype.restoreDefaultFramebuffer=function(){this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,null);this.setViewport(this._cachedViewport);this.wipeCaches();};Engine.prototype._resetVertexBufferBinding=function(){this._gl.bindBuffer(this._gl.ARRAY_BUFFER,null);this._cachedVertexBuffers=null;};Engine.prototype.createVertexBuffer=function(vertices){var vbo=this._gl.createBuffer();this._gl.bindBuffer(this._gl.ARRAY_BUFFER,vbo);this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(vertices),this._gl.STATIC_DRAW);this._resetVertexBufferBinding();vbo.references=1;return vbo;};Engine.prototype.createDynamicVertexBuffer=function(capacity){var vbo=this._gl.createBuffer();this._gl.bindBuffer(this._gl.ARRAY_BUFFER,vbo);this._gl.bufferData(this._gl.ARRAY_BUFFER,capacity,this._gl.DYNAMIC_DRAW);this._resetVertexBufferBinding();vbo.references=1;return vbo;};Engine.prototype.updateDynamicVertexBuffer=function(vertexBuffer,vertices,length){this._gl.bindBuffer(this._gl.ARRAY_BUFFER,vertexBuffer);if(vertices instanceof Float32Array){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,vertices);}else{this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(vertices));}this._resetVertexBufferBinding();};Engine.prototype._resetIndexBufferBinding=function(){this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER,null);this._cachedIndexBuffer=null;};Engine.prototype.createIndexBuffer=function(indices){var vbo=this._gl.createBuffer();this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER,vbo);this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,new Uint16Array(indices),this._gl.STATIC_DRAW);this._resetIndexBufferBinding();vbo.references=1;return vbo;};Engine.prototype.bindBuffers=function(vertexBuffer,indexBuffer,vertexDeclaration,vertexStrideSize,effect){if(this._cachedVertexBuffers!==vertexBuffer||this._cachedEffectForVertexBuffers!==effect){this._cachedVertexBuffers=vertexBuffer;this._cachedEffectForVertexBuffers=effect;this._gl.bindBuffer(this._gl.ARRAY_BUFFER,vertexBuffer);var offset=0;for(var index=0;index=0){this._gl.vertexAttribPointer(order,vertexDeclaration[index],this._gl.FLOAT,false,vertexStrideSize,offset);}offset+=vertexDeclaration[index]*4;}}if(this._cachedIndexBuffer!==indexBuffer){this._cachedIndexBuffer=indexBuffer;this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER,indexBuffer);}};Engine.prototype.bindMultiBuffers=function(vertexBuffers,indexBuffer,effect){if(this._cachedVertexBuffers!==vertexBuffers||this._cachedEffectForVertexBuffers!==effect){this._cachedVertexBuffers=vertexBuffers;this._cachedEffectForVertexBuffers=effect;var attributes=effect.getAttributesNames();for(var index=0;index=0){var vertexBuffer=vertexBuffers[attributes[index]];if(!vertexBuffer){continue;}var stride=vertexBuffer.getStrideSize();this._gl.bindBuffer(this._gl.ARRAY_BUFFER,vertexBuffer.getBuffer());this._gl.vertexAttribPointer(order,stride,this._gl.FLOAT,false,stride*4,0);}}}if(this._cachedIndexBuffer!==indexBuffer){this._cachedIndexBuffer=indexBuffer;this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER,indexBuffer);}};Engine.prototype._releaseBuffer=function(buffer){buffer.references--;if(buffer.references===0){this._gl.deleteBuffer(buffer);return true;}return false;};Engine.prototype.createInstancesBuffer=function(capacity){var buffer=this._gl.createBuffer();buffer.capacity=capacity;this._gl.bindBuffer(this._gl.ARRAY_BUFFER,buffer);this._gl.bufferData(this._gl.ARRAY_BUFFER,capacity,this._gl.DYNAMIC_DRAW);return buffer;};Engine.prototype.deleteInstancesBuffer=function(buffer){this._gl.deleteBuffer(buffer);};Engine.prototype.updateAndBindInstancesBuffer=function(instancesBuffer,data,offsetLocations){this._gl.bindBuffer(this._gl.ARRAY_BUFFER,instancesBuffer);this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,data);for(var index=0;index<4;index++){var offsetLocation=offsetLocations[index];this._gl.enableVertexAttribArray(offsetLocation);this._gl.vertexAttribPointer(offsetLocation,4,this._gl.FLOAT,false,64,index*16);this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation,1);}};Engine.prototype.unBindInstancesBuffer=function(instancesBuffer,offsetLocations){this._gl.bindBuffer(this._gl.ARRAY_BUFFER,instancesBuffer);for(var index=0;index<4;index++){var offsetLocation=offsetLocations[index];this._gl.disableVertexAttribArray(offsetLocation);this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation,0);}};Engine.prototype.draw=function(useTriangles,indexStart,indexCount,instancesCount){if(instancesCount){this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles?this._gl.TRIANGLES:this._gl.LINES,indexCount,this._gl.UNSIGNED_SHORT,indexStart*2,instancesCount);return;}this._gl.drawElements(useTriangles?this._gl.TRIANGLES:this._gl.LINES,indexCount,this._gl.UNSIGNED_SHORT,indexStart*2);};Engine.prototype._releaseEffect=function(effect){if(this._compiledEffects[effect._key]){delete this._compiledEffects[effect._key];if(effect.getProgram()){this._gl.deleteProgram(effect.getProgram());}}};Engine.prototype.createEffect=function(baseName,attributesNames,uniformsNames,samplers,defines,optionalDefines,onCompiled,onError){var vertex=baseName.vertexElement||baseName.vertex||baseName;var fragment=baseName.fragmentElement||baseName.fragment||baseName;var name=vertex+"+"+fragment+"@"+defines;if(this._compiledEffects[name]){return this._compiledEffects[name];}var effect=new BABYLON.Effect(baseName,attributesNames,uniformsNames,samplers,this,defines,optionalDefines,onCompiled,onError);effect._key=name;this._compiledEffects[name]=effect;return effect;};Engine.prototype.createShaderProgram=function(vertexCode,fragmentCode,defines){var vertexShader=compileShader(this._gl,vertexCode,"vertex",defines);var fragmentShader=compileShader(this._gl,fragmentCode,"fragment",defines);var shaderProgram=this._gl.createProgram();this._gl.attachShader(shaderProgram,vertexShader);this._gl.attachShader(shaderProgram,fragmentShader);this._gl.linkProgram(shaderProgram);var linked=this._gl.getProgramParameter(shaderProgram,this._gl.LINK_STATUS);if(!linked){var error=this._gl.getProgramInfoLog(shaderProgram);if(error){throw new Error(error);}}this._gl.deleteShader(vertexShader);this._gl.deleteShader(fragmentShader);return shaderProgram;};Engine.prototype.getUniforms=function(shaderProgram,uniformsNames){var results=[];for(var index=0;indexthis._gl.VERTEX_ATTRIB_ARRAY_ENABLED||!this._vertexAttribArrays[i]){continue;}this._vertexAttribArrays[i]=false;this._gl.disableVertexAttribArray(i);}var attributesCount=effect.getAttributesCount();for(var index=0;index=0){this._vertexAttribArrays[order]=true;this._gl.enableVertexAttribArray(order);}}this._currentEffect=effect;};Engine.prototype.setArray=function(uniform,array){if(!uniform)return;this._gl.uniform1fv(uniform,array);};Engine.prototype.setMatrices=function(uniform,matrices){if(!uniform)return;this._gl.uniformMatrix4fv(uniform,false,matrices);};Engine.prototype.setMatrix=function(uniform,matrix){if(!uniform)return;this._gl.uniformMatrix4fv(uniform,false,matrix.toArray());};Engine.prototype.setFloat=function(uniform,value){if(!uniform)return;this._gl.uniform1f(uniform,value);};Engine.prototype.setFloat2=function(uniform,x,y){if(!uniform)return;this._gl.uniform2f(uniform,x,y);};Engine.prototype.setFloat3=function(uniform,x,y,z){if(!uniform)return;this._gl.uniform3f(uniform,x,y,z);};Engine.prototype.setBool=function(uniform,bool){if(!uniform)return;this._gl.uniform1i(uniform,bool);};Engine.prototype.setFloat4=function(uniform,x,y,z,w){if(!uniform)return;this._gl.uniform4f(uniform,x,y,z,w);};Engine.prototype.setColor3=function(uniform,color3){if(!uniform)return;this._gl.uniform3f(uniform,color3.r,color3.g,color3.b);};Engine.prototype.setColor4=function(uniform,color3,alpha){if(!uniform)return;this._gl.uniform4f(uniform,color3.r,color3.g,color3.b,alpha);};Engine.prototype.setState=function(culling){if(this._cullingState!==culling){if(culling){this._gl.cullFace(this.cullBackFaces?this._gl.BACK:this._gl.FRONT);this._gl.enable(this._gl.CULL_FACE);}else{this._gl.disable(this._gl.CULL_FACE);}this._cullingState=culling;}};Engine.prototype.setDepthBuffer=function(enable){if(enable){this._gl.enable(this._gl.DEPTH_TEST);}else{this._gl.disable(this._gl.DEPTH_TEST);}};Engine.prototype.setDepthWrite=function(enable){this._gl.depthMask(enable);this._depthMask=enable;};Engine.prototype.setColorWrite=function(enable){this._gl.colorMask(enable,enable,enable,enable);};Engine.prototype.setAlphaMode=function(mode){switch(mode){case BABYLON.Engine.ALPHA_DISABLE:this.setDepthWrite(true);this._gl.disable(this._gl.BLEND);break;case BABYLON.Engine.ALPHA_COMBINE:this.setDepthWrite(false);this._gl.blendFuncSeparate(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE);this._gl.enable(this._gl.BLEND);break;case BABYLON.Engine.ALPHA_ADD:this.setDepthWrite(false);this._gl.blendFuncSeparate(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE);this._gl.enable(this._gl.BLEND);break;}};Engine.prototype.setAlphaTesting=function(enable){this._alphaTest=enable;};Engine.prototype.getAlphaTesting=function(){return this._alphaTest;};Engine.prototype.wipeCaches=function(){this._activeTexturesCache=[];this._currentEffect=null;this._cullingState=null;this._cachedVertexBuffers=null;this._cachedIndexBuffer=null;this._cachedEffectForVertexBuffers=null;};Engine.prototype.setSamplingMode=function(texture,samplingMode){var gl=this._gl;gl.bindTexture(gl.TEXTURE_2D,texture);var magFilter=gl.NEAREST;var minFilter=gl.NEAREST;if(samplingMode===BABYLON.Texture.BILINEAR_SAMPLINGMODE){magFilter=gl.LINEAR;minFilter=gl.LINEAR;}else if(samplingMode===BABYLON.Texture.TRILINEAR_SAMPLINGMODE){magFilter=gl.LINEAR;minFilter=gl.LINEAR_MIPMAP_LINEAR;}gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,magFilter);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,minFilter);gl.bindTexture(gl.TEXTURE_2D,null);};Engine.prototype.createTexture=function(url,noMipmap,invertY,scene,samplingMode){var _this=this;if(typeof samplingMode==="undefined"){samplingMode=BABYLON.Texture.TRILINEAR_SAMPLINGMODE;}var texture=this._gl.createTexture();var extension=url.substr(url.length-4,4).toLowerCase();var isDDS=this.getCaps().s3tc&&(extension===".dds");var isTGA=(extension===".tga");scene._addPendingData(texture);texture.url=url;texture.noMipmap=noMipmap;texture.references=1;this._loadedTexturesCache.push(texture);if(isTGA){BABYLON.Tools.LoadFile(url,function(arrayBuffer){var data=new Uint8Array(arrayBuffer);var header=BABYLON.Internals.TGATools.GetTGAHeader(data);prepareWebGLTexture(texture,_this._gl,scene,header.width,header.height,invertY,noMipmap,false,function(){BABYLON.Internals.TGATools.UploadContent(_this._gl,data);},samplingMode);},null,scene.database,true);}else if(isDDS){BABYLON.Tools.LoadFile(url,function(data){var info=BABYLON.Internals.DDSTools.GetDDSInfo(data);var loadMipmap=(info.isRGB||info.isLuminance||info.mipmapCount>1)&&!noMipmap&&((info.width>>(info.mipmapCount-1))==1);prepareWebGLTexture(texture,_this._gl,scene,info.width,info.height,invertY,!loadMipmap,info.isFourCC,function(){console.log("loading "+url);BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl,_this.getCaps().s3tc,data,info,loadMipmap,1);},samplingMode);},null,scene.database,true);}else{var onload=function(img){prepareWebGLTexture(texture,_this._gl,scene,img.width,img.height,invertY,noMipmap,false,function(potWidth,potHeight){var isPot=(img.width==potWidth&&img.height==potHeight);if(!isPot){_this._workingCanvas.width=potWidth;_this._workingCanvas.height=potHeight;_this._workingContext.drawImage(img,0,0,img.width,img.height,0,0,potWidth,potHeight);}_this._gl.texImage2D(_this._gl.TEXTURE_2D,0,_this._gl.RGBA,_this._gl.RGBA,_this._gl.UNSIGNED_BYTE,isPot?img:_this._workingCanvas);},samplingMode);};var onerror=function(){scene._removePendingData(texture);};BABYLON.Tools.LoadImage(url,onload,onerror,scene.database);}return texture;};Engine.prototype.createDynamicTexture=function(width,height,generateMipMaps,samplingMode){var texture=this._gl.createTexture();width=getExponantOfTwo(width,this._caps.maxTextureSize);height=getExponantOfTwo(height,this._caps.maxTextureSize);this._gl.bindTexture(this._gl.TEXTURE_2D,texture);var filters=getSamplingParameters(samplingMode,generateMipMaps,this._gl);this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,filters.mag);this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,filters.min);this._gl.bindTexture(this._gl.TEXTURE_2D,null);this._activeTexturesCache=[];texture._baseWidth=width;texture._baseHeight=height;texture._width=width;texture._height=height;texture.isReady=false;texture.generateMipMaps=generateMipMaps;texture.references=1;this._loadedTexturesCache.push(texture);return texture;};Engine.prototype.updateDynamicTexture=function(texture,canvas,invertY){this._gl.bindTexture(this._gl.TEXTURE_2D,texture);this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,invertY?1:0);this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,canvas);if(texture.generateMipMaps){this._gl.generateMipmap(this._gl.TEXTURE_2D);}this._gl.bindTexture(this._gl.TEXTURE_2D,null);this._activeTexturesCache=[];texture.isReady=true;};Engine.prototype.updateVideoTexture=function(texture,video,invertY){this._gl.bindTexture(this._gl.TEXTURE_2D,texture);this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,invertY?0:1);if(video.videoWidth!==texture._width||video.videoHeight!==texture._height){if(!texture._workingCanvas){texture._workingCanvas=document.createElement("canvas");texture._workingContext=texture._workingCanvas.getContext("2d");texture._workingCanvas.width=texture._width;texture._workingCanvas.height=texture._height;}texture._workingContext.drawImage(video,0,0,video.videoWidth,video.videoHeight,0,0,texture._width,texture._height);this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,texture._workingCanvas);}else{this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,video);}if(texture.generateMipMaps){this._gl.generateMipmap(this._gl.TEXTURE_2D);}this._gl.bindTexture(this._gl.TEXTURE_2D,null);this._activeTexturesCache=[];texture.isReady=true;};Engine.prototype.createRenderTargetTexture=function(size,options){var generateMipMaps=false;var generateDepthBuffer=true;var samplingMode=BABYLON.Texture.TRILINEAR_SAMPLINGMODE;if(options!==undefined){generateMipMaps=options.generateMipMaps===undefined?options:options.generateMipmaps;generateDepthBuffer=options.generateDepthBuffer===undefined?true:options.generateDepthBuffer;if(options.samplingMode!==undefined){samplingMode=options.samplingMode;}}var gl=this._gl;var texture=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,texture);var width=size.width||size;var height=size.height||size;var filters=getSamplingParameters(samplingMode,generateMipMaps,gl);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,filters.mag);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,filters.min);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,width,height,0,gl.RGBA,gl.UNSIGNED_BYTE,null);var depthBuffer;if(generateDepthBuffer){depthBuffer=gl.createRenderbuffer();gl.bindRenderbuffer(gl.RENDERBUFFER,depthBuffer);gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_COMPONENT16,width,height);}var framebuffer=gl.createFramebuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,framebuffer);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0);if(generateDepthBuffer){gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.DEPTH_ATTACHMENT,gl.RENDERBUFFER,depthBuffer);}gl.bindTexture(gl.TEXTURE_2D,null);gl.bindRenderbuffer(gl.RENDERBUFFER,null);gl.bindFramebuffer(gl.FRAMEBUFFER,null);texture._framebuffer=framebuffer;if(generateDepthBuffer){texture._depthBuffer=depthBuffer;}texture._width=width;texture._height=height;texture.isReady=true;texture.generateMipMaps=generateMipMaps;texture.references=1;this._activeTexturesCache=[];this._loadedTexturesCache.push(texture);return texture;};Engine.prototype.createCubeTexture=function(rootUrl,scene,extensions,noMipmap){var _this=this;var gl=this._gl;var texture=gl.createTexture();texture.isCube=true;texture.url=rootUrl;texture.references=1;this._loadedTexturesCache.push(texture);var extension=rootUrl.substr(rootUrl.length-4,4).toLowerCase();var isDDS=this.getCaps().s3tc&&(extension===".dds");if(isDDS){BABYLON.Tools.LoadFile(rootUrl,function(data){var info=BABYLON.Internals.DDSTools.GetDDSInfo(data);var loadMipmap=(info.isRGB||info.isLuminance||info.mipmapCount>1)&&!noMipmap;gl.bindTexture(gl.TEXTURE_CUBE_MAP,texture);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,1);BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl,_this.getCaps().s3tc,data,info,loadMipmap,6);if(!noMipmap&&!info.isFourCC&&info.mipmapCount==1){gl.generateMipmap(gl.TEXTURE_CUBE_MAP);}gl.texParameteri(gl.TEXTURE_CUBE_MAP,gl.TEXTURE_MAG_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_CUBE_MAP,gl.TEXTURE_MIN_FILTER,loadMipmap?gl.LINEAR_MIPMAP_LINEAR:gl.LINEAR);gl.texParameteri(gl.TEXTURE_CUBE_MAP,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_CUBE_MAP,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.bindTexture(gl.TEXTURE_CUBE_MAP,null);_this._activeTexturesCache=[];texture._width=info.width;texture._height=info.height;texture.isReady=true;});}else{cascadeLoad(rootUrl,0,[],scene,function(imgs){var width=getExponantOfTwo(imgs[0].width,_this._caps.maxCubemapTextureSize);var height=width;_this._workingCanvas.width=width;_this._workingCanvas.height=height;var faces=[gl.TEXTURE_CUBE_MAP_POSITIVE_X,gl.TEXTURE_CUBE_MAP_POSITIVE_Y,gl.TEXTURE_CUBE_MAP_POSITIVE_Z,gl.TEXTURE_CUBE_MAP_NEGATIVE_X,gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,gl.TEXTURE_CUBE_MAP_NEGATIVE_Z];gl.bindTexture(gl.TEXTURE_CUBE_MAP,texture);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,0);for(var index=0;indexthis._gl.VERTEX_ATTRIB_ARRAY_ENABLED||!this._vertexAttribArrays[i]){continue;}this._gl.disableVertexAttribArray(i);}window.removeEventListener("blur",this._onBlur);window.removeEventListener("focus",this._onFocus);document.removeEventListener("fullscreenchange",this._onFullscreenChange);document.removeEventListener("mozfullscreenchange",this._onFullscreenChange);document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange);document.removeEventListener("msfullscreenchange",this._onFullscreenChange);document.removeEventListener("pointerlockchange",this._onPointerLockChange);document.removeEventListener("mspointerlockchange",this._onPointerLockChange);document.removeEventListener("mozpointerlockchange",this._onPointerLockChange);document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange);};Engine.isSupported=function(){try{var tempcanvas=document.createElement("canvas");var gl=tempcanvas.getContext("webgl")||tempcanvas.getContext("experimental-webgl");return gl!=null&&!!window.WebGLRenderingContext;}catch(e){return false;}};Engine._ALPHA_DISABLE=0;Engine._ALPHA_ADD=1;Engine._ALPHA_COMBINE=2;Engine._DELAYLOADSTATE_NONE=0;Engine._DELAYLOADSTATE_LOADED=1;Engine._DELAYLOADSTATE_LOADING=2;Engine._DELAYLOADSTATE_NOTLOADED=4;Engine.Epsilon=0.001;Engine.CollisionsEpsilon=0.001;Engine.ShadersRepository="Babylon/Shaders/";return Engine;})();BABYLON.Engine=Engine;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var Node=(function(){function Node(name,scene){this.state="";this.animations=new Array();this._childrenFlag=-1;this._isEnabled=true;this._isReady=true;this._currentRenderId=-1;this.name=name;this.id=name;this._scene=scene;this._initCache();}Node.prototype.getScene=function(){return this._scene;};Node.prototype.getEngine=function(){return this._scene.getEngine();};Node.prototype.getWorldMatrix=function(){return BABYLON.Matrix.Identity();};Node.prototype._initCache=function(){this._cache={};this._cache.parent=undefined;};Node.prototype.updateCache=function(force){if(!force&&this.isSynchronized())return;this._cache.parent=this.parent;this._updateCache();};Node.prototype._updateCache=function(ignoreParentClass){};Node.prototype._isSynchronized=function(){return true;};Node.prototype.isSynchronizedWithParent=function(){return this.parent?this.parent._currentRenderId<=this._currentRenderId:true;};Node.prototype.isSynchronized=function(updateCache){var check=this.hasNewParent();check=check||!this.isSynchronizedWithParent();check=check||!this._isSynchronized();if(updateCache)this.updateCache(true);return!check;};Node.prototype.hasNewParent=function(update){if(this._cache.parent===this.parent)return false;if(update)this._cache.parent=this.parent;return true;};Node.prototype.isReady=function(){return this._isReady;};Node.prototype.isEnabled=function(){if(!this._isEnabled){return false;}if(this.parent){return this.parent.isEnabled();}return true;};Node.prototype.setEnabled=function(value){this._isEnabled=value;};Node.prototype.isDescendantOf=function(ancestor){if(this.parent){if(this.parent===ancestor){return true;}return this.parent.isDescendantOf(ancestor);}return false;};Node.prototype._getDescendants=function(list,results){for(var index=0;indexthis.maximumWorld.x)this.maximumWorld.x=v.x;if(v.y>this.maximumWorld.y)this.maximumWorld.y=v.y;if(v.z>this.maximumWorld.z)this.maximumWorld.z=v.z;}this.maximumWorld.addToRef(this.minimumWorld,this.center);this.center.scaleInPlace(0.5);BABYLON.Vector3.FromFloatArrayToRef(world.m,0,this.directions[0]);BABYLON.Vector3.FromFloatArrayToRef(world.m,4,this.directions[1]);BABYLON.Vector3.FromFloatArrayToRef(world.m,8,this.directions[2]);this._worldMatrix=world;};BoundingBox.prototype.isInFrustum=function(frustumPlanes){return BoundingBox.IsInFrustum(this.vectorsWorld,frustumPlanes);};BoundingBox.prototype.intersectsPoint=function(point){var delta=BABYLON.Engine.Epsilon;if(this.maximumWorld.x-point.xpoint.x-this.minimumWorld.x)return false;if(this.maximumWorld.y-point.ypoint.y-this.minimumWorld.y)return false;if(this.maximumWorld.z-point.zpoint.z-this.minimumWorld.z)return false;return true;};BoundingBox.prototype.intersectsSphere=function(sphere){return BoundingBox.IntersectsSphere(this.minimumWorld,this.maximumWorld,sphere.centerWorld,sphere.radiusWorld);};BoundingBox.prototype.intersectsMinMax=function(min,max){if(this.maximumWorld.xmax.x)return false;if(this.maximumWorld.ymax.y)return false;if(this.maximumWorld.zmax.z)return false;return true;};BoundingBox.Intersects=function(box0,box1){if(box0.maximumWorld.xbox1.maximumWorld.x)return false;if(box0.maximumWorld.ybox1.maximumWorld.y)return false;if(box0.maximumWorld.zbox1.maximumWorld.z)return false;return true;};BoundingBox.IntersectsSphere=function(minPoint,maxPoint,sphereCenter,sphereRadius){var vector=BABYLON.Vector3.Clamp(sphereCenter,minPoint,maxPoint);var num=BABYLON.Vector3.DistanceSquared(sphereCenter,vector);return(num<=(sphereRadius*sphereRadius));};BoundingBox.IsInFrustum=function(boundingVectors,frustumPlanes){for(var p=0;p<6;p++){var inCount=8;for(var i=0;i<8;i++){if(frustumPlanes[p].dotCoordinate(boundingVectors[i])<0){--inCount;}else{break;}}if(inCount==0)return false;}return true;};return BoundingBox;})();BABYLON.BoundingBox=BoundingBox;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var computeBoxExtents=function(axis,box){var p=BABYLON.Vector3.Dot(box.center,axis);var r0=Math.abs(BABYLON.Vector3.Dot(box.directions[0],axis))*box.extends.x;var r1=Math.abs(BABYLON.Vector3.Dot(box.directions[1],axis))*box.extends.y;var r2=Math.abs(BABYLON.Vector3.Dot(box.directions[2],axis))*box.extends.z;var r=r0+r1+r2;return{min:p-r,max:p+r};};var extentsOverlap=function(min0,max0,min1,max1){return!(min0>max1||min1>max0);};var axisOverlap=function(axis,box0,box1){var result0=computeBoxExtents(axis,box0);var result1=computeBoxExtents(axis,box1);return extentsOverlap(result0.min,result0.max,result1.min,result1.max);};var BoundingInfo=(function(){function BoundingInfo(minimum,maximum){this.minimum=minimum;this.maximum=maximum;this.boundingBox=new BABYLON.BoundingBox(minimum,maximum);this.boundingSphere=new BABYLON.BoundingSphere(minimum,maximum);}BoundingInfo.prototype._update=function(world){this.boundingBox._update(world);this.boundingSphere._update(world);};BoundingInfo.prototype.isInFrustum=function(frustumPlanes){if(!this.boundingSphere.isInFrustum(frustumPlanes))return false;return this.boundingBox.isInFrustum(frustumPlanes);};BoundingInfo.prototype._checkCollision=function(collider){return collider._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld);};BoundingInfo.prototype.intersectsPoint=function(point){if(!this.boundingSphere.centerWorld){return false;}if(!this.boundingSphere.intersectsPoint(point)){return false;}if(!this.boundingBox.intersectsPoint(point)){return false;}return true;};BoundingInfo.prototype.intersects=function(boundingInfo,precise){if(!this.boundingSphere.centerWorld||!boundingInfo.boundingSphere.centerWorld){return false;}if(!BABYLON.BoundingSphere.Intersects(this.boundingSphere,boundingInfo.boundingSphere)){return false;}if(!BABYLON.BoundingBox.Intersects(this.boundingBox,boundingInfo.boundingBox)){return false;}if(!precise){return true;}var box0=this.boundingBox;var box1=boundingInfo.boundingBox;if(!axisOverlap(box0.directions[0],box0,box1))return false;if(!axisOverlap(box0.directions[1],box0,box1))return false;if(!axisOverlap(box0.directions[2],box0,box1))return false;if(!axisOverlap(box1.directions[0],box0,box1))return false;if(!axisOverlap(box1.directions[1],box0,box1))return false;if(!axisOverlap(box1.directions[2],box0,box1))return false;if(!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0],box1.directions[0]),box0,box1))return false;if(!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0],box1.directions[1]),box0,box1))return false;if(!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0],box1.directions[2]),box0,box1))return false;if(!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1],box1.directions[0]),box0,box1))return false;if(!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1],box1.directions[1]),box0,box1))return false;if(!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1],box1.directions[2]),box0,box1))return false;if(!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2],box1.directions[0]),box0,box1))return false;if(!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2],box1.directions[1]),box0,box1))return false;if(!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2],box1.directions[2]),box0,box1))return false;return true;};return BoundingInfo;})();BABYLON.BoundingInfo=BoundingInfo;})(BABYLON||(BABYLON={}));var __extends=this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d;}__.prototype=b.prototype;d.prototype=new __();};var BABYLON;(function(BABYLON){var Light=(function(_super){__extends(Light,_super);function Light(name,scene){_super.call(this,name,scene);this.diffuse=new BABYLON.Color3(1.0,1.0,1.0);this.specular=new BABYLON.Color3(1.0,1.0,1.0);this.intensity=1.0;this.range=Number.MAX_VALUE;this.includedOnlyMeshes=new Array();this.excludedMeshes=new Array();this._excludedMeshesIds=new Array();this._includedOnlyMeshesIds=new Array();scene.lights.push(this);}Light.prototype.getShadowGenerator=function(){return this._shadowGenerator;};Light.prototype.transferToEffect=function(effect,uniformName0,uniformName1){};Light.prototype._getWorldMatrix=function(){return BABYLON.Matrix.Identity();};Light.prototype.canAffectMesh=function(mesh){if(!mesh){return true;}if(this.includedOnlyMeshes.length>0&&this.includedOnlyMeshes.indexOf(mesh)===-1){return false;}if(this.includedOnlyMeshes.length>0&&this.excludedMeshes.indexOf(mesh)!==-1){return false;}return true;};Light.prototype.getWorldMatrix=function(){this._currentRenderId=this.getScene().getRenderId();var worldMatrix=this._getWorldMatrix();if(this.parent&&this.parent.getWorldMatrix){if(!this._parentedWorldMatrix){this._parentedWorldMatrix=BABYLON.Matrix.Identity();}worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._parentedWorldMatrix);return this._parentedWorldMatrix;}return worldMatrix;};Light.prototype.dispose=function(){if(this._shadowGenerator){this._shadowGenerator.dispose();this._shadowGenerator=null;}var index=this.getScene().lights.indexOf(this);this.getScene().lights.splice(index,1);};return Light;})(BABYLON.Node);BABYLON.Light=Light;})(BABYLON||(BABYLON={}));var __extends=this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d;}__.prototype=b.prototype;d.prototype=new __();};var BABYLON;(function(BABYLON){var PointLight=(function(_super){__extends(PointLight,_super);function PointLight(name,position,scene){_super.call(this,name,scene);this.position=position;}PointLight.prototype.transferToEffect=function(effect,positionUniformName){if(this.parent&&this.parent.getWorldMatrix){if(!this._transformedPosition){this._transformedPosition=BABYLON.Vector3.Zero();}BABYLON.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this._transformedPosition);effect.setFloat4(positionUniformName,this._transformedPosition.x,this._transformedPosition.y,this._transformedPosition.z,0);return;}effect.setFloat4(positionUniformName,this.position.x,this.position.y,this.position.z,0);};PointLight.prototype.getShadowGenerator=function(){return null;};PointLight.prototype._getWorldMatrix=function(){if(!this._worldMatrix){this._worldMatrix=BABYLON.Matrix.Identity();}BABYLON.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix);return this._worldMatrix;};return PointLight;})(BABYLON.Light);BABYLON.PointLight=PointLight;})(BABYLON||(BABYLON={}));var __extends=this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d;}__.prototype=b.prototype;d.prototype=new __();};var BABYLON;(function(BABYLON){var SpotLight=(function(_super){__extends(SpotLight,_super);function SpotLight(name,position,direction,angle,exponent,scene){_super.call(this,name,scene);this.position=position;this.direction=direction;this.angle=angle;this.exponent=exponent;}SpotLight.prototype.setDirectionToTarget=function(target){this.direction=BABYLON.Vector3.Normalize(target.subtract(this.position));return this.direction;};SpotLight.prototype.transferToEffect=function(effect,positionUniformName,directionUniformName){var normalizeDirection;if(this.parent&&this.parent.getWorldMatrix){if(!this._transformedDirection){this._transformedDirection=BABYLON.Vector3.Zero();}if(!this._transformedPosition){this._transformedPosition=BABYLON.Vector3.Zero();}var parentWorldMatrix=this.parent.getWorldMatrix();BABYLON.Vector3.TransformCoordinatesToRef(this.position,parentWorldMatrix,this._transformedPosition);BABYLON.Vector3.TransformNormalToRef(this.direction,parentWorldMatrix,this._transformedDirection);effect.setFloat4(positionUniformName,this._transformedPosition.x,this._transformedPosition.y,this._transformedPosition.z,this.exponent);normalizeDirection=BABYLON.Vector3.Normalize(this._transformedDirection);}else{effect.setFloat4(positionUniformName,this.position.x,this.position.y,this.position.z,this.exponent);normalizeDirection=BABYLON.Vector3.Normalize(this.direction);}effect.setFloat4(directionUniformName,normalizeDirection.x,normalizeDirection.y,normalizeDirection.z,Math.cos(this.angle*0.5));};SpotLight.prototype._getWorldMatrix=function(){if(!this._worldMatrix){this._worldMatrix=BABYLON.Matrix.Identity();}BABYLON.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix);return this._worldMatrix;};return SpotLight;})(BABYLON.Light);BABYLON.SpotLight=SpotLight;})(BABYLON||(BABYLON={}));var __extends=this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d;}__.prototype=b.prototype;d.prototype=new __();};var BABYLON;(function(BABYLON){var DirectionalLight=(function(_super){__extends(DirectionalLight,_super);function DirectionalLight(name,direction,scene){_super.call(this,name,scene);this.direction=direction;this.position=direction.scale(-1);}DirectionalLight.prototype.setDirectionToTarget=function(target){this.direction=BABYLON.Vector3.Normalize(target.subtract(this.position));return this.direction;};DirectionalLight.prototype._computeTransformedPosition=function(){if(this.parent&&this.parent.getWorldMatrix){if(!this._transformedPosition){this._transformedPosition=BABYLON.Vector3.Zero();}BABYLON.Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this._transformedPosition);return true;}return false;};DirectionalLight.prototype.transferToEffect=function(effect,directionUniformName){if(this.parent&&this.parent.getWorldMatrix){if(!this._transformedDirection){this._transformedDirection=BABYLON.Vector3.Zero();}BABYLON.Vector3.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this._transformedDirection);effect.setFloat4(directionUniformName,this._transformedDirection.x,this._transformedDirection.y,this._transformedDirection.z,1);return;}effect.setFloat4(directionUniformName,this.direction.x,this.direction.y,this.direction.z,1);};DirectionalLight.prototype._getWorldMatrix=function(){if(!this._worldMatrix){this._worldMatrix=BABYLON.Matrix.Identity();}BABYLON.Matrix.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix);return this._worldMatrix;};return DirectionalLight;})(BABYLON.Light);BABYLON.DirectionalLight=DirectionalLight;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var ShadowGenerator=(function(){function ShadowGenerator(mapSize,light){var _this=this;this.filter=ShadowGenerator.FILTER_VARIANCESHADOWMAP;this._darkness=0;this._transparencyShadow=false;this._viewMatrix=BABYLON.Matrix.Zero();this._projectionMatrix=BABYLON.Matrix.Zero();this._transformMatrix=BABYLON.Matrix.Zero();this._worldViewProjection=BABYLON.Matrix.Zero();this._light=light;this._scene=light.getScene();light._shadowGenerator=this;this._shadowMap=new BABYLON.RenderTargetTexture(light.name+"_shadowMap",mapSize,this._scene,false);this._shadowMap.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE;this._shadowMap.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE;this._shadowMap.renderParticles=false;var renderSubMesh=function(subMesh){var mesh=subMesh.getRenderingMesh();var scene=_this._scene;var engine=scene.getEngine();engine.setState(subMesh.getMaterial().backFaceCulling);var batch=mesh._getInstancesRenderList(subMesh._id);if(batch.mustReturn){return;}var hardwareInstancedRendering=(engine.getCaps().instancedArrays!==null)&&(batch.visibleInstances!==null);if(_this.isReady(subMesh,hardwareInstancedRendering)){engine.enableEffect(_this._effect);mesh._bind(subMesh,_this._effect,false);var material=subMesh.getMaterial();_this._effect.setMatrix("viewProjection",_this.getTransformMatrix());if(material&&material.needAlphaTesting()){var alphaTexture=material.getAlphaTestTexture();_this._effect.setTexture("diffuseSampler",alphaTexture);_this._effect.setMatrix("diffuseMatrix",alphaTexture.getTextureMatrix());}var useBones=mesh.skeleton&&mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)&&mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);if(useBones){_this._effect.setMatrices("mBones",mesh.skeleton.getTransformMatrices());}if(hardwareInstancedRendering){mesh._renderWithInstances(subMesh,false,batch,_this._effect,engine);}else{if(batch.renderSelf[subMesh._id]){_this._effect.setMatrix("world",mesh.getWorldMatrix());mesh._draw(subMesh,true);}if(batch.visibleInstances[subMesh._id]){for(var instanceIndex=0;instanceIndex=1.0)this._darkness=1.0;else if(darkness<=0.0)this._darkness=0.0;elsethis._darkness=darkness;};ShadowGenerator.prototype.setTransparencyShadow=function(hasShadow){this._transparencyShadow=hasShadow;};ShadowGenerator.prototype.dispose=function(){this._shadowMap.dispose();};ShadowGenerator._FILTER_NONE=0;ShadowGenerator._FILTER_VARIANCESHADOWMAP=1;ShadowGenerator._FILTER_POISSONSAMPLING=2;return ShadowGenerator;})();BABYLON.ShadowGenerator=ShadowGenerator;})(BABYLON||(BABYLON={}));var __extends=this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d;}__.prototype=b.prototype;d.prototype=new __();};var BABYLON;(function(BABYLON){var HemisphericLight=(function(_super){__extends(HemisphericLight,_super);function HemisphericLight(name,direction,scene){_super.call(this,name,scene);this.direction=direction;this.groundColor=new BABYLON.Color3(0.0,0.0,0.0);}HemisphericLight.prototype.setDirectionToTarget=function(target){this.direction=BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));return this.direction;};HemisphericLight.prototype.getShadowGenerator=function(){return null;};HemisphericLight.prototype.transferToEffect=function(effect,directionUniformName,groundColorUniformName){var normalizeDirection=BABYLON.Vector3.Normalize(this.direction);effect.setFloat4(directionUniformName,normalizeDirection.x,normalizeDirection.y,normalizeDirection.z,0);effect.setColor3(groundColorUniformName,this.groundColor.scale(this.intensity));};HemisphericLight.prototype._getWorldMatrix=function(){if(!this._worldMatrix){this._worldMatrix=BABYLON.Matrix.Identity();}return this._worldMatrix;};return HemisphericLight;})(BABYLON.Light);BABYLON.HemisphericLight=HemisphericLight;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var intersectBoxAASphere=function(boxMin,boxMax,sphereCenter,sphereRadius){if(boxMin.x>sphereCenter.x+sphereRadius)return false;if(sphereCenter.x-sphereRadius>boxMax.x)return false;if(boxMin.y>sphereCenter.y+sphereRadius)return false;if(sphereCenter.y-sphereRadius>boxMax.y)return false;if(boxMin.z>sphereCenter.z+sphereRadius)return false;if(sphereCenter.z-sphereRadius>boxMax.z)return false;return true;};var getLowestRoot=function(a,b,c,maxR){var determinant=b*b-4.0*a*c;var result={root:0,found:false};if(determinant<0)return result;var sqrtD=Math.sqrt(determinant);var r1=(-b-sqrtD)/(2.0*a);var r2=(-b+sqrtD)/(2.0*a);if(r1>r2){var temp=r2;r2=r1;r1=temp;}if(r1>0&&r10&&r2=0;};Collider.prototype._canDoCollision=function(sphereCenter,sphereRadius,vecMin,vecMax){var distance=BABYLON.Vector3.Distance(this.basePointWorld,sphereCenter);var max=Math.max(this.radius.x,this.radius.y,this.radius.z);if(distance>this.velocityWorldLength+max+sphereRadius){return false;}if(!intersectBoxAASphere(vecMin,vecMax,this.basePointWorld,this.velocityWorldLength+max))return false;return true;};Collider.prototype._testTriangle=function(faceIndex,subMesh,p1,p2,p3){var t0;var embeddedInPlane=false;if(!subMesh._trianglePlanes){subMesh._trianglePlanes=[];}if(!subMesh._trianglePlanes[faceIndex]){subMesh._trianglePlanes[faceIndex]=new BABYLON.Plane(0,0,0,0);subMesh._trianglePlanes[faceIndex].copyFromPoints(p1,p2,p3);}var trianglePlane=subMesh._trianglePlanes[faceIndex];if((!subMesh.getMaterial())&&!trianglePlane.isFrontFacingTo(this.normalizedVelocity,0))return;var signedDistToTrianglePlane=trianglePlane.signedDistanceTo(this.basePoint);var normalDotVelocity=BABYLON.Vector3.Dot(trianglePlane.normal,this.velocity);if(normalDotVelocity==0){if(Math.abs(signedDistToTrianglePlane)>=1.0)return;embeddedInPlane=true;t0=0;}else{t0=(-1.0-signedDistToTrianglePlane)/normalDotVelocity;var t1=(1.0-signedDistToTrianglePlane)/normalDotVelocity;if(t0>t1){var temp=t1;t1=t0;t0=temp;}if(t0>1.0||t1<0.0)return;if(t0<0)t0=0;if(t0>1.0)t0=1.0;}this._collisionPoint.copyFromFloats(0,0,0);var found=false;var t=1.0;if(!embeddedInPlane){this.basePoint.subtractToRef(trianglePlane.normal,this._planeIntersectionPoint);this.velocity.scaleToRef(t0,this._tempVector);this._planeIntersectionPoint.addInPlace(this._tempVector);if(this._checkPointInTriangle(this._planeIntersectionPoint,p1,p2,p3,trianglePlane.normal)){found=true;t=t0;this._collisionPoint.copyFrom(this._planeIntersectionPoint);}}if(!found){var velocitySquaredLength=this.velocity.lengthSquared();var a=velocitySquaredLength;this.basePoint.subtractToRef(p1,this._tempVector);var b=2.0*(BABYLON.Vector3.Dot(this.velocity,this._tempVector));var c=this._tempVector.lengthSquared()-1.0;var lowestRoot=getLowestRoot(a,b,c,t);if(lowestRoot.found){t=lowestRoot.root;found=true;this._collisionPoint.copyFrom(p1);}this.basePoint.subtractToRef(p2,this._tempVector);b=2.0*(BABYLON.Vector3.Dot(this.velocity,this._tempVector));c=this._tempVector.lengthSquared()-1.0;lowestRoot=getLowestRoot(a,b,c,t);if(lowestRoot.found){t=lowestRoot.root;found=true;this._collisionPoint.copyFrom(p2);}this.basePoint.subtractToRef(p3,this._tempVector);b=2.0*(BABYLON.Vector3.Dot(this.velocity,this._tempVector));c=this._tempVector.lengthSquared()-1.0;lowestRoot=getLowestRoot(a,b,c,t);if(lowestRoot.found){t=lowestRoot.root;found=true;this._collisionPoint.copyFrom(p3);}p2.subtractToRef(p1,this._edge);p1.subtractToRef(this.basePoint,this._baseToVertex);var edgeSquaredLength=this._edge.lengthSquared();var edgeDotVelocity=BABYLON.Vector3.Dot(this._edge,this.velocity);var edgeDotBaseToVertex=BABYLON.Vector3.Dot(this._edge,this._baseToVertex);a=edgeSquaredLength*(-velocitySquaredLength)+edgeDotVelocity*edgeDotVelocity;b=edgeSquaredLength*(2.0*BABYLON.Vector3.Dot(this.velocity,this._baseToVertex))-2.0*edgeDotVelocity*edgeDotBaseToVertex;c=edgeSquaredLength*(1.0-this._baseToVertex.lengthSquared())+edgeDotBaseToVertex*edgeDotBaseToVertex;lowestRoot=getLowestRoot(a,b,c,t);if(lowestRoot.found){var f=(edgeDotVelocity*lowestRoot.root-edgeDotBaseToVertex)/edgeSquaredLength;if(f>=0.0&&f<=1.0){t=lowestRoot.root;found=true;this._edge.scaleInPlace(f);p1.addToRef(this._edge,this._collisionPoint);}}p3.subtractToRef(p2,this._edge);p2.subtractToRef(this.basePoint,this._baseToVertex);edgeSquaredLength=this._edge.lengthSquared();edgeDotVelocity=BABYLON.Vector3.Dot(this._edge,this.velocity);edgeDotBaseToVertex=BABYLON.Vector3.Dot(this._edge,this._baseToVertex);a=edgeSquaredLength*(-velocitySquaredLength)+edgeDotVelocity*edgeDotVelocity;b=edgeSquaredLength*(2.0*BABYLON.Vector3.Dot(this.velocity,this._baseToVertex))-2.0*edgeDotVelocity*edgeDotBaseToVertex;c=edgeSquaredLength*(1.0-this._baseToVertex.lengthSquared())+edgeDotBaseToVertex*edgeDotBaseToVertex;lowestRoot=getLowestRoot(a,b,c,t);if(lowestRoot.found){f=(edgeDotVelocity*lowestRoot.root-edgeDotBaseToVertex)/edgeSquaredLength;if(f>=0.0&&f<=1.0){t=lowestRoot.root;found=true;this._edge.scaleInPlace(f);p2.addToRef(this._edge,this._collisionPoint);}}p1.subtractToRef(p3,this._edge);p3.subtractToRef(this.basePoint,this._baseToVertex);edgeSquaredLength=this._edge.lengthSquared();edgeDotVelocity=BABYLON.Vector3.Dot(this._edge,this.velocity);edgeDotBaseToVertex=BABYLON.Vector3.Dot(this._edge,this._baseToVertex);a=edgeSquaredLength*(-velocitySquaredLength)+edgeDotVelocity*edgeDotVelocity;b=edgeSquaredLength*(2.0*BABYLON.Vector3.Dot(this.velocity,this._baseToVertex))-2.0*edgeDotVelocity*edgeDotBaseToVertex;c=edgeSquaredLength*(1.0-this._baseToVertex.lengthSquared())+edgeDotBaseToVertex*edgeDotBaseToVertex;lowestRoot=getLowestRoot(a,b,c,t);if(lowestRoot.found){f=(edgeDotVelocity*lowestRoot.root-edgeDotBaseToVertex)/edgeSquaredLength;if(f>=0.0&&f<=1.0){t=lowestRoot.root;found=true;this._edge.scaleInPlace(f);p3.addToRef(this._edge,this._collisionPoint);}}}if(found){var distToCollision=t*this.velocity.length();if(!this.collisionFound||distToCollision-1){BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");return 0;}if(insertAt==null||insertAt<0){this._postProcesses.push(postProcess);this._postProcessesTakenIndices.push(this._postProcesses.length-1);return this._postProcesses.length-1;}var add=0;if(this._postProcesses[insertAt]){var start=this._postProcesses.length-1;for(var i=start;i>=insertAt+1;--i){this._postProcesses[i+1]=this._postProcesses[i];}add=1;}for(i=0;i=i;--j){this._postProcessesTakenIndices[j+1]=this._postProcessesTakenIndices[j]+add;}this._postProcessesTakenIndices[i]=insertAt;break;}if(!add&&this._postProcessesTakenIndices.indexOf(insertAt)==-1){this._postProcessesTakenIndices.push(insertAt);}var result=insertAt+add;this._postProcesses[result]=postProcess;return result;};Camera.prototype.detachPostProcess=function(postProcess,atIndices){if(typeof atIndices==="undefined"){atIndices=null;}var result=[];if(!atIndices){var length=this._postProcesses.length;for(var i=0;i=0.0){this.rotation.y=(-Math.atan(vDir.z/vDir.x)+Math.PI/2.0);}else{this.rotation.y=(-Math.atan(vDir.z/vDir.x)-Math.PI/2.0);}this.rotation.z=-Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0,1.0,0),this.upVector));if(isNaN(this.rotation.x)){this.rotation.x=0;}if(isNaN(this.rotation.y)){this.rotation.y=0;}if(isNaN(this.rotation.z)){this.rotation.z=0;}};FreeCamera.prototype.getTarget=function(){return this._currentTarget;};FreeCamera.prototype.attachControl=function(element,noPreventDefault){var _this=this;var previousPosition;var engine=this.getEngine();if(this._attachedElement){return;}this._attachedElement=element;if(this._onMouseDown===undefined){this._onMouseDown=function(evt){previousPosition={x:evt.clientX,y:evt.clientY};if(!noPreventDefault){evt.preventDefault();}};this._onMouseUp=function(evt){previousPosition=null;if(!noPreventDefault){evt.preventDefault();}};this._onMouseOut=function(evt){previousPosition=null;_this._keys=[];if(!noPreventDefault){evt.preventDefault();}};this._onMouseMove=function(evt){if(!previousPosition&&!engine.isPointerLock){return;}var offsetX;var offsetY;if(!engine.isPointerLock){offsetX=evt.clientX-previousPosition.x;offsetY=evt.clientY-previousPosition.y;}else{offsetX=evt.movementX||evt.mozMovementX||evt.webkitMovementX||evt.msMovementX||0;offsetY=evt.movementY||evt.mozMovementY||evt.webkitMovementY||evt.msMovementY||0;}_this.cameraRotation.y+=offsetX/_this.angularSensibility;_this.cameraRotation.x+=offsetY/_this.angularSensibility;previousPosition={x:evt.clientX,y:evt.clientY};if(!noPreventDefault){evt.preventDefault();}};this._onKeyDown=function(evt){if(_this.keysUp.indexOf(evt.keyCode)!==-1||_this.keysDown.indexOf(evt.keyCode)!==-1||_this.keysLeft.indexOf(evt.keyCode)!==-1||_this.keysRight.indexOf(evt.keyCode)!==-1){var index=_this._keys.indexOf(evt.keyCode);if(index===-1){_this._keys.push(evt.keyCode);}if(!noPreventDefault){evt.preventDefault();}}};this._onKeyUp=function(evt){if(_this.keysUp.indexOf(evt.keyCode)!==-1||_this.keysDown.indexOf(evt.keyCode)!==-1||_this.keysLeft.indexOf(evt.keyCode)!==-1||_this.keysRight.indexOf(evt.keyCode)!==-1){var index=_this._keys.indexOf(evt.keyCode);if(index>=0){_this._keys.splice(index,1);}if(!noPreventDefault){evt.preventDefault();}}};this._onLostFocus=function(){_this._keys=[];};this._reset=function(){_this._keys=[];previousPosition=null;_this.cameraDirection=new BABYLON.Vector3(0,0,0);_this.cameraRotation=new BABYLON.Vector2(0,0);};}element.addEventListener("mousedown",this._onMouseDown,false);element.addEventListener("mouseup",this._onMouseUp,false);element.addEventListener("mouseout",this._onMouseOut,false);element.addEventListener("mousemove",this._onMouseMove,false);BABYLON.Tools.RegisterTopRootEvents([{name:"keydown",handler:this._onKeyDown},{name:"keyup",handler:this._onKeyUp},{name:"blur",handler:this._onLostFocus}]);};FreeCamera.prototype.detachControl=function(element){if(this._attachedElement!=element){return;}element.removeEventListener("mousedown",this._onMouseDown);element.removeEventListener("mouseup",this._onMouseUp);element.removeEventListener("mouseout",this._onMouseOut);element.removeEventListener("mousemove",this._onMouseMove);BABYLON.Tools.UnregisterTopRootEvents([{name:"keydown",handler:this._onKeyDown},{name:"keyup",handler:this._onKeyUp},{name:"blur",handler:this._onLostFocus}]);this._attachedElement=null;if(this._reset){this._reset();}};FreeCamera.prototype._collideWithWorld=function(velocity){var globalPosition;if(this.parent){globalPosition=BABYLON.Vector3.TransformCoordinates(this.position,this.parent.getWorldMatrix());}else{globalPosition=this.position;}globalPosition.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition);this._collider.radius=this.ellipsoid;this.getScene()._getNewPosition(this._oldPosition,velocity,this._collider,3,this._newPosition);this._newPosition.subtractToRef(this._oldPosition,this._diffPosition);if(this._diffPosition.length()>BABYLON.Engine.CollisionsEpsilon){this.position.addInPlace(this._diffPosition);if(this.onCollide){this.onCollide(this._collider.collidedMesh);}}};FreeCamera.prototype._checkInputs=function(){if(!this._localDirection){this._localDirection=BABYLON.Vector3.Zero();this._transformedDirection=BABYLON.Vector3.Zero();}for(var index=0;index0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0;var needToRotate=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(needToMove){if(this.checkCollisions&&this.getScene().collisionsEnabled){this._collideWithWorld(this.cameraDirection);if(this.applyGravity){var oldPosition=this.position;this._collideWithWorld(this.getScene().gravity);this._needMoveForGravity=(BABYLON.Vector3.DistanceSquared(oldPosition,this.position)!=0);}}else{this.position.addInPlace(this.cameraDirection);}}if(needToRotate){this.rotation.x+=this.cameraRotation.x;this.rotation.y+=this.cameraRotation.y;if(!this.noRotationConstraint){var limit=(Math.PI/2)*0.95;if(this.rotation.x>limit)this.rotation.x=limit;if(this.rotation.x<-limit)this.rotation.x=-limit;}}if(needToMove){if(Math.abs(this.cameraDirection.x)1){this.cameraRotation.x+=-this._offsetY/this.angularSensibility;}else{var speed=this._computeLocalCameraSpeed();var direction=new BABYLON.Vector3(0,0,speed*this._offsetY/this.moveSensibility);BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,0,this._cameraRotationMatrix);this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction,this._cameraRotationMatrix));}};return TouchCamera;})(BABYLON.FreeCamera);BABYLON.TouchCamera=TouchCamera;})(BABYLON||(BABYLON={}));var __extends=this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d;}__.prototype=b.prototype;d.prototype=new __();};var BABYLON;(function(BABYLON){var DeviceOrientationCamera=(function(_super){__extends(DeviceOrientationCamera,_super);function DeviceOrientationCamera(name,position,scene){var _this=this;_super.call(this,name,position,scene);this._offsetX=null;this._offsetY=null;this._orientationGamma=0;this._orientationBeta=0;this._initialOrientationGamma=0;this._initialOrientationBeta=0;this.angularSensibility=10000.0;this.moveSensibility=50.0;window.addEventListener("resize",function(){_this._initialOrientationGamma=null;},false);}DeviceOrientationCamera.prototype.attachControl=function(canvas,noPreventDefault){var _this=this;if(this._attachedCanvas){return;}this._attachedCanvas=canvas;if(!this._orientationChanged){this._orientationChanged=function(evt){if(!_this._initialOrientationGamma){_this._initialOrientationGamma=evt.gamma;_this._initialOrientationBeta=evt.beta;}_this._orientationGamma=evt.gamma;_this._orientationBeta=evt.beta;_this._offsetY=(_this._initialOrientationBeta-_this._orientationBeta);_this._offsetX=(_this._initialOrientationGamma-_this._orientationGamma);};}window.addEventListener("deviceorientation",this._orientationChanged);};DeviceOrientationCamera.prototype.detachControl=function(canvas){if(this._attachedCanvas!=canvas){return;}window.removeEventListener("deviceorientation",this._orientationChanged);this._attachedCanvas=null;this._orientationGamma=0;this._orientationBeta=0;this._initialOrientationGamma=0;this._initialOrientationBeta=0;};DeviceOrientationCamera.prototype._checkInputs=function(){if(!this._offsetX){return;}this.cameraRotation.y-=this._offsetX/this.angularSensibility;var speed=this._computeLocalCameraSpeed();var direction=new BABYLON.Vector3(0,0,speed*this._offsetY/this.moveSensibility);BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,0,this._cameraRotationMatrix);this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction,this._cameraRotationMatrix));};return DeviceOrientationCamera;})(BABYLON.FreeCamera);BABYLON.DeviceOrientationCamera=DeviceOrientationCamera;})(BABYLON||(BABYLON={}));var __extends=this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d;}__.prototype=b.prototype;d.prototype=new __();};var BABYLON;(function(BABYLON){var eventPrefix=BABYLON.Tools.GetPointerPrefix();var ArcRotateCamera=(function(_super){__extends(ArcRotateCamera,_super);function ArcRotateCamera(name,alpha,beta,radius,target,scene){_super.call(this,name,BABYLON.Vector3.Zero(),scene);this.alpha=alpha;this.beta=beta;this.radius=radius;this.target=target;this.inertialAlphaOffset=0;this.inertialBetaOffset=0;this.inertialRadiusOffset=0;this.lowerAlphaLimit=null;this.upperAlphaLimit=null;this.lowerBetaLimit=0.01;this.upperBetaLimit=Math.PI;this.lowerRadiusLimit=null;this.upperRadiusLimit=null;this.angularSensibility=1000.0;this.wheelPrecision=3.0;this.keysUp=[38];this.keysDown=[40];this.keysLeft=[37];this.keysRight=[39];this.zoomOnFactor=1;this._keys=[];this._viewMatrix=new BABYLON.Matrix();this.checkCollisions=false;this.collisionRadius=new BABYLON.Vector3(0.5,0.5,0.5);this._collider=new BABYLON.Collider();this._previousPosition=BABYLON.Vector3.Zero();this._collisionVelocity=BABYLON.Vector3.Zero();this._newPosition=BABYLON.Vector3.Zero();this.getViewMatrix();}ArcRotateCamera.prototype._getTargetPosition=function(){return this.target.position||this.target;};ArcRotateCamera.prototype._initCache=function(){_super.prototype._initCache.call(this);this._cache.target=new BABYLON.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);this._cache.alpha=undefined;this._cache.beta=undefined;this._cache.radius=undefined;};ArcRotateCamera.prototype._updateCache=function(ignoreParentClass){if(!ignoreParentClass){_super.prototype._updateCache.call(this);}this._cache.target.copyFrom(this._getTargetPosition());this._cache.alpha=this.alpha;this._cache.beta=this.beta;this._cache.radius=this.radius;};ArcRotateCamera.prototype._isSynchronizedViewMatrix=function(){if(!_super.prototype._isSynchronizedViewMatrix.call(this))return false;return this._cache.target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius;};ArcRotateCamera.prototype.attachControl=function(element,noPreventDefault){var _this=this;var previousPosition;var pointerId;if(this._attachedElement){return;}this._attachedElement=element;var engine=this.getEngine();if(this._onPointerDown===undefined){this._onPointerDown=function(evt){if(pointerId){return;}pointerId=evt.pointerId;previousPosition={x:evt.clientX,y:evt.clientY};if(!noPreventDefault){evt.preventDefault();}};this._onPointerUp=function(evt){previousPosition=null;pointerId=null;if(!noPreventDefault){evt.preventDefault();}};this._onPointerMove=function(evt){if(!previousPosition){return;}if(pointerId!==evt.pointerId){return;}var offsetX=evt.clientX-previousPosition.x;var offsetY=evt.clientY-previousPosition.y;_this.inertialAlphaOffset-=offsetX/_this.angularSensibility;_this.inertialBetaOffset-=offsetY/_this.angularSensibility;previousPosition={x:evt.clientX,y:evt.clientY};if(!noPreventDefault){evt.preventDefault();}};this._onMouseMove=function(evt){if(!engine.isPointerLock){return;}var offsetX=evt.movementX||evt.mozMovementX||evt.webkitMovementX||evt.msMovementX||0;var offsetY=evt.movementY||evt.mozMovementY||evt.webkitMovementY||evt.msMovementY||0;_this.inertialAlphaOffset-=offsetX/_this.angularSensibility;_this.inertialBetaOffset-=offsetY/_this.angularSensibility;if(!noPreventDefault){evt.preventDefault();}};this._wheel=function(event){var delta=0;if(event.wheelDelta){delta=event.wheelDelta/(_this.wheelPrecision*40);}else if(event.detail){delta=-event.detail/_this.wheelPrecision;}if(delta)_this.inertialRadiusOffset+=delta;if(event.preventDefault){if(!noPreventDefault){event.preventDefault();}}};this._onKeyDown=function(evt){if(_this.keysUp.indexOf(evt.keyCode)!==-1||_this.keysDown.indexOf(evt.keyCode)!==-1||_this.keysLeft.indexOf(evt.keyCode)!==-1||_this.keysRight.indexOf(evt.keyCode)!==-1){var index=_this._keys.indexOf(evt.keyCode);if(index===-1){_this._keys.push(evt.keyCode);}if(evt.preventDefault){if(!noPreventDefault){evt.preventDefault();}}}};this._onKeyUp=function(evt){if(_this.keysUp.indexOf(evt.keyCode)!==-1||_this.keysDown.indexOf(evt.keyCode)!==-1||_this.keysLeft.indexOf(evt.keyCode)!==-1||_this.keysRight.indexOf(evt.keyCode)!==-1){var index=_this._keys.indexOf(evt.keyCode);if(index>=0){_this._keys.splice(index,1);}if(evt.preventDefault){if(!noPreventDefault){evt.preventDefault();}}}};this._onLostFocus=function(){_this._keys=[];pointerId=null;};this._onGestureStart=function(e){if(window.MSGesture===undefined){return;}if(!_this._MSGestureHandler){_this._MSGestureHandler=new MSGesture();_this._MSGestureHandler.target=element;}_this._MSGestureHandler.addPointer(e.pointerId);};this._onGesture=function(e){_this.radius*=e.scale;if(e.preventDefault){if(!noPreventDefault){e.stopPropagation();e.preventDefault();}}};this._reset=function(){_this._keys=[];_this.inertialAlphaOffset=0;_this.inertialBetaOffset=0;_this.inertialRadiusOffset=0;previousPosition=null;pointerId=null;};}element.addEventListener(eventPrefix+"down",this._onPointerDown,false);element.addEventListener(eventPrefix+"up",this._onPointerUp,false);element.addEventListener(eventPrefix+"out",this._onPointerUp,false);element.addEventListener(eventPrefix+"move",this._onPointerMove,false);element.addEventListener("mousemove",this._onMouseMove,false);element.addEventListener("MSPointerDown",this._onGestureStart,false);element.addEventListener("MSGestureChange",this._onGesture,false);element.addEventListener('mousewheel',this._wheel,false);element.addEventListener('DOMMouseScroll',this._wheel,false);BABYLON.Tools.RegisterTopRootEvents([{name:"keydown",handler:this._onKeyDown},{name:"keyup",handler:this._onKeyUp},{name:"blur",handler:this._onLostFocus}]);};ArcRotateCamera.prototype.detachControl=function(element){if(this._attachedElement!=element){return;}element.removeEventListener(eventPrefix+"down",this._onPointerDown);element.removeEventListener(eventPrefix+"up",this._onPointerUp);element.removeEventListener(eventPrefix+"out",this._onPointerUp);element.removeEventListener(eventPrefix+"move",this._onPointerMove);element.removeEventListener("mousemove",this._onMouseMove);element.removeEventListener("MSPointerDown",this._onGestureStart);element.removeEventListener("MSGestureChange",this._onGesture);element.removeEventListener('mousewheel',this._wheel);element.removeEventListener('DOMMouseScroll',this._wheel);BABYLON.Tools.UnregisterTopRootEvents([{name:"keydown",handler:this._onKeyDown},{name:"keyup",handler:this._onKeyUp},{name:"blur",handler:this._onLostFocus}]);this._MSGestureHandler=null;this._attachedElement=null;if(this._reset){this._reset();}};ArcRotateCamera.prototype._update=function(){for(var index=0;indexthis.upperAlphaLimit){this.alpha=this.upperAlphaLimit;}if(this.lowerBetaLimit&&this.betathis.upperBetaLimit){this.beta=this.upperBetaLimit;}if(this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit){this.radius=this.upperRadiusLimit;}};ArcRotateCamera.prototype.setPosition=function(position){var radiusv3=position.subtract(this._getTargetPosition());this.radius=radiusv3.length();this.alpha=Math.acos(radiusv3.x/Math.sqrt(Math.pow(radiusv3.x,2)+Math.pow(radiusv3.z,2)));if(radiusv3.z<0){this.alpha=2*Math.PI-this.alpha;}this.beta=Math.acos(radiusv3.y/this.radius);};ArcRotateCamera.prototype._getViewMatrix=function(){var cosa=Math.cos(this.alpha);var sina=Math.sin(this.alpha);var cosb=Math.cos(this.beta);var sinb=Math.sin(this.beta);var target=this._getTargetPosition();target.addToRef(new BABYLON.Vector3(this.radius*cosa*sinb,this.radius*cosb,this.radius*sina*sinb),this.position);if(this.checkCollisions){this._collider.radius=this.collisionRadius;this.position.subtractToRef(this._previousPosition,this._collisionVelocity);this.getScene()._getNewPosition(this._previousPosition,this._collisionVelocity,this._collider,3,this._newPosition);if(!this._newPosition.equalsWithEpsilon(this.position)){this.position.copyFrom(this._previousPosition);this.alpha=this._previousAlpha;this.beta=this._previousBeta;this.radius=this._previousRadius;if(this.onCollide){this.onCollide(this._collider.collidedMesh);}}}BABYLON.Matrix.LookAtLHToRef(this.position,target,this.upVector,this._viewMatrix);this._previousAlpha=this.alpha;this._previousBeta=this.beta;this._previousRadius=this.radius;this._previousPosition.copyFrom(this.position);return this._viewMatrix;};ArcRotateCamera.prototype.zoomOn=function(meshes){meshes=meshes||this.getScene().meshes;var minMaxVector=BABYLON.Mesh.MinMax(meshes);var distance=BABYLON.Vector3.Distance(minMaxVector.min,minMaxVector.max);this.radius=distance*this.zoomOnFactor;this.focusOn({min:minMaxVector.min,max:minMaxVector.max,distance:distance});};ArcRotateCamera.prototype.focusOn=function(meshesOrMinMaxVectorAndDistance){var meshesOrMinMaxVector;var distance;if(meshesOrMinMaxVectorAndDistance.min===undefined){meshesOrMinMaxVector=meshesOrMinMaxVectorAndDistance||this.getScene().meshes;meshesOrMinMaxVector=BABYLON.Mesh.MinMax(meshesOrMinMaxVector);distance=BABYLON.Vector3.Distance(meshesOrMinMaxVector.min,meshesOrMinMaxVector.max);}else{meshesOrMinMaxVector=meshesOrMinMaxVectorAndDistance;distance=meshesOrMinMaxVectorAndDistance.distance;}this.target=BABYLON.Mesh.Center(meshesOrMinMaxVector);this.maxZ=distance*2;};return ArcRotateCamera;})(BABYLON.Camera);BABYLON.ArcRotateCamera=ArcRotateCamera;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var Scene=(function(){function Scene(engine){this.autoClear=true;this.clearColor=new BABYLON.Color3(0.2,0.2,0.3);this.ambientColor=new BABYLON.Color3(0,0,0);this.forceWireframe=false;this.cameraToUseForPointers=null;this.fogMode=BABYLON.Scene.FOGMODE_NONE;this.fogColor=new BABYLON.Color3(0.2,0.2,0.3);this.fogDensity=0.1;this.fogStart=0;this.fogEnd=1000.0;this.lightsEnabled=true;this.lights=new Array();this.cameras=new Array();this.activeCameras=new Array();this.meshes=new Array();this._geometries=new Array();this.materials=new Array();this.multiMaterials=new Array();this.defaultMaterial=new BABYLON.StandardMaterial("default material",this);this.texturesEnabled=true;this.textures=new Array();this.particlesEnabled=true;this.particleSystems=new Array();this.spriteManagers=new Array();this.layers=new Array();this.skeletons=new Array();this.lensFlareSystems=new Array();this.collisionsEnabled=true;this.gravity=new BABYLON.Vector3(0,-9.0,0);this.postProcessesEnabled=true;this.renderTargetsEnabled=true;this.customRenderTargets=new Array();this.importedMeshesFiles=new Array();this._actionManagers=new Array();this._meshesForIntersections=new BABYLON.SmartArray(256);this._totalVertices=0;this._activeVertices=0;this._activeParticles=0;this._lastFrameDuration=0;this._evaluateActiveMeshesDuration=0;this._renderTargetsDuration=0;this._particlesDuration=0;this._renderDuration=0;this._spritesDuration=0;this._animationRatio=0;this._renderId=0;this._executeWhenReadyTimeoutId=-1;this._toBeDisposed=new BABYLON.SmartArray(256);this._onReadyCallbacks=new Array();this._pendingData=[];this._onBeforeRenderCallbacks=new Array();this._activeMeshes=new BABYLON.SmartArray(256);this._processedMaterials=new BABYLON.SmartArray(256);this._renderTargets=new BABYLON.SmartArray(256);this._activeParticleSystems=new BABYLON.SmartArray(256);this._activeSkeletons=new BABYLON.SmartArray(32);this._activeAnimatables=new Array();this._transformMatrix=BABYLON.Matrix.Zero();this._scaledPosition=BABYLON.Vector3.Zero();this._scaledVelocity=BABYLON.Vector3.Zero();this._engine=engine;engine.scenes.push(this);this._renderingManager=new BABYLON.RenderingManager(this);this.postProcessManager=new BABYLON.PostProcessManager(this);this.postProcessRenderPipelineManager=new BABYLON.PostProcessRenderPipelineManager();this._boundingBoxRenderer=new BABYLON.BoundingBoxRenderer(this);this.attachControl();}Object.defineProperty(Scene.prototype,"meshUnderPointer",{get:function(){return this._meshUnderPointer;},enumerable:true,configurable:true});Object.defineProperty(Scene.prototype,"pointerX",{get:function(){return this._pointerX;},enumerable:true,configurable:true});Object.defineProperty(Scene.prototype,"pointerY",{get:function(){return this._pointerY;},enumerable:true,configurable:true});Scene.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer;};Scene.prototype.getEngine=function(){return this._engine;};Scene.prototype.getTotalVertices=function(){return this._totalVertices;};Scene.prototype.getActiveVertices=function(){return this._activeVertices;};Scene.prototype.getActiveParticles=function(){return this._activeParticles;};Scene.prototype.getLastFrameDuration=function(){return this._lastFrameDuration;};Scene.prototype.getEvaluateActiveMeshesDuration=function(){return this._evaluateActiveMeshesDuration;};Scene.prototype.getActiveMeshes=function(){return this._activeMeshes;};Scene.prototype.getRenderTargetsDuration=function(){return this._renderTargetsDuration;};Scene.prototype.getRenderDuration=function(){return this._renderDuration;};Scene.prototype.getParticlesDuration=function(){return this._particlesDuration;};Scene.prototype.getSpritesDuration=function(){return this._spritesDuration;};Scene.prototype.getAnimationRatio=function(){return this._animationRatio;};Scene.prototype.getRenderId=function(){return this._renderId;};Scene.prototype._updatePointerPosition=function(evt){var canvasRect=this._engine.getRenderingCanvasClientRect();this._pointerX=evt.clientX-canvasRect.left;this._pointerY=evt.clientY-canvasRect.top;if(this.cameraToUseForPointers){this._pointerX=this._pointerX-this.cameraToUseForPointers.viewport.x*this._engine.getRenderWidth();this._pointerY=this._pointerY-this.cameraToUseForPointers.viewport.y*this._engine.getRenderHeight();}};Scene.prototype.attachControl=function(){var _this=this;this._onPointerMove=function(evt){var canvas=_this._engine.getRenderingCanvas();_this._updatePointerPosition(evt);var pickResult=_this.pick(_this._pointerX,_this._pointerY,function(mesh){return mesh.isPickable&&mesh.isVisible&&mesh.isReady()&&mesh.actionManager&&mesh.actionManager.hasPointerTriggers;},false,_this.cameraToUseForPointers);if(pickResult.hit){_this.setPointerOverMesh(pickResult.pickedMesh);canvas.style.cursor="pointer";_this._meshUnderPointer=pickResult.pickedMesh;}else{_this.setPointerOverMesh(null);canvas.style.cursor="";_this._meshUnderPointer=null;}};this._onPointerDown=function(evt){var predicate=null;if(!_this.onPointerDown){predicate=function(mesh){return mesh.isPickable&&mesh.isVisible&&mesh.isReady()&&mesh.actionManager&&mesh.actionManager.hasPickTriggers;};}_this._updatePointerPosition(evt);var pickResult=_this.pick(_this._pointerX,_this._pointerY,predicate,false,_this.cameraToUseForPointers);if(pickResult.hit){if(pickResult.pickedMesh.actionManager){switch(evt.button){case 0:pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger,BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));break;case 1:pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger,BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));break;case 2:pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger,BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));break;}pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger,BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));}}if(_this.onPointerDown){_this.onPointerDown(evt,pickResult);}};this._onKeyDown=function(evt){if(_this.actionManager){_this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger,BABYLON.ActionEvent.CreateNewFromScene(_this,evt));}};this._onKeyUp=function(evt){if(_this.actionManager){_this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger,BABYLON.ActionEvent.CreateNewFromScene(_this,evt));}};var eventPrefix=BABYLON.Tools.GetPointerPrefix();this._engine.getRenderingCanvas().addEventListener(eventPrefix+"move",this._onPointerMove,false);this._engine.getRenderingCanvas().addEventListener(eventPrefix+"down",this._onPointerDown,false);window.addEventListener("keydown",this._onKeyDown,false);window.addEventListener("keyup",this._onKeyUp,false);};Scene.prototype.detachControl=function(){var eventPrefix=BABYLON.Tools.GetPointerPrefix();this._engine.getRenderingCanvas().removeEventListener(eventPrefix+"move",this._onPointerMove);this._engine.getRenderingCanvas().removeEventListener(eventPrefix+"down",this._onPointerDown);window.removeEventListener("keydown",this._onKeyDown);window.removeEventListener("keyup",this._onKeyUp);};Scene.prototype.isReady=function(){if(this._pendingData.length>0){return false;}for(var index=0;index-1){this._onBeforeRenderCallbacks.splice(index,1);}};Scene.prototype._addPendingData=function(data){this._pendingData.push(data);};Scene.prototype._removePendingData=function(data){var index=this._pendingData.indexOf(data);if(index!==-1){this._pendingData.splice(index,1);}};Scene.prototype.getWaitingItemsCount=function(){return this._pendingData.length;};Scene.prototype.executeWhenReady=function(func){var _this=this;this._onReadyCallbacks.push(func);if(this._executeWhenReadyTimeoutId!==-1){return;}this._executeWhenReadyTimeoutId=setTimeout(function(){_this._checkIsReady();},150);};Scene.prototype._checkIsReady=function(){var _this=this;if(this.isReady()){this._onReadyCallbacks.forEach(function(func){func();});this._onReadyCallbacks=[];this._executeWhenReadyTimeoutId=-1;return;}this._executeWhenReadyTimeoutId=setTimeout(function(){_this._checkIsReady();},150);};Scene.prototype.beginAnimation=function(target,from,to,loop,speedRatio,onAnimationEnd,animatable){if(speedRatio===undefined){speedRatio=1.0;}this.stopAnimation(target);if(!animatable){animatable=new BABYLON.Animatable(this,target,from,to,loop,speedRatio,onAnimationEnd);}if(target.animations){animatable.appendAnimations(target,target.animations);}if(target.getAnimatables){var animatables=target.getAnimatables();for(var index=0;index=0;index--){if(this.meshes[index].id===id){return this.meshes[index];}}return null;};Scene.prototype.getLastEntryByID=function(id){for(var index=this.meshes.length-1;index>=0;index--){if(this.meshes[index].id===id){return this.meshes[index];}}for(index=this.cameras.length-1;index>=0;index--){if(this.cameras[index].id===id){return this.cameras[index];}}for(index=this.lights.length-1;index>=0;index--){if(this.lights[index].id===id){return this.lights[index];}}return null;};Scene.prototype.getMeshByName=function(name){for(var index=0;index=0;index--){if(this.skeletons[index].id===id){return this.skeletons[index];}}return null;};Scene.prototype.getSkeletonById=function(id){for(var index=0;index0&&((mesh.layerMask&this.activeCamera.layerMask)!=0)&&mesh.isInFrustum(this._frustumPlanes)){this._activeMeshes.push(mesh);mesh._activate(this._renderId);this._activeMesh(mesh);}}var beforeParticlesDate=new Date().getTime();if(this.particlesEnabled){for(var particleIndex=0;particleIndex0){engine.restoreDefaultFramebuffer();}this._renderTargetsDuration=new Date().getTime()-beforeRenderTargetDate;this.postProcessManager._prepareFrame();var beforeRenderDate=new Date().getTime();if(this.layers.length){engine.setDepthBuffer(false);var layerIndex;var layer;for(layerIndex=0;layerIndex-1&&action.trigger==BABYLON.ActionManager.OnIntersectionExitTrigger){sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger,BABYLON.ActionEvent.CreateNew(sourceMesh));var indexOfOther=sourceMesh._intersectionsInProgress.indexOf(otherMesh);if(indexOfOther>-1){sourceMesh._intersectionsInProgress.splice(indexOfOther,1);}}}}}};Scene.prototype.render=function(){var startDate=new Date().getTime();this._particlesDuration=0;this._spritesDuration=0;this._activeParticles=0;this._renderDuration=0;this._evaluateActiveMeshesDuration=0;this._totalVertices=0;this._activeVertices=0;this._meshesForIntersections.reset();if(this.actionManager){this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger,null);}if(this.beforeRender){this.beforeRender();}for(var callbackIndex=0;callbackIndex0){var currentRenderId=this._renderId;for(var cameraIndex=0;cameraIndex=maximumRetry){finalPosition.copyFrom(position);return;}collider._initialize(position,velocity,closeDistance);for(var index=0;index=pickingInfo.distance)continue;pickingInfo=result;if(fastCheck){break;}}return pickingInfo||new BABYLON.PickingInfo();};Scene.prototype.pick=function(x,y,predicate,fastCheck,camera){var _this=this;return this._internalPick(function(world){return _this.createPickingRay(x,y,world,camera);},predicate,fastCheck);};Scene.prototype.pickWithRay=function(ray,predicate,fastCheck){var _this=this;return this._internalPick(function(world){if(!_this._pickWithRayInverseMatrix){_this._pickWithRayInverseMatrix=BABYLON.Matrix.Identity();}world.invertToRef(_this._pickWithRayInverseMatrix);return BABYLON.Ray.Transform(ray,_this._pickWithRayInverseMatrix);},predicate,fastCheck);};Scene.prototype.setPointerOverMesh=function(mesh){if(this._pointerOverMesh===mesh){return;}if(this._pointerOverMesh&&this._pointerOverMesh.actionManager){this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger,BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));}this._pointerOverMesh=mesh;if(this._pointerOverMesh&&this._pointerOverMesh.actionManager){this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger,BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));}};Scene.prototype.getPointerOverMesh=function(){return this._pointerOverMesh;};Scene.prototype.getPhysicsEngine=function(){return this._physicsEngine;};Scene.prototype.enablePhysics=function(gravity,plugin){if(this._physicsEngine){return true;}this._physicsEngine=new BABYLON.PhysicsEngine(plugin);if(!this._physicsEngine.isSupported()){this._physicsEngine=null;return false;}this._physicsEngine._initialize(gravity);return true;};Scene.prototype.disablePhysicsEngine=function(){if(!this._physicsEngine){return;}this._physicsEngine.dispose();this._physicsEngine=undefined;};Scene.prototype.isPhysicsEnabled=function(){return this._physicsEngine!==undefined;};Scene.prototype.setGravity=function(gravity){if(!this._physicsEngine){return;}this._physicsEngine._setGravity(gravity);};Scene.prototype.createCompoundImpostor=function(parts,options){if(parts.parts){options=parts;parts=parts.parts;}if(!this._physicsEngine){return null;}for(var index=0;indexBABYLON.Engine.CollisionsEpsilon){this.position.addInPlace(this._diffPositionForCollisions);}};/***This function will create an octree to help select the right submeshes for rendering,picking and collisions*Please note that you must have a decent number of submeshes to get performance improvements when using octree*/AbstractMesh.prototype.createOrUpdateSubmeshesOctree=function(maxCapacity,maxDepth){if(typeof maxCapacity==="undefined"){maxCapacity=64;}if(typeof maxDepth==="undefined"){maxDepth=2;}if(!this._submeshesOctree){this._submeshesOctree=new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes,maxCapacity,maxDepth);}this.computeWorldMatrix(true);var bbox=this.getBoundingInfo().boundingBox;this._submeshesOctree.update(bbox.minimumWorld,bbox.maximumWorld,this.subMeshes);return this._submeshesOctree;};AbstractMesh.prototype._collideForSubMesh=function(subMesh,transformMatrix,collider){this._generatePointsArray();if(!subMesh._lastColliderWorldVertices||!subMesh._lastColliderTransformMatrix.equals(transformMatrix)){subMesh._lastColliderTransformMatrix=transformMatrix.clone();subMesh._lastColliderWorldVertices=[];subMesh._trianglePlanes=[];var start=subMesh.verticesStart;var end=(subMesh.verticesStart+subMesh.verticesCount);for(var i=start;i1&&!subMesh._checkCollision(collider))continue;this._collideForSubMesh(subMesh,transformMatrix,collider);}};AbstractMesh.prototype._checkCollision=function(collider){if(!this._boundingInfo._checkCollision(collider))return;BABYLON.Matrix.ScalingToRef(1.0/collider.radius.x,1.0/collider.radius.y,1.0/collider.radius.z,this._collisionsScalingMatrix);this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix,this._collisionsTransformMatrix);this._processCollisionsForSubMeshes(collider,this._collisionsTransformMatrix);};AbstractMesh.prototype._generatePointsArray=function(){return false;};AbstractMesh.prototype.intersects=function(ray,fastCheck){var pickingInfo=new BABYLON.PickingInfo();if(!this.subMeshes||!this._boundingInfo||!ray.intersectsSphere(this._boundingInfo.boundingSphere)||!ray.intersectsBox(this._boundingInfo.boundingBox)){return pickingInfo;}if(!this._generatePointsArray()){return pickingInfo;}var intersectInfo=null;var subMeshes;var len;if(this._submeshesOctree&&this.useOctreeForPicking){var worldRay=BABYLON.Ray.Transform(ray,this.getWorldMatrix());var intersections=this._submeshesOctree.intersectsRay(worldRay);len=intersections.length;subMeshes=intersections.data;}else{subMeshes=this.subMeshes;len=subMeshes.length;}for(var index=0;index1&&!subMesh.canIntersects(ray))continue;var currentIntersectInfo=subMesh.intersects(ray,this._positions,this.getIndices(),fastCheck);if(currentIntersectInfo){if(fastCheck||!intersectInfo||currentIntersectInfo.distance=totalIndices){break;}BABYLON.SubMesh.CreateFromIndices(0,offset,Math.min(subdivisionSize,totalIndices-offset),this);offset+=subdivisionSize;}this.synchronizeInstances();};Mesh.prototype.setVerticesData=function(kind,data,updatable){if(kind instanceof Array){var temp=data;data=kind;kind=temp;BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");}if(!this._geometry){var vertexData=new BABYLON.VertexData();vertexData.set(data,kind);var scene=this.getScene();new BABYLON.Geometry(BABYLON.Geometry.RandomId(),scene,vertexData,updatable,this);}else{this._geometry.setVerticesData(kind,data,updatable);}};Mesh.prototype.updateVerticesData=function(kind,data,updateExtends,makeItUnique){if(!this._geometry){return;}if(!makeItUnique){this._geometry.updateVerticesData(kind,data,updateExtends);}else{this.makeGeometryUnique();this.updateVerticesData(kind,data,updateExtends,false);}};Mesh.prototype.makeGeometryUnique=function(){if(!this._geometry){return;}var geometry=this._geometry.copy(BABYLON.Geometry.RandomId());geometry.applyToMesh(this);};Mesh.prototype.setIndices=function(indices){if(!this._geometry){var vertexData=new BABYLON.VertexData();vertexData.indices=indices;var scene=this.getScene();new BABYLON.Geometry(BABYLON.Geometry.RandomId(),scene,vertexData,false,this);}else{this._geometry.setIndices(indices);}};Mesh.prototype._bind=function(subMesh,effect,wireframe){var engine=this.getScene().getEngine();var indexToBind=this._geometry.getIndexBuffer();if(wireframe){indexToBind=subMesh.getLinesIndexBuffer(this.getIndices(),engine);}engine.bindMultiBuffers(this._geometry.getVertexBuffers(),indexToBind,effect);};Mesh.prototype._draw=function(subMesh,useTriangles,instancesCount){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._geometry.getIndexBuffer()){return;}var engine=this.getScene().getEngine();engine.draw(useTriangles,useTriangles?subMesh.indexStart:0,useTriangles?subMesh.indexCount:subMesh.linesIndexCount,instancesCount);};Mesh.prototype.registerBeforeRender=function(func){this._onBeforeRenderCallbacks.push(func);};Mesh.prototype.unregisterBeforeRender=function(func){var index=this._onBeforeRenderCallbacks.indexOf(func);if(index>-1){this._onBeforeRenderCallbacks.splice(index,1);}};Mesh.prototype.registerAfterRender=function(func){this._onAfterRenderCallbacks.push(func);};Mesh.prototype.unregisterAfterRender=function(func){var index=this._onAfterRenderCallbacks.indexOf(func);if(index>-1){this._onAfterRenderCallbacks.splice(index,1);}};Mesh.prototype._getInstancesRenderList=function(subMeshId){var scene=this.getScene();this._batchCache.mustReturn=false;this._batchCache.renderSelf[subMeshId]=this.isEnabled()&&this.isVisible;this._batchCache.visibleInstances[subMeshId]=null;if(this._visibleInstances){var currentRenderId=scene.getRenderId();this._batchCache.visibleInstances[subMeshId]=this._visibleInstances[currentRenderId];var selfRenderId=this._renderId;if(!this._batchCache.visibleInstances[subMeshId]&&this._visibleInstances.defaultRenderId){this._batchCache.visibleInstances[subMeshId]=this._visibleInstances[this._visibleInstances.defaultRenderId];currentRenderId=this._visibleInstances.defaultRenderId;selfRenderId=this._visibleInstances.selfDefaultRenderId;}if(this._batchCache.visibleInstances[subMeshId]&&this._batchCache.visibleInstances[subMeshId].length){if(this._renderIdForInstances[subMeshId]===currentRenderId){this._batchCache.mustReturn=true;return this._batchCache;}if(currentRenderId!==selfRenderId){this._batchCache.renderSelf[subMeshId]=false;}}this._renderIdForInstances[subMeshId]=currentRenderId;}return this._batchCache;};Mesh.prototype._renderWithInstances=function(subMesh,wireFrame,batch,effect,engine){var matricesCount=this.instances.length+1;var bufferSize=matricesCount*16*4;while(this._instancesBufferSizemaxVertexIndex)maxVertexIndex=vertexIndex;}return new BABYLON.SubMesh(materialIndex,minVertexIndex,maxVertexIndex-minVertexIndex+1,startIndex,indexCount,mesh,renderingMesh);};return SubMesh;})();BABYLON.SubMesh=SubMesh;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var BaseTexture=(function(){function BaseTexture(scene){this.delayLoadState=BABYLON.Engine.DELAYLOADSTATE_NONE;this.hasAlpha=false;this.getAlphaFromRGB=false;this.level=1;this.isCube=false;this.isRenderTarget=false;this.animations=new Array();this.coordinatesIndex=0;this.coordinatesMode=BABYLON.Texture.EXPLICIT_MODE;this.wrapU=BABYLON.Texture.WRAP_ADDRESSMODE;this.wrapV=BABYLON.Texture.WRAP_ADDRESSMODE;this.anisotropicFilteringLevel=4;this._scene=scene;this._scene.textures.push(this);}BaseTexture.prototype.getScene=function(){return this._scene;};BaseTexture.prototype.getTextureMatrix=function(){return null;};BaseTexture.prototype.getReflectionTextureMatrix=function(){return null;};BaseTexture.prototype.getInternalTexture=function(){return this._texture;};BaseTexture.prototype.isReady=function(){if(this.delayLoadState===BABYLON.Engine.DELAYLOADSTATE_NOTLOADED){return true;}if(this._texture){return this._texture.isReady;}return false;};BaseTexture.prototype.getSize=function(){if(this._texture._width){return{width:this._texture._width,height:this._texture._height};}if(this._texture._size){return{width:this._texture._size,height:this._texture._size};}return{width:0,height:0};};BaseTexture.prototype.getBaseSize=function(){if(!this.isReady())return{width:0,height:0};if(this._texture._size){return{width:this._texture._size,height:this._texture._size};}return{width:this._texture._baseWidth,height:this._texture._baseHeight};};BaseTexture.prototype._getFromCache=function(url,noMipmap){var texturesCache=this._scene.getEngine().getLoadedTexturesCache();for(var index=0;index=0){this._scene.textures.splice(index,1);}if(this._texture===undefined){return;}this.releaseInternalTexture();if(this.onDispose){this.onDispose();}};return BaseTexture;})();BABYLON.BaseTexture=BaseTexture;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var RenderingGroup=(function(){function RenderingGroup(index,scene){this.index=index;this._opaqueSubMeshes=new BABYLON.SmartArray(256);this._transparentSubMeshes=new BABYLON.SmartArray(256);this._alphaTestSubMeshes=new BABYLON.SmartArray(256);this._scene=scene;}RenderingGroup.prototype.render=function(customRenderFunction,beforeTransparents){if(customRenderFunction){customRenderFunction(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,beforeTransparents);return true;}if(this._opaqueSubMeshes.length===0&&this._alphaTestSubMeshes.length===0&&this._transparentSubMeshes.length===0){return false;}var engine=this._scene.getEngine();var subIndex;var submesh;for(subIndex=0;subIndexb._distanceToCamera){return-1;}return 0;});engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);for(subIndex=0;subIndex0||mesh.visibility<1.0){this._transparentSubMeshes.push(subMesh);}}else if(material.needAlphaTesting()){this._alphaTestSubMeshes.push(subMesh);}else{this._opaqueSubMeshes.push(subMesh);}};return RenderingGroup;})();BABYLON.RenderingGroup=RenderingGroup;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var RenderingManager=(function(){function RenderingManager(scene){this._renderingGroups=new Array();this._scene=scene;}RenderingManager.prototype._renderParticles=function(index,activeMeshes){if(this._scene._activeParticleSystems.length===0){return;}var beforeParticlesDate=new Date().getTime();for(var particleIndex=0;particleIndex 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n for (int i = 0; i<4; i++){\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[i] / 1500.0)) < depth.z){\n visibility -= 0.2;\n }\n }\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz * vBumpInfos.y;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}", defaultVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}", displayPassPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(passSampler, vUV);\n}", filterPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\n vec3 baseColor = texture2D(textureSampler, vUV).rgb;\n vec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\n gl_FragColor = vec4(updatedColor, 1.0);\n}", fxaaPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\n\nvoid main(){\n vec2 localTexelSize = texelSize;\n vec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\n vec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\n vec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\n vec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\n vec4 rgbM = texture2D(textureSampler, vUV);\n vec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n vec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\n float dirReduce = max(\n (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\n FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * localTexelSize;\n\n vec4 rgbA = 0.5 * (\n texture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\n texture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\n vec4 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(textureSampler, vUV + dir * -0.5) +\n texture2D(textureSampler, vUV + dir * 0.5));\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax)) {\n gl_FragColor = rgbA;\n }\n else {\n gl_FragColor = rgbB;\n }\n}", layerPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}", layerVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 textureMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\n gl_Position = vec4(position, 0.0, 1.0);\n}", legacydefaultPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}", legacydefaultVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}", lensFlarePixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}", lensFlareVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 viewportMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}", oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\n vec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\n float rSq = theta.x * theta.x + theta.y * theta.y;\n vec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n return LensCenter + Scale * rvector;\n}\n\n\n\nvoid main(void)\n{\n vec2 tc = HmdWarp(vUV);\n if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n else{\n gl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n }\n}", particlesPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n gl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}", particlesVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\n// Uniforms\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n float size = options.y;\n float angle = options.x;\n vec2 offset = options.zw;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n \n vColor = color;\n vUV = offset;\n\n // Clip plane\n#ifdef CLIPPLANE\n vec4 worldPos = invView * vec4(viewPos, 1.0);\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n}", passPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n gl_FragColor = texture2D(textureSampler, vUV);\n}", postprocessVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}", refractionPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\n// Parameters\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\n float ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\n vec2 uv = vUV - vec2(0.5);\n vec2 offset = uv * depth * ref;\n vec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\n gl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}", shadowMapPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(254.), vec4(255.)) / vec4(254.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z / gl_FragCoord.w;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}", shadowMapVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}", spritesPixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n if (alphaTest) \n {\n if (baseColor.a < 0.95)\n discard;\n }\n\n baseColor *= vColor;\n\n#ifdef FOG\n float fog = CalcFogFactor();\n baseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = baseColor;\n}", spritesVertexShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\n// Uniforms\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n \n float angle = options.x;\n float size = options.y;\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n\n // Color\n vColor = color;\n \n // Texture\n vec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\n vUV = (uvOffset + cellInfo.zw) * uvScale;\n\n // Fog\n#ifdef FOG\n fFogDistance = viewPos.z;\n#endif\n}", };return Effect;})();BABYLON.Effect=Effect;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var Material=(function(){function Material(name,scene,doNotAdd){this.name=name;this.checkReadyOnEveryCall=true;this.checkReadyOnlyOnce=false;this.state="";this.alpha=1.0;this.wireframe=false;this.backFaceCulling=true;this._wasPreviouslyReady=false;this.id=name;this._scene=scene;if(!doNotAdd){scene.materials.push(this);}}Material.prototype.isReady=function(mesh,useInstances){return true;};Material.prototype.getEffect=function(){return this._effect;};Material.prototype.getScene=function(){return this._scene;};Material.prototype.needAlphaBlending=function(){return(this.alpha<1.0);};Material.prototype.needAlphaTesting=function(){return false;};Material.prototype.getAlphaTestTexture=function(){return null;};Material.prototype.trackCreation=function(onCompiled,onError){};Material.prototype._preBind=function(){var engine=this._scene.getEngine();engine.enableEffect(this._effect);engine.setState(this.backFaceCulling);};Material.prototype.bind=function(world,mesh){};Material.prototype.bindOnlyWorldMatrix=function(world){};Material.prototype.unbind=function(){};Material.prototype.dispose=function(forceDisposeEffect){var index=this._scene.materials.indexOf(this);this._scene.materials.splice(index,1);if(forceDisposeEffect&&this._effect){this._scene.getEngine()._releaseEffect(this._effect);this._effect=null;}if(this.onDispose){this.onDispose();}};return Material;})();BABYLON.Material=Material;})(BABYLON||(BABYLON={}));var __extends=this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d;}__.prototype=b.prototype;d.prototype=new __();};var BABYLON;(function(BABYLON){var maxSimultaneousLights=4;var StandardMaterial=(function(_super){__extends(StandardMaterial,_super);function StandardMaterial(name,scene){var _this=this;_super.call(this,name,scene);this.ambientColor=new BABYLON.Color3(0,0,0);this.diffuseColor=new BABYLON.Color3(1,1,1);this.specularColor=new BABYLON.Color3(1,1,1);this.specularPower=64;this.emissiveColor=new BABYLON.Color3(0,0,0);this.useAlphaFromDiffuseTexture=false;this._cachedDefines=null;this._renderTargets=new BABYLON.SmartArray(16);this._worldViewProjectionMatrix=BABYLON.Matrix.Zero();this._globalAmbientColor=new BABYLON.Color3(0,0,0);this._baseColor=new BABYLON.Color3();this._scaledDiffuse=new BABYLON.Color3();this._scaledSpecular=new BABYLON.Color3();this.getRenderTargetTextures=function(){_this._renderTargets.reset();if(_this.reflectionTexture&&_this.reflectionTexture.isRenderTarget){_this._renderTargets.push(_this.reflectionTexture);}return _this._renderTargets;};}StandardMaterial.prototype.needAlphaBlending=function(){return(this.alpha<1.0)||(this.opacityTexture!=null)||this._shouldUseAlphaFromDiffuseTexture();};StandardMaterial.prototype.needAlphaTesting=function(){return this.diffuseTexture!=null&&this.diffuseTexture.hasAlpha&&!this.diffuseTexture.getAlphaFromRGB;};StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture=function(){return this.diffuseTexture!=null&&this.diffuseTexture.hasAlpha&&this.useAlphaFromDiffuseTexture;};StandardMaterial.prototype.getAlphaTestTexture=function(){return this.diffuseTexture;};StandardMaterial.prototype.isReady=function(mesh,useInstances){if(this.checkReadyOnlyOnce){if(this._wasPreviouslyReady){return true;}}var scene=this.getScene();if(!this.checkReadyOnEveryCall){if(this._renderId===scene.getRenderId()){return true;}}var engine=scene.getEngine();var defines=[];var optionalDefines=new Array();if(scene.texturesEnabled){if(this.diffuseTexture&&BABYLON.StandardMaterial.DiffuseTextureEnabled){if(!this.diffuseTexture.isReady()){return false;}else{defines.push("#define DIFFUSE");}}if(this.ambientTexture&&BABYLON.StandardMaterial.AmbientTextureEnabled){if(!this.ambientTexture.isReady()){return false;}else{defines.push("#define AMBIENT");}}if(this.opacityTexture&&BABYLON.StandardMaterial.OpacityTextureEnabled){if(!this.opacityTexture.isReady()){return false;}else{defines.push("#define OPACITY");if(this.opacityTexture.getAlphaFromRGB){defines.push("#define OPACITYRGB");}}}if(this.reflectionTexture&&BABYLON.StandardMaterial.ReflectionTextureEnabled){if(!this.reflectionTexture.isReady()){return false;}else{defines.push("#define REFLECTION");}}if(this.emissiveTexture&&BABYLON.StandardMaterial.EmissiveTextureEnabled){if(!this.emissiveTexture.isReady()){return false;}else{defines.push("#define EMISSIVE");}}if(this.specularTexture&&BABYLON.StandardMaterial.SpecularTextureEnabled){if(!this.specularTexture.isReady()){return false;}else{defines.push("#define SPECULAR");optionalDefines.push(defines[defines.length-1]);}}}if(scene.getEngine().getCaps().standardDerivatives&&this.bumpTexture&&BABYLON.StandardMaterial.BumpTextureEnabled){if(!this.bumpTexture.isReady()){return false;}else{defines.push("#define BUMP");optionalDefines.push(defines[defines.length-1]);}}if(scene.clipPlane){defines.push("#define CLIPPLANE");}if(engine.getAlphaTesting()){defines.push("#define ALPHATEST");}if(this._shouldUseAlphaFromDiffuseTexture()){defines.push("#define ALPHAFROMDIFFUSE");}if(scene.fogMode!==BABYLON.Scene.FOGMODE_NONE){defines.push("#define FOG");optionalDefines.push(defines[defines.length-1]);}var shadowsActivated=false;var lightIndex=0;if(scene.lightsEnabled){for(var index=0;index0){for(var excludedIndex=0;excludedIndex0){for(var includedOnlyIndex=0;includedOnlyIndex0){optionalDefines.push(defines[defines.length-1]);}var type;if(light instanceof BABYLON.SpotLight){type="#define SPOTLIGHT"+lightIndex;}else if(light instanceof BABYLON.HemisphericLight){type="#define HEMILIGHT"+lightIndex;}else{type="#define POINTDIRLIGHT"+lightIndex;}defines.push(type);if(lightIndex>0){optionalDefines.push(defines[defines.length-1]);}var shadowGenerator=light.getShadowGenerator();if(mesh&&mesh.receiveShadows&&shadowGenerator){defines.push("#define SHADOW"+lightIndex);if(lightIndex>0){optionalDefines.push(defines[defines.length-1]);}if(!shadowsActivated){defines.push("#define SHADOWS");shadowsActivated=true;}if(shadowGenerator.useVarianceShadowMap){defines.push("#define SHADOWVSM"+lightIndex);if(lightIndex>0){optionalDefines.push(defines[defines.length-1]);}}if(shadowGenerator.usePoissonSampling){defines.push("#define SHADOWPCF"+lightIndex);if(lightIndex>0){optionalDefines.push(defines[defines.length-1]);}}}lightIndex++;if(lightIndex==maxSimultaneousLights)break;}}var attribs=[BABYLON.VertexBuffer.PositionKind,BABYLON.VertexBuffer.NormalKind];if(mesh){if(mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)){attribs.push(BABYLON.VertexBuffer.UVKind);defines.push("#define UV1");}if(mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)){attribs.push(BABYLON.VertexBuffer.UV2Kind);defines.push("#define UV2");}if(mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)){attribs.push(BABYLON.VertexBuffer.ColorKind);defines.push("#define VERTEXCOLOR");}if(mesh.skeleton&&mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)&&mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)){attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);defines.push("#define BONES");defines.push("#define BonesPerMesh "+(mesh.skeleton.bones.length+1));defines.push("#define BONES4");optionalDefines.push(defines[defines.length-1]);}if(useInstances){defines.push("#define INSTANCES");attribs.push("world0");attribs.push("world1");attribs.push("world2");attribs.push("world3");}}var join=defines.join("\n");if(this._cachedDefines!=join){this._cachedDefines=join;var shaderName="default";if(!scene.getEngine().getCaps().standardDerivatives){shaderName="legacydefault";}this._effect=scene.getEngine().createEffect(shaderName,attribs,["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","vLightData0","vLightDiffuse0","vLightSpecular0","vLightDirection0","vLightGround0","lightMatrix0","vLightData1","vLightDiffuse1","vLightSpecular1","vLightDirection1","vLightGround1","lightMatrix1","vLightData2","vLightDiffuse2","vLightSpecular2","vLightDirection2","vLightGround2","lightMatrix2","vLightData3","vLightDiffuse3","vLightSpecular3","vLightDirection3","vLightGround3","lightMatrix3","vFogInfos","vFogColor","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","mBones","vClipPlane","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","darkness0","darkness1","darkness2","darkness3"],["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","shadowSampler0","shadowSampler1","shadowSampler2","shadowSampler3"],join,optionalDefines,this.onCompiled,this.onError);}if(!this._effect.isReady()){return false;}this._renderId=scene.getRenderId();this._wasPreviouslyReady=true;return true;};StandardMaterial.prototype.unbind=function(){if(this.reflectionTexture&&this.reflectionTexture.isRenderTarget){this._effect.setTexture("reflection2DSampler",null);}};StandardMaterial.prototype.bindOnlyWorldMatrix=function(world){this._effect.setMatrix("world",world);};StandardMaterial.prototype.bind=function(world,mesh){var scene=this.getScene();this._baseColor.copyFrom(this.diffuseColor);this.bindOnlyWorldMatrix(world);this._effect.setMatrix("viewProjection",scene.getTransformMatrix());if(mesh.skeleton&&mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)&&mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)){this._effect.setMatrices("mBones",mesh.skeleton.getTransformMatrices());}if(this.diffuseTexture&&BABYLON.StandardMaterial.DiffuseTextureEnabled){this._effect.setTexture("diffuseSampler",this.diffuseTexture);this._effect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level);this._effect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix());this._baseColor.copyFromFloats(1,1,1);}if(this.ambientTexture&&BABYLON.StandardMaterial.AmbientTextureEnabled){this._effect.setTexture("ambientSampler",this.ambientTexture);this._effect.setFloat2("vAmbientInfos",this.ambientTexture.coordinatesIndex,this.ambientTexture.level);this._effect.setMatrix("ambientMatrix",this.ambientTexture.getTextureMatrix());}if(this.opacityTexture&&BABYLON.StandardMaterial.OpacityTextureEnabled){this._effect.setTexture("opacitySampler",this.opacityTexture);this._effect.setFloat2("vOpacityInfos",this.opacityTexture.coordinatesIndex,this.opacityTexture.level);this._effect.setMatrix("opacityMatrix",this.opacityTexture.getTextureMatrix());}if(this.reflectionTexture&&BABYLON.StandardMaterial.ReflectionTextureEnabled){if(this.reflectionTexture.isCube){this._effect.setTexture("reflectionCubeSampler",this.reflectionTexture);}else{this._effect.setTexture("reflection2DSampler",this.reflectionTexture);}this._effect.setMatrix("reflectionMatrix",this.reflectionTexture.getReflectionTextureMatrix());this._effect.setFloat3("vReflectionInfos",this.reflectionTexture.coordinatesMode,this.reflectionTexture.level,this.reflectionTexture.isCube?1:0);}if(this.emissiveTexture&&BABYLON.StandardMaterial.EmissiveTextureEnabled){this._effect.setTexture("emissiveSampler",this.emissiveTexture);this._effect.setFloat2("vEmissiveInfos",this.emissiveTexture.coordinatesIndex,this.emissiveTexture.level);this._effect.setMatrix("emissiveMatrix",this.emissiveTexture.getTextureMatrix());}if(this.specularTexture&&BABYLON.StandardMaterial.SpecularTextureEnabled){this._effect.setTexture("specularSampler",this.specularTexture);this._effect.setFloat2("vSpecularInfos",this.specularTexture.coordinatesIndex,this.specularTexture.level);this._effect.setMatrix("specularMatrix",this.specularTexture.getTextureMatrix());}if(this.bumpTexture&&scene.getEngine().getCaps().standardDerivatives&&BABYLON.StandardMaterial.BumpTextureEnabled){this._effect.setTexture("bumpSampler",this.bumpTexture);this._effect.setFloat2("vBumpInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level);this._effect.setMatrix("bumpMatrix",this.bumpTexture.getTextureMatrix());}scene.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor);this._effect.setVector3("vEyePosition",scene.activeCamera.position);this._effect.setColor3("vAmbientColor",this._globalAmbientColor);this._effect.setColor4("vDiffuseColor",this._baseColor,this.alpha*mesh.visibility);this._effect.setColor4("vSpecularColor",this.specularColor,this.specularPower);this._effect.setColor3("vEmissiveColor",this.emissiveColor);if(scene.lightsEnabled){var lightIndex=0;for(var index=0;index0){results.push(this.diffuseTexture);}if(this.ambientTexture&&this.ambientTexture.animations&&this.ambientTexture.animations.length>0){results.push(this.ambientTexture);}if(this.opacityTexture&&this.opacityTexture.animations&&this.opacityTexture.animations.length>0){results.push(this.opacityTexture);}if(this.reflectionTexture&&this.reflectionTexture.animations&&this.reflectionTexture.animations.length>0){results.push(this.reflectionTexture);}if(this.emissiveTexture&&this.emissiveTexture.animations&&this.emissiveTexture.animations.length>0){results.push(this.emissiveTexture);}if(this.specularTexture&&this.specularTexture.animations&&this.specularTexture.animations.length>0){results.push(this.specularTexture);}if(this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0){results.push(this.bumpTexture);}return results;};StandardMaterial.prototype.dispose=function(forceDisposeEffect){if(this.diffuseTexture){this.diffuseTexture.dispose();}if(this.ambientTexture){this.ambientTexture.dispose();}if(this.opacityTexture){this.opacityTexture.dispose();}if(this.reflectionTexture){this.reflectionTexture.dispose();}if(this.emissiveTexture){this.emissiveTexture.dispose();}if(this.specularTexture){this.specularTexture.dispose();}if(this.bumpTexture){this.bumpTexture.dispose();}_super.prototype.dispose.call(this,forceDisposeEffect);};StandardMaterial.prototype.clone=function(name){var newStandardMaterial=new BABYLON.StandardMaterial(name,this.getScene());newStandardMaterial.checkReadyOnEveryCall=this.checkReadyOnEveryCall;newStandardMaterial.alpha=this.alpha;newStandardMaterial.wireframe=this.wireframe;newStandardMaterial.backFaceCulling=this.backFaceCulling;if(this.diffuseTexture&&this.diffuseTexture.clone){newStandardMaterial.diffuseTexture=this.diffuseTexture.clone();}if(this.ambientTexture&&this.ambientTexture.clone){newStandardMaterial.ambientTexture=this.ambientTexture.clone();}if(this.opacityTexture&&this.opacityTexture.clone){newStandardMaterial.opacityTexture=this.opacityTexture.clone();}if(this.reflectionTexture&&this.reflectionTexture.clone){newStandardMaterial.reflectionTexture=this.reflectionTexture.clone();}if(this.emissiveTexture&&this.emissiveTexture.clone){newStandardMaterial.emissiveTexture=this.emissiveTexture.clone();}if(this.specularTexture&&this.specularTexture.clone){newStandardMaterial.specularTexture=this.specularTexture.clone();}if(this.bumpTexture&&this.bumpTexture.clone){newStandardMaterial.bumpTexture=this.bumpTexture.clone();}newStandardMaterial.ambientColor=this.ambientColor.clone();newStandardMaterial.diffuseColor=this.diffuseColor.clone();newStandardMaterial.specularColor=this.specularColor.clone();newStandardMaterial.specularPower=this.specularPower;newStandardMaterial.emissiveColor=this.emissiveColor.clone();return newStandardMaterial;};StandardMaterial.DiffuseTextureEnabled=true;StandardMaterial.AmbientTextureEnabled=true;StandardMaterial.OpacityTextureEnabled=true;StandardMaterial.ReflectionTextureEnabled=true;StandardMaterial.EmissiveTextureEnabled=true;StandardMaterial.SpecularTextureEnabled=true;StandardMaterial.BumpTextureEnabled=true;return StandardMaterial;})(BABYLON.Material);BABYLON.StandardMaterial=StandardMaterial;})(BABYLON||(BABYLON={}));var __extends=this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d;}__.prototype=b.prototype;d.prototype=new __();};var BABYLON;(function(BABYLON){var MultiMaterial=(function(_super){__extends(MultiMaterial,_super);function MultiMaterial(name,scene){_super.call(this,name,scene,true);this.subMaterials=new Array();scene.multiMaterials.push(this);}MultiMaterial.prototype.getSubMaterial=function(index){if(index<0||index>=this.subMaterials.length){return this.getScene().defaultMaterial;}return this.subMaterials[index];};MultiMaterial.prototype.isReady=function(mesh){for(var index=0;index0){_this.db.deleteObjectStore("scenes");_this.db.deleteObjectStore("versions");_this.db.deleteObjectStore("textures");}var scenesStore=_this.db.createObjectStore("scenes",{keyPath:"sceneUrl"});var versionsStore=_this.db.createObjectStore("versions",{keyPath:"sceneUrl"});var texturesStore=_this.db.createObjectStore("textures",{keyPath:"textureUrl"});}catch(ex){BABYLON.Tools.Error("Error while creating object stores. Exception: "+ex.message);handleError();}};}else{if(successCallback)successCallback();}}};Database.prototype.loadImageFromDB=function(url,image){var _this=this;var completeURL=BABYLON.Database.ReturnFullUrlLocation(url);var saveAndLoadImage=function(){if(!_this.hasReachedQuota&&_this.db!==null){_this._saveImageIntoDBAsync(completeURL,image);}else{image.src=url;}};if(!this.mustUpdateRessources){this._loadImageFromDBAsync(completeURL,image,saveAndLoadImage);}else{saveAndLoadImage();}};Database.prototype._loadImageFromDBAsync=function(url,image,notInDBCallback){if(this.isSupported&&this.db!==null){var texture;var transaction=this.db.transaction(["textures"]);transaction.onabort=function(event){image.src=url;};transaction.oncomplete=function(event){var blobTextureURL;if(texture){var URL=window.URL||window.webkitURL;blobTextureURL=URL.createObjectURL(texture.data,{oneTimeOnly:true});image.onerror=function(){BABYLON.Tools.Error("Error loading image from blob URL: "+blobTextureURL+" switching back to web url: "+url);image.src=url;};image.src=blobTextureURL;}else{notInDBCallback();}};var getRequest=transaction.objectStore("textures").get(url);getRequest.onsuccess=function(event){texture=(event.target).result;};getRequest.onerror=function(event){BABYLON.Tools.Error("Error loading texture "+url+" from DB.");image.src=url;};}else{BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");image.src=url;}};Database.prototype._saveImageIntoDBAsync=function(url,image){var _this=this;if(this.isSupported){var generateBlobUrl=function(){var blobTextureURL;if(blob){var URL=window.URL||window.webkitURL;try{blobTextureURL=URL.createObjectURL(blob,{oneTimeOnly:true});}catch(ex){blobTextureURL=URL.createObjectURL(blob);}}image.src=blobTextureURL;};if(BABYLON.Database.isUASupportingBlobStorage){var xhr=new XMLHttpRequest(),blob;xhr.open("GET",url,true);xhr.responseType="blob";xhr.addEventListener("load",function(){if(xhr.status===200){blob=xhr.response;var transaction=_this.db.transaction(["textures"],"readwrite");transaction.onabort=function(event){try{if(event.srcElement.error.name==="QuotaExceededError"){this.hasReachedQuota=true;}}catch(ex){}generateBlobUrl();};transaction.oncomplete=function(event){generateBlobUrl();};var newTexture={textureUrl:url,data:blob};try{var addRequest=transaction.objectStore("textures").put(newTexture);addRequest.onsuccess=function(event){};addRequest.onerror=function(event){generateBlobUrl();};}catch(ex){if(ex.code===25){BABYLON.Database.isUASupportingBlobStorage=false;}image.src=url;}}else{image.src=url;}},false);xhr.addEventListener("error",function(event){BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");image.src=url;},false);xhr.send();}else{image.src=url;}}else{BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");image.src=url;}};Database.prototype._checkVersionFromDB=function(url,versionLoaded){var _this=this;var updateVersion=function(event){_this._saveVersionIntoDBAsync(url,versionLoaded);};this._loadVersionFromDBAsync(url,versionLoaded,updateVersion);};Database.prototype._loadVersionFromDBAsync=function(url,callback,updateInDBCallback){var _this=this;if(this.isSupported){var version;try{var transaction=this.db.transaction(["versions"]);transaction.oncomplete=function(event){if(version){if(_this.manifestVersionFound>version.data){_this.mustUpdateRessources=true;updateInDBCallback();}else{callback(version.data);}}else{_this.mustUpdateRessources=true;updateInDBCallback();}};transaction.onabort=function(event){callback(-1);};var getRequest=transaction.objectStore("versions").get(url);getRequest.onsuccess=function(event){version=(event.target).result;};getRequest.onerror=function(event){BABYLON.Tools.Error("Error loading version for scene "+url+" from DB.");callback(-1);};}catch(ex){BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: "+ex.message);callback(-1);}}else{BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");callback(-1);}};Database.prototype._saveVersionIntoDBAsync=function(url,callback){var _this=this;if(this.isSupported&&!this.hasReachedQuota){try{var transaction=this.db.transaction(["versions"],"readwrite");transaction.onabort=function(event){try{if(event.srcElement.error.name==="QuotaExceededError"){_this.hasReachedQuota=true;}}catch(ex){}callback(-1);};transaction.oncomplete=function(event){callback(_this.manifestVersionFound);};var newVersion={sceneUrl:url,data:this.manifestVersionFound};var addRequest=transaction.objectStore("versions").put(newVersion);addRequest.onsuccess=function(event){};addRequest.onerror=function(event){BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");};}catch(ex){BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+ex.message);callback(-1);}}else{callback(-1);}};Database.prototype.loadFileFromDB=function(url,sceneLoaded,progressCallBack,errorCallback,useArrayBuffer){var _this=this;var completeUrl=BABYLON.Database.ReturnFullUrlLocation(url);var saveAndLoadFile=function(event){_this._saveFileIntoDBAsync(completeUrl,sceneLoaded,progressCallBack);};this._checkVersionFromDB(completeUrl,function(version){if(version!==-1){if(!_this.mustUpdateRessources){_this._loadFileFromDBAsync(completeUrl,sceneLoaded,saveAndLoadFile,useArrayBuffer);}else{_this._saveFileIntoDBAsync(completeUrl,sceneLoaded,progressCallBack,useArrayBuffer);}}else{errorCallback();}});};Database.prototype._loadFileFromDBAsync=function(url,callback,notInDBCallback,useArrayBuffer){if(this.isSupported){var targetStore;if(url.indexOf(".babylon")!==-1){targetStore="scenes";}else{targetStore="textures";}var file;var transaction=this.db.transaction([targetStore]);transaction.oncomplete=function(event){if(file){callback(file.data);}else{notInDBCallback();}};transaction.onabort=function(event){notInDBCallback();};var getRequest=transaction.objectStore(targetStore).get(url);getRequest.onsuccess=function(event){file=(event.target).result;};getRequest.onerror=function(event){BABYLON.Tools.Error("Error loading file "+url+" from DB.");notInDBCallback();};}else{BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");callback();}};Database.prototype._saveFileIntoDBAsync=function(url,callback,progressCallback,useArrayBuffer){var _this=this;if(this.isSupported){var targetStore;if(url.indexOf(".babylon")!==-1){targetStore="scenes";}else{targetStore="textures";}var xhr=new XMLHttpRequest(),fileData;xhr.open("GET",url,true);if(useArrayBuffer){xhr.responseType="arraybuffer";}xhr.onprogress=progressCallback;xhr.addEventListener("load",function(){if(xhr.status===200||BABYLON.Tools.ValidateXHRData(xhr,!useArrayBuffer?1:6)){fileData=!useArrayBuffer?xhr.responseText:xhr.response;if(!_this.hasReachedQuota){var transaction=_this.db.transaction([targetStore],"readwrite");transaction.onabort=function(event){try{if(event.srcElement.error.name==="QuotaExceededError"){this.hasReachedQuota=true;}}catch(ex){}callback(fileData);};transaction.oncomplete=function(event){callback(fileData);};var newFile;if(targetStore==="scenes"){newFile={sceneUrl:url,data:fileData,version:_this.manifestVersionFound};}else{newFile={textureUrl:url,data:fileData};}try{var addRequest=transaction.objectStore(targetStore).put(newFile);addRequest.onsuccess=function(event){};addRequest.onerror=function(event){BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");};}catch(ex){callback(fileData);}}else{callback(fileData);}}else{callback();}},false);xhr.addEventListener("error",function(event){BABYLON.Tools.Error("error on XHR request.");callback();},false);xhr.send();}else{BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");callback();}};Database.isUASupportingBlobStorage=true;Database.parseURL=function(url){var a=document.createElement('a');a.href=url;var fileName=url.substring(url.lastIndexOf("/")+1,url.length);var absLocation=url.substring(0,url.indexOf(fileName,0));return absLocation;};Database.ReturnFullUrlLocation=function(url){if(url.indexOf("http:/")===-1){return(BABYLON.Database.parseURL(window.location.href)+url);}else{return url;}};return Database;})();BABYLON.Database=Database;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var SpriteManager=(function(){function SpriteManager(name,imgUrl,capacity,cellSize,scene,epsilon){this.name=name;this.cellSize=cellSize;this.sprites=new Array();this.renderingGroupId=0;this._vertexDeclaration=[3,4,4,4];this._vertexStrideSize=15*4;this._capacity=capacity;this._spriteTexture=new BABYLON.Texture(imgUrl,scene,true,false);this._spriteTexture.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE;this._spriteTexture.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE;this._epsilon=epsilon===undefined?0.01:epsilon;this._scene=scene;this._scene.spriteManagers.push(this);this._vertexDeclaration=[3,4,4,4];this._vertexStrideSize=15*4;this._vertexBuffer=scene.getEngine().createDynamicVertexBuffer(capacity*this._vertexStrideSize*4);var indices=[];var index=0;for(var count=0;count>0;this._vertices[arrayOffset+9]=sprite.cellIndex-offset*rowSize;this._vertices[arrayOffset+10]=offset;this._vertices[arrayOffset+11]=sprite.color.r;this._vertices[arrayOffset+12]=sprite.color.g;this._vertices[arrayOffset+13]=sprite.color.b;this._vertices[arrayOffset+14]=sprite.color.a;};SpriteManager.prototype.render=function(){if(!this._effectBase.isReady()||!this._effectFog.isReady()||!this._spriteTexture||!this._spriteTexture.isReady())return;var engine=this._scene.getEngine();var baseSize=this._spriteTexture.getBaseSize();var deltaTime=BABYLON.Tools.GetDeltaTime();var max=Math.min(this._capacity,this.sprites.length);var rowSize=baseSize.width/this.cellSize;var offset=0;for(var index=0;indexthis._delay){this._time=this._time%this._delay;this.cellIndex+=this._direction;if(this.cellIndex==this._toIndex){if(this._loopAnimation){this.cellIndex=this._fromIndex;}else{this._animationStarted=false;if(this.disposeWhenFinishedAnimating){this.dispose();}}}}};Sprite.prototype.dispose=function(){for(var i=0;i0;for(var index=0;index=particle.lifeTime){this._stockParticles.push(this.particles.splice(index,1)[0]);index--;continue;}else{particle.colorStep.scaleToRef(this._scaledUpdateSpeed,this._scaledColorStep);particle.color.addInPlace(this._scaledColorStep);if(particle.color.a<0)particle.color.a=0;particle.angle+=particle.angularSpeed*this._scaledUpdateSpeed;particle.direction.scaleToRef(this._scaledUpdateSpeed,this._scaledDirection);particle.position.addInPlace(this._scaledDirection);this.gravity.scaleToRef(this._scaledUpdateSpeed,this._scaledGravity);particle.direction.addInPlace(this._scaledGravity);}}var worldMatrix;if(this.emitter.position){worldMatrix=this.emitter.getWorldMatrix();}else{worldMatrix=BABYLON.Matrix.Translation(this.emitter.x,this.emitter.y,this.emitter.z);}for(index=0;index-1){emitCout=this.manualEmitCount;this.manualEmitCount=0;}else{emitCout=this.emitRate;}var newParticles=((emitCout*this._scaledUpdateSpeed)>>0);this._newPartsExcess+=emitCout*this._scaledUpdateSpeed-newParticles;if(this._newPartsExcess>1.0){newParticles+=this._newPartsExcess>>0;this._newPartsExcess-=this._newPartsExcess>>0;}this._alive=false;if(!this._stopped){this._actualFrame+=this._scaledUpdateSpeed;if(this.targetStopDuration&&this._actualFrame>=this.targetStopDuration)this.stop();}else{newParticles=0;}this._update(newParticles);if(this._stopped){if(!this._alive){this._started=false;if(this.disposeOnStop){this._scene._toBeDisposed.push(this);}}}var offset=0;for(var index=0;index0){return highLimitValue.clone?highLimitValue.clone():highLimitValue;}this.currentFrame=currentFrame;for(var key=0;key=currentFrame){var startValue=this._keys[key].value;var endValue=this._keys[key+1].value;var gradient=(currentFrame-this._keys[key].frame)/(this._keys[key+1].frame-this._keys[key].frame);switch(this.dataType){case Animation.ANIMATIONTYPE_FLOAT:switch(loopMode){case Animation.ANIMATIONLOOPMODE_CYCLE:case Animation.ANIMATIONLOOPMODE_CONSTANT:return this.floatInterpolateFunction(startValue,endValue,gradient);case Animation.ANIMATIONLOOPMODE_RELATIVE:return offsetValue*repeatCount+this.floatInterpolateFunction(startValue,endValue,gradient);}break;case Animation.ANIMATIONTYPE_QUATERNION:var quaternion=null;switch(loopMode){case Animation.ANIMATIONLOOPMODE_CYCLE:case Animation.ANIMATIONLOOPMODE_CONSTANT:quaternion=this.quaternionInterpolateFunction(startValue,endValue,gradient);break;case Animation.ANIMATIONLOOPMODE_RELATIVE:quaternion=this.quaternionInterpolateFunction(startValue,endValue,gradient).add(offsetValue.scale(repeatCount));break;}return quaternion;case Animation.ANIMATIONTYPE_VECTOR3:switch(loopMode){case Animation.ANIMATIONLOOPMODE_CYCLE:case Animation.ANIMATIONLOOPMODE_CONSTANT:return this.vector3InterpolateFunction(startValue,endValue,gradient);case Animation.ANIMATIONLOOPMODE_RELATIVE:return this.vector3InterpolateFunction(startValue,endValue,gradient).add(offsetValue.scale(repeatCount));}case Animation.ANIMATIONTYPE_COLOR3:switch(loopMode){case Animation.ANIMATIONLOOPMODE_CYCLE:case Animation.ANIMATIONLOOPMODE_CONSTANT:return this.color3InterpolateFunction(startValue,endValue,gradient);case Animation.ANIMATIONLOOPMODE_RELATIVE:return this.color3InterpolateFunction(startValue,endValue,gradient).add(offsetValue.scale(repeatCount));}case Animation.ANIMATIONTYPE_MATRIX:switch(loopMode){case Animation.ANIMATIONLOOPMODE_CYCLE:case Animation.ANIMATIONLOOPMODE_CONSTANT:case Animation.ANIMATIONLOOPMODE_RELATIVE:return startValue;}default:break;}break;}}return this._keys[this._keys.length-1].value;};Animation.prototype.animate=function(delay,from,to,loop,speedRatio){if(!this.targetPropertyPath||this.targetPropertyPath.length<1){this._stopped=true;return false;}var returnValue=true;if(this._keys[0].frame!=0){var newKey={frame:0,value:this._keys[0].value};this._keys.splice(0,0,newKey);}if(fromthis._keys[this._keys.length-1].frame){from=this._keys[0].frame;}if(tothis._keys[this._keys.length-1].frame){to=this._keys[this._keys.length-1].frame;}var range=to-from;var offsetValue;var ratio=delay*(this.framePerSecond*speedRatio)/1000.0;if(ratio>range&&!loop){returnValue=false;highLimitValue=this._keys[this._keys.length-1].value;}else{var highLimitValue=0;if(this.loopMode!=Animation.ANIMATIONLOOPMODE_CYCLE){var keyOffset=to.toString()+from.toString();if(!this._offsetsCache[keyOffset]){var fromValue=this._interpolate(from,0,Animation.ANIMATIONLOOPMODE_CYCLE);var toValue=this._interpolate(to,0,Animation.ANIMATIONLOOPMODE_CYCLE);switch(this.dataType){case Animation.ANIMATIONTYPE_FLOAT:this._offsetsCache[keyOffset]=toValue-fromValue;break;case Animation.ANIMATIONTYPE_QUATERNION:this._offsetsCache[keyOffset]=toValue.subtract(fromValue);break;case Animation.ANIMATIONTYPE_VECTOR3:this._offsetsCache[keyOffset]=toValue.subtract(fromValue);case Animation.ANIMATIONTYPE_COLOR3:this._offsetsCache[keyOffset]=toValue.subtract(fromValue);default:break;}this._highLimitsCache[keyOffset]=toValue;}highLimitValue=this._highLimitsCache[keyOffset];offsetValue=this._offsetsCache[keyOffset];}}if(offsetValue===undefined){switch(this.dataType){case Animation.ANIMATIONTYPE_FLOAT:offsetValue=0;break;case Animation.ANIMATIONTYPE_QUATERNION:offsetValue=new BABYLON.Quaternion();break;case Animation.ANIMATIONTYPE_VECTOR3:offsetValue=BABYLON.Vector3.Zero();break;case Animation.ANIMATIONTYPE_COLOR3:offsetValue=BABYLON.Color3.Black();}}var repeatCount=(ratio/range)>>0;var currentFrame=returnValue?from+ratio%range:to;var currentValue=this._interpolate(currentFrame,repeatCount,this.loopMode,offsetValue,highLimitValue);if(this.targetPropertyPath.length>1){var property=this._target[this.targetPropertyPath[0]];for(var index=1;index-1){this._scene._activeAnimatables.splice(index,1);}if(this.onAnimationEnd){this.onAnimationEnd();}};Animatable.prototype._animate=function(delay){if(this._paused){return true;}if(!this._localDelayOffset){this._localDelayOffset=delay;}var running=false;var animations=this._animations;for(var index=0;indexthis.capacity&&this._depth0){for(var i=0;i0){for(var i=0;i0){this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width=-1;}};return PostProcess;})();BABYLON.PostProcess=PostProcess;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var PostProcessManager=(function(){function PostProcessManager(scene){this._vertexDeclaration=[2];this._vertexStrideSize=2*4;this._scene=scene;var vertices=[];vertices.push(1,1);vertices.push(-1,1);vertices.push(-1,-1);vertices.push(1,-1);this._vertexBuffer=scene.getEngine().createVertexBuffer(vertices);var indices=[];indices.push(0);indices.push(1);indices.push(2);indices.push(0);indices.push(2);indices.push(3);this._indexBuffer=scene.getEngine().createIndexBuffer(indices);}PostProcessManager.prototype._prepareFrame=function(sourceTexture){var postProcesses=this._scene.activeCamera._postProcesses;var postProcessesTakenIndices=this._scene.activeCamera._postProcessesTakenIndices;if(postProcessesTakenIndices.length===0||!this._scene.postProcessesEnabled){return false;}postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera,sourceTexture);return true;};PostProcessManager.prototype._finalizeFrame=function(doNotPresent,targetTexture){var postProcesses=this._scene.activeCamera._postProcesses;var postProcessesTakenIndices=this._scene.activeCamera._postProcessesTakenIndices;if(postProcessesTakenIndices.length===0||!this._scene.postProcessesEnabled){return;}var engine=this._scene.getEngine();for(var index=0;index0){if((this._positionX>globalViewport.x)&&(this._positionXglobalViewport.y)&&(this._positionYdistance;};LensFlareSystem.prototype.render=function(){if(!this._effect.isReady())return false;var engine=this._scene.getEngine();var viewport=this._scene.activeCamera.viewport;var globalViewport=viewport.toGlobal(engine);if(!this.computeEffectivePosition(globalViewport)){return false;}if(!this._isVisible()){return false;}var awayX;var awayY;if(this._positionXglobalViewport.x+globalViewport.width-this.borderLimit){awayX=this._positionX-globalViewport.x-globalViewport.width+this.borderLimit;}else{awayX=0;}if(this._positionYglobalViewport.y+globalViewport.height-this.borderLimit){awayY=this._positionY-globalViewport.y-globalViewport.height+this.borderLimit;}else{awayY=0;}var away=(awayX>awayY)?awayX:awayY;if(away>this.borderLimit){away=this.borderLimit;}var intensity=1.0-(away/this.borderLimit);if(intensity<0){return false;}if(intensity>1.0){intensity=1.0;}var centerX=globalViewport.x+globalViewport.width/2;var centerY=globalViewport.y+globalViewport.height/2;var distX=centerX-this._positionX;var distY=centerY-this._positionY;engine.enableEffect(this._effect);engine.setState(false);engine.setDepthBuffer(false);engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);engine.bindBuffers(this._vertexBuffer,this._indexBuffer,this._vertexDeclaration,this._vertexStrideSize,this._effect);for(var index=0;index0){this.textureLoadingCallback(remaining);}}this.currentScene.render();}};FilesInput.prototype.drag=function(e){e.stopPropagation();e.preventDefault();};FilesInput.prototype.drop=function(eventDrop){eventDrop.stopPropagation();eventDrop.preventDefault();this.loadFiles(eventDrop);};FilesInput.prototype.loadFiles=function(event){var _this=this;var that=this;if(this.startingProcessingFilesCallback)this.startingProcessingFilesCallback();var sceneFileToLoad;var filesToLoad;if(event&&event.dataTransfer&&event.dataTransfer.files){filesToLoad=event.dataTransfer.files;}if(event&&event.target&&event.target.files){filesToLoad=event.target.files;}if(filesToLoad&&filesToLoad.length>0){for(var i=0;i0.1){delta=0.1;}else if(delta<=0){delta=1.0/60.0;}this._currentPlugin.runOneStep(delta);};PhysicsEngine.prototype._setGravity=function(gravity){this.gravity=gravity||new BABYLON.Vector3(0,-9.82,0);this._currentPlugin.setGravity(this.gravity);};PhysicsEngine.prototype._registerMesh=function(mesh,impostor,options){return this._currentPlugin.registerMesh(mesh,impostor,options);};PhysicsEngine.prototype._registerMeshesAsCompound=function(parts,options){return this._currentPlugin.registerMeshesAsCompound(parts,options);};PhysicsEngine.prototype._unregisterMesh=function(mesh){this._currentPlugin.unregisterMesh(mesh);};PhysicsEngine.prototype._applyImpulse=function(mesh,force,contactPoint){this._currentPlugin.applyImpulse(mesh,force,contactPoint);};PhysicsEngine.prototype._createLink=function(mesh1,mesh2,pivot1,pivot2,options){return this._currentPlugin.createLink(mesh1,mesh2,pivot1,pivot2,options);};PhysicsEngine.prototype._updateBodyPosition=function(mesh){this._currentPlugin.updateBodyPosition(mesh);};PhysicsEngine.prototype.dispose=function(){this._currentPlugin.dispose();};PhysicsEngine.prototype.isSupported=function(){return this._currentPlugin.isSupported();};PhysicsEngine.NoImpostor=0;PhysicsEngine.SphereImpostor=1;PhysicsEngine.BoxImpostor=2;PhysicsEngine.PlaneImpostor=3;PhysicsEngine.CompoundImpostor=4;PhysicsEngine.MeshImpostor=4;PhysicsEngine.CapsuleImpostor=5;PhysicsEngine.ConeImpostor=6;PhysicsEngine.CylinderImpostor=7;PhysicsEngine.ConvexHullImpostor=8;PhysicsEngine.Epsilon=0.001;return PhysicsEngine;})();BABYLON.PhysicsEngine=PhysicsEngine;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var serializeLight=function(light){var serializationObject={};serializationObject.name=light.name;serializationObject.id=light.id;serializationObject.tags=BABYLON.Tags.GetTags(light);if(light instanceof BABYLON.PointLight){serializationObject.type=0;serializationObject.position=light.position.asArray();}else if(light instanceof BABYLON.DirectionalLight){serializationObject.type=1;var directionalLight=light;serializationObject.position=directionalLight.position.asArray();serializationObject.direction=directionalLight.direction.asArray();}else if(light instanceof BABYLON.SpotLight){serializationObject.type=2;var spotLight=light;serializationObject.position=spotLight.position.asArray();serializationObject.direction=spotLight.position.asArray();serializationObject.angle=spotLight.angle;serializationObject.exponent=spotLight.exponent;}else if(light instanceof BABYLON.HemisphericLight){serializationObject.type=3;var hemisphericLight=light;serializationObject.direction=hemisphericLight.direction.asArray();serializationObject.groundColor=hemisphericLight.groundColor.asArray();}if(light.intensity){serializationObject.intensity=light.intensity;}serializationObject.range=light.range;serializationObject.diffuse=light.diffuse.asArray();serializationObject.specular=light.specular.asArray();return serializationObject;};var serializeCamera=function(camera){var serializationObject={};serializationObject.name=camera.name;serializationObject.tags=BABYLON.Tags.GetTags(camera);serializationObject.id=camera.id;serializationObject.position=camera.position.asArray();if(camera.parent){serializationObject.parentId=camera.parent.id;}serializationObject.rotation=camera.rotation.asArray();if(camera.lockedTarget&&camera.lockedTarget.id){serializationObject.lockedTargetId=camera.lockedTarget.id;}serializationObject.fov=camera.fov;serializationObject.minZ=camera.minZ;serializationObject.maxZ=camera.maxZ;serializationObject.speed=camera.speed;serializationObject.inertia=camera.inertia;serializationObject.checkCollisions=camera.checkCollisions;serializationObject.applyGravity=camera.applyGravity;if(camera.ellipsoid){serializationObject.ellipsoid=camera.ellipsoid.asArray();}appendAnimations(camera,serializationObject);serializationObject.layerMask=camera.layerMask;return serializationObject;};var appendAnimations=function(source,destination){if(source.animations){destination.animations=[];for(var animationIndex=0;animationIndex0){serializedBone.animation=serializeAnimation(bone.animations[0]);}}return serializationObject;};var serializeParticleSystem=function(particleSystem){var serializationObject={};serializationObject.emitterId=particleSystem.emitter.id;serializationObject.capacity=particleSystem.getCapacity();if(particleSystem.particleTexture){serializationObject.textureName=particleSystem.particleTexture.name;}serializationObject.minAngularSpeed=particleSystem.minAngularSpeed;serializationObject.maxAngularSpeed=particleSystem.maxAngularSpeed;serializationObject.minSize=particleSystem.minSize;serializationObject.maxSize=particleSystem.maxSize;serializationObject.minLifeTime=particleSystem.minLifeTime;serializationObject.maxLifeTime=particleSystem.maxLifeTime;serializationObject.emitRate=particleSystem.emitRate;serializationObject.minEmitBox=particleSystem.minEmitBox.asArray();serializationObject.maxEmitBox=particleSystem.maxEmitBox.asArray();serializationObject.gravity=particleSystem.gravity.asArray();serializationObject.direction1=particleSystem.direction1.asArray();serializationObject.direction2=particleSystem.direction2.asArray();serializationObject.color1=particleSystem.color1.asArray();serializationObject.color2=particleSystem.color2.asArray();serializationObject.colorDead=particleSystem.colorDead.asArray();serializationObject.updateSpeed=particleSystem.updateSpeed;serializationObject.targetStopDuration=particleSystem.targetStopDuration;serializationObject.textureMask=particleSystem.textureMask.asArray();serializationObject.blendMode=particleSystem.blendMode;return serializationObject;};var serializeLensFlareSystem=function(lensFlareSystem){var serializationObject={};serializationObject.emitterId=lensFlareSystem.getEmitter().id;serializationObject.borderLimit=lensFlareSystem.borderLimit;serializationObject.flares=[];for(var index=0;index-1){parentBone=skeleton.bones[parsedBone.parentBoneIndex];}var bone=new BABYLON.Bone(parsedBone.name,skeleton,parentBone,BABYLON.Matrix.FromArray(parsedBone.matrix));if(parsedBone.animation){bone.animations.push(parseAnimation(parsedBone.animation));}}return skeleton;};var parseMaterial=function(parsedMaterial,scene,rootUrl){var material;material=new BABYLON.StandardMaterial(parsedMaterial.name,scene);material.ambientColor=BABYLON.Color3.FromArray(parsedMaterial.ambient);material.diffuseColor=BABYLON.Color3.FromArray(parsedMaterial.diffuse);material.specularColor=BABYLON.Color3.FromArray(parsedMaterial.specular);material.specularPower=parsedMaterial.specularPower;material.emissiveColor=BABYLON.Color3.FromArray(parsedMaterial.emissive);material.alpha=parsedMaterial.alpha;material.id=parsedMaterial.id;BABYLON.Tags.AddTagsTo(material,parsedMaterial.tags);material.backFaceCulling=parsedMaterial.backFaceCulling;material.wireframe=parsedMaterial.wireframe;if(parsedMaterial.diffuseTexture){material.diffuseTexture=loadTexture(rootUrl,parsedMaterial.diffuseTexture,scene);}if(parsedMaterial.ambientTexture){material.ambientTexture=loadTexture(rootUrl,parsedMaterial.ambientTexture,scene);}if(parsedMaterial.opacityTexture){material.opacityTexture=loadTexture(rootUrl,parsedMaterial.opacityTexture,scene);}if(parsedMaterial.reflectionTexture){material.reflectionTexture=loadTexture(rootUrl,parsedMaterial.reflectionTexture,scene);}if(parsedMaterial.emissiveTexture){material.emissiveTexture=loadTexture(rootUrl,parsedMaterial.emissiveTexture,scene);}if(parsedMaterial.specularTexture){material.specularTexture=loadTexture(rootUrl,parsedMaterial.specularTexture,scene);}if(parsedMaterial.bumpTexture){material.bumpTexture=loadTexture(rootUrl,parsedMaterial.bumpTexture,scene);}return material;};var parseMaterialById=function(id,parsedData,scene,rootUrl){for(var index=0;index-1){mesh.skeleton=scene.getLastSkeletonByID(parsedMesh.skeletonId);}if(parsedMesh.physicsImpostor){if(!scene.isPhysicsEnabled()){scene.enablePhysics();}mesh.setPhysicsState({impostor:parsedMesh.physicsImpostor,mass:parsedMesh.physicsMass,friction:parsedMesh.physicsFriction,restitution:parsedMesh.physicsRestitution});}if(parsedMesh.animations){for(var animationIndex=0;animationIndex>8);floatIndices.push((matricesIndex&0x00FF0000)>>16);floatIndices.push(matricesIndex>>24);}mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind,floatIndices,false);}else{delete parsedGeometry.matricesIndices._isExpanded;mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind,parsedGeometry.matricesIndices,false);}}if(parsedGeometry.matricesWeights){mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind,parsedGeometry.matricesWeights,false);}mesh.setIndices(parsedGeometry.indices);}if(parsedGeometry.subMeshes){mesh.subMeshes=[];for(var subIndex=0;subIndex-1&&scene.skeletons){var skeletonAlreadyLoaded=(loadedSkeletonsIds.indexOf(parsedMesh.skeletonId)>-1);if(!skeletonAlreadyLoaded){for(var skeletonIndex=0;skeletonIndexPlane.EPSILON)?FRONT:COPLANAR;polygonType|=type;types.push(type);}switch(polygonType){case COPLANAR:(BABYLON.Vector3.Dot(this.normal,polygon.plane.normal)>0?coplanarFront:coplanarBack).push(polygon);break;case FRONT:front.push(polygon);break;case BACK:back.push(polygon);break;case SPANNING:var f=[],b=[];for(i=0;i=3){var poly=new Polygon(f,polygon.shared);if(poly.plane)front.push(poly);}if(b.length>=3){poly=new Polygon(b,polygon.shared);if(poly.plane)back.push(poly);}break;}};Plane.EPSILON=1e-5;return Plane;})();var Polygon=(function(){function Polygon(vertices,shared){this.vertices=vertices;this.shared=shared;this.plane=Plane.FromPoints(vertices[0].pos,vertices[1].pos,vertices[2].pos);}Polygon.prototype.clone=function(){var vertices=this.vertices.map(function(v){return v.clone();});return new Polygon(vertices,this.shared);};Polygon.prototype.flip=function(){this.vertices.reverse().map(function(v){v.flip();});this.plane.flip();};return Polygon;})();var Node=(function(){function Node(polygons){this.plane=null;this.front=null;this.back=null;this.polygons=[];if(polygons){this.build(polygons);}}Node.prototype.clone=function(){var node=new Node();node.plane=this.plane&&this.plane.clone();node.front=this.front&&this.front.clone();node.back=this.back&&this.back.clone();node.polygons=this.polygons.map(function(p){return p.clone();});return node;};Node.prototype.invert=function(){for(var i=0;iVirtualJoystick.halfWidth);}if(positionOnScreenCondition&&this._joystickPointerID<0){this._joystickPointerID=e.pointerId;this._joystickPointerStartPos.x=e.clientX;this._joystickPointerStartPos.y=e.clientY;this._joystickPointerPos=this._joystickPointerStartPos.clone();this._deltaJoystickVector.x=0;this._deltaJoystickVector.y=0;this.pressed=true;this._touches.add(e.pointerId.toString(),e);}else{if(VirtualJoystick._globalJoystickIndex<2&&this._action){this._action();this._touches.add(e.pointerId.toString(),e);}}};VirtualJoystick.prototype._onPointerMove=function(e){if(this._joystickPointerID==e.pointerId){this._joystickPointerPos.x=e.clientX;this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone();this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos);var directionLeftRight=this.reverseLeftRight?-1:1;var deltaJoystickX=directionLeftRight*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case 0/*X*/:this.deltaPosition.x=Math.min(1,Math.max(-1,deltaJoystickX));break;case 1/*Y*/:this.deltaPosition.y=Math.min(1,Math.max(-1,deltaJoystickX));break;case 2/*Z*/:this.deltaPosition.z=Math.min(1,Math.max(-1,deltaJoystickX));break;}var directionUpDown=this.reverseUpDown?1:-1;var deltaJoystickY=directionUpDown*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case 0/*X*/:this.deltaPosition.x=Math.min(1,Math.max(-1,deltaJoystickY));break;case 1/*Y*/:this.deltaPosition.y=Math.min(1,Math.max(-1,deltaJoystickY));break;case 2/*Z*/:this.deltaPosition.z=Math.min(1,Math.max(-1,deltaJoystickY));break;}}else{if(this._touches.item(e.pointerId.toString())){this._touches.item(e.pointerId.toString()).x=e.clientX;this._touches.item(e.pointerId.toString()).y=e.clientY;}}};VirtualJoystick.prototype._onPointerUp=function(e){this._clearCanvas();if(this._joystickPointerID==e.pointerId){this._joystickPointerID=-1;this.pressed=false;}this._deltaJoystickVector.x=0;this._deltaJoystickVector.y=0;this._touches.remove(e.pointerId.toString());};/***Change the color of the virtual joystick*@param newColor a string that must be a CSS color value(like"red")or the hexa value(like"#FF0000")*/VirtualJoystick.prototype.setJoystickColor=function(newColor){this._joystickColor=newColor;};VirtualJoystick.prototype.setActionOnTouch=function(action){this._action=action;};VirtualJoystick.prototype.setAxisForLeftRight=function(axis){switch(axis){case 0/*X*/:case 1/*Y*/:case 2/*Z*/:this._axisTargetedByLeftAndRight=axis;break;this._axisTargetedByLeftAndRight=axis;break;default:this._axisTargetedByLeftAndRight=0/*X*/;break;}};VirtualJoystick.prototype.setAxisForUpDown=function(axis){switch(axis){case 0/*X*/:case 1/*Y*/:case 2/*Z*/:this._axisTargetedByUpAndDown=axis;break;default:this._axisTargetedByUpAndDown=1/*Y*/;break;}};VirtualJoystick.prototype._clearCanvas=function(){if(this._leftJoystick){VirtualJoystick.vjCanvasContext.clearRect(0,0,VirtualJoystick.vjCanvasWidth/2,VirtualJoystick.vjCanvasHeight);}else{VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth/2,0,VirtualJoystick.vjCanvasWidth,VirtualJoystick.vjCanvasHeight);}};VirtualJoystick.prototype._drawVirtualJoystick=function(){var _this=this;if(this.pressed){this._clearCanvas();this._touches.forEach(function(touch){if(touch.pointerId===_this._joystickPointerID){VirtualJoystick.vjCanvasContext.beginPath();VirtualJoystick.vjCanvasContext.strokeStyle=_this._joystickColor;VirtualJoystick.vjCanvasContext.lineWidth=6;VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x,_this._joystickPointerStartPos.y,40,0,Math.PI*2,true);VirtualJoystick.vjCanvasContext.stroke();VirtualJoystick.vjCanvasContext.beginPath();VirtualJoystick.vjCanvasContext.strokeStyle=_this._joystickColor;VirtualJoystick.vjCanvasContext.lineWidth=2;VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x,_this._joystickPointerStartPos.y,60,0,Math.PI*2,true);VirtualJoystick.vjCanvasContext.stroke();VirtualJoystick.vjCanvasContext.beginPath();VirtualJoystick.vjCanvasContext.strokeStyle=_this._joystickColor;VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x,_this._joystickPointerPos.y,40,0,Math.PI*2,true);VirtualJoystick.vjCanvasContext.stroke();}else{VirtualJoystick.vjCanvasContext.beginPath();VirtualJoystick.vjCanvasContext.fillStyle="white";VirtualJoystick.vjCanvasContext.beginPath();VirtualJoystick.vjCanvasContext.strokeStyle="red";VirtualJoystick.vjCanvasContext.lineWidth=6;VirtualJoystick.vjCanvasContext.arc(touch.x,touch.y,40,0,Math.PI*2,true);VirtualJoystick.vjCanvasContext.stroke();};});}requestAnimationFrame(function(){_this._drawVirtualJoystick();});};VirtualJoystick.prototype.releaseCanvas=function(){if(VirtualJoystick.vjCanvas){document.body.removeChild(VirtualJoystick.vjCanvas);VirtualJoystick.vjCanvas=null;}};VirtualJoystick._globalJoystickIndex=0;return VirtualJoystick;})();BABYLON.VirtualJoystick=VirtualJoystick;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){(function(VirtualJoystick){var Collection=(function(){function Collection(){this._count=0;this._collection=new Array();}Collection.prototype.Count=function(){return this._count;};Collection.prototype.add=function(key,item){if(this._collection[key]!=undefined){return undefined;}this._collection[key]=item;return++this._count;};Collection.prototype.remove=function(key){if(this._collection[key]==undefined){return undefined;}delete this._collection[key];return--this._count;};Collection.prototype.item=function(key){return this._collection[key];};Collection.prototype.forEach=function(block){var key;for(key in this._collection){if(this._collection.hasOwnProperty(key)){block(this._collection[key]);}}};return Collection;})();VirtualJoystick.Collection=Collection;})(BABYLON.VirtualJoystick||(BABYLON.VirtualJoystick={}));var VirtualJoystick=BABYLON.VirtualJoystick;})(BABYLON||(BABYLON={}));var __extends=this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d;}__.prototype=b.prototype;d.prototype=new __();};var BABYLON;(function(BABYLON){var OculusRiftDevKit2013_Metric={HResolution:1280,VResolution:800,HScreenSize:0.149759993,VScreenSize:0.0935999975,VScreenCenter:0.0467999987,EyeToScreenDistance:0.0410000011,LensSeparationDistance:0.0635000020,InterpupillaryDistance:0.0640000030,DistortionK:[1.0,0.219999999,0.239999995,0.0],ChromaAbCorrection:[0.995999992,-0.00400000019,1.01400006,0.0],PostProcessScaleFactor:1.714605507808412,LensCenterOffset:0.151976421};var _OculusInnerCamera=(function(_super){__extends(_OculusInnerCamera,_super);function _OculusInnerCamera(name,position,scene,isLeftEye){_super.call(this,name,position,scene);this._workMatrix=new BABYLON.Matrix();this._actualUp=new BABYLON.Vector3(0,0,0);this._aspectRatioAspectRatio=OculusRiftDevKit2013_Metric.HResolution/(2*OculusRiftDevKit2013_Metric.VResolution);this._aspectRatioFov=(2*Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor*OculusRiftDevKit2013_Metric.VScreenSize)/(2*OculusRiftDevKit2013_Metric.EyeToScreenDistance)));var hMeters=(OculusRiftDevKit2013_Metric.HScreenSize/4)-(OculusRiftDevKit2013_Metric.LensSeparationDistance/2);var h=(4*hMeters)/OculusRiftDevKit2013_Metric.HScreenSize;this._hMatrix=BABYLON.Matrix.Translation(isLeftEye?h:-h,0,0);this.viewport=new BABYLON.Viewport(isLeftEye?0:0.5,0,0.5,1.0);this._preViewMatrix=BABYLON.Matrix.Translation(isLeftEye?.5*OculusRiftDevKit2013_Metric.InterpupillaryDistance:-.5*OculusRiftDevKit2013_Metric.InterpupillaryDistance,0,0);var postProcess=new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion",this,!isLeftEye,OculusRiftDevKit2013_Metric);}_OculusInnerCamera.prototype.getProjectionMatrix=function(){BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov,this._aspectRatioAspectRatio,this.minZ,this.maxZ,this._workMatrix);this._workMatrix.multiplyToRef(this._hMatrix,this._projectionMatrix);return this._projectionMatrix;};_OculusInnerCamera.prototype._getViewMatrix=function(){BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix);BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint);BABYLON.Vector3.TransformNormalToRef(this.upVector,this._cameraRotationMatrix,this._actualUp);this.position.addToRef(this._transformedReferencePoint,this._currentTarget);BABYLON.Matrix.LookAtLHToRef(this.position,this._currentTarget,this._actualUp,this._workMatrix);this._workMatrix.multiplyToRef(this._preViewMatrix,this._viewMatrix);return this._viewMatrix;};return _OculusInnerCamera;})(BABYLON.FreeCamera);var OculusCamera=(function(_super){__extends(OculusCamera,_super);function OculusCamera(name,position,scene){_super.call(this,name,position,scene);this._leftCamera=new _OculusInnerCamera(name+"_left",position.clone(),scene,true);this._rightCamera=new _OculusInnerCamera(name+"_right",position.clone(),scene,false);this.subCameras.push(this._leftCamera);this.subCameras.push(this._rightCamera);this._deviceOrientationHandler=this._onOrientationEvent.bind(this);}OculusCamera.prototype._update=function(){this._leftCamera.position.copyFrom(this.position);this._rightCamera.position.copyFrom(this.position);this._updateCamera(this._leftCamera);this._updateCamera(this._rightCamera);_super.prototype._update.call(this);};OculusCamera.prototype._updateCamera=function(camera){camera.minZ=this.minZ;camera.maxZ=this.maxZ;camera.rotation.x=this.rotation.x;camera.rotation.y=this.rotation.y;camera.rotation.z=this.rotation.z;};OculusCamera.prototype._onOrientationEvent=function(evt){var yaw=evt.alpha/180*Math.PI;var pitch=evt.beta/180*Math.PI;var roll=evt.gamma/180*Math.PI;if(!this._offsetOrientation){this._offsetOrientation={yaw:yaw,pitch:pitch,roll:roll};return;}else{this.rotation.y+=yaw-this._offsetOrientation.yaw;this.rotation.x+=pitch-this._offsetOrientation.pitch;this.rotation.z+=this._offsetOrientation.roll-roll;this._offsetOrientation.yaw=yaw;this._offsetOrientation.pitch=pitch;this._offsetOrientation.roll=roll;}};OculusCamera.prototype.attachControl=function(element,noPreventDefault){_super.prototype.attachControl.call(this,element,noPreventDefault);window.addEventListener("deviceorientation",this._deviceOrientationHandler);};OculusCamera.prototype.detachControl=function(element){_super.prototype.detachControl.call(this,element);window.removeEventListener("deviceorientation",this._deviceOrientationHandler);};return OculusCamera;})(BABYLON.FreeCamera);BABYLON.OculusCamera=OculusCamera;})(BABYLON||(BABYLON={}));var __extends=this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d;}__.prototype=b.prototype;d.prototype=new __();};var BABYLON;(function(BABYLON){var VirtualJoysticksCamera=(function(_super){__extends(VirtualJoysticksCamera,_super);function VirtualJoysticksCamera(name,position,scene){_super.call(this,name,position,scene);this._leftjoystick=new BABYLON.VirtualJoystick(true);this._leftjoystick.setAxisForUpDown(2/*Z*/);this._leftjoystick.setAxisForLeftRight(0/*X*/);this._leftjoystick.setJoystickSensibility(0.15);this._rightjoystick=new BABYLON.VirtualJoystick(false);this._rightjoystick.setAxisForUpDown(0/*X*/);this._rightjoystick.setAxisForLeftRight(1/*Y*/);this._rightjoystick.reverseUpDown=true;this._rightjoystick.setJoystickSensibility(0.05);this._rightjoystick.setJoystickColor("yellow");}VirtualJoysticksCamera.prototype._checkInputs=function(){var cameraTransform=BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y,this.rotation.x,0);var deltaTransform=BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition,cameraTransform);this.cameraDirection=this.cameraDirection.add(deltaTransform);this.cameraRotation=this.cameraRotation.add(this._rightjoystick.deltaPosition);if(!this._leftjoystick.pressed){this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(0.9);}if(!this._rightjoystick.pressed){this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(0.9);}};VirtualJoysticksCamera.prototype.dispose=function(){this._leftjoystick.releaseCanvas();};return VirtualJoysticksCamera;})(BABYLON.FreeCamera);BABYLON.VirtualJoysticksCamera=VirtualJoysticksCamera;})(BABYLON||(BABYLON={}));var __extends=this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d;}__.prototype=b.prototype;d.prototype=new __();};var BABYLON;(function(BABYLON){var ShaderMaterial=(function(_super){__extends(ShaderMaterial,_super);function ShaderMaterial(name,scene,shaderPath,options){_super.call(this,name,scene);this._textures=new Array();this._floats=new Array();this._floatsArrays={};this._colors3=new Array();this._colors4=new Array();this._vectors2=new Array();this._vectors3=new Array();this._matrices=new Array();this._cachedWorldViewMatrix=new BABYLON.Matrix();this._shaderPath=shaderPath;options.needAlphaBlending=options.needAlphaBlending||false;options.needAlphaTesting=options.needAlphaTesting||false;options.attributes=options.attributes||["position","normal","uv"];options.uniforms=options.uniforms||["worldViewProjection"];options.samplers=options.samplers||[];this._options=options;}ShaderMaterial.prototype.needAlphaBlending=function(){return this._options.needAlphaBlending;};ShaderMaterial.prototype.needAlphaTesting=function(){return this._options.needAlphaTesting;};ShaderMaterial.prototype._checkUniform=function(uniformName){if(this._options.uniforms.indexOf(uniformName)===-1){this._options.uniforms.push(uniformName);}};ShaderMaterial.prototype.setTexture=function(name,texture){if(this._options.samplers.indexOf(name)===-1){this._options.samplers.push(name);}this._textures[name]=texture;return this;};ShaderMaterial.prototype.setFloat=function(name,value){this._checkUniform(name);this._floats[name]=value;return this;};ShaderMaterial.prototype.setFloats=function(name,value){this._checkUniform(name);this._floatsArrays[name]=value;return this;};ShaderMaterial.prototype.setColor3=function(name,value){this._checkUniform(name);this._colors3[name]=value;return this;};ShaderMaterial.prototype.setColor4=function(name,value){this._checkUniform(name);this._colors4[name]=value;return this;};ShaderMaterial.prototype.setVector2=function(name,value){this._checkUniform(name);this._vectors2[name]=value;return this;};ShaderMaterial.prototype.setVector3=function(name,value){this._checkUniform(name);this._vectors3[name]=value;return this;};ShaderMaterial.prototype.setMatrix=function(name,value){this._checkUniform(name);this._matrices[name]=value;return this;};ShaderMaterial.prototype.isReady=function(){var engine=this.getScene().getEngine();this._effect=engine.createEffect(this._shaderPath,this._options.attributes,this._options.uniforms,this._options.samplers,"",null,this.onCompiled,this.onError);if(!this._effect.isReady()){return false;}return true;};ShaderMaterial.prototype.bind=function(world){if(this._options.uniforms.indexOf("world")!==-1){this._effect.setMatrix("world",world);}if(this._options.uniforms.indexOf("view")!==-1){this._effect.setMatrix("view",this.getScene().getViewMatrix());}if(this._options.uniforms.indexOf("worldView")!==-1){world.multiplyToRef(this.getScene().getViewMatrix(),this._cachedWorldViewMatrix);this._effect.setMatrix("worldView",this._cachedWorldViewMatrix);}if(this._options.uniforms.indexOf("projection")!==-1){this._effect.setMatrix("projection",this.getScene().getProjectionMatrix());}if(this._options.uniforms.indexOf("worldViewProjection")!==-1){this._effect.setMatrix("worldViewProjection",world.multiply(this.getScene().getTransformMatrix()));}for(var name in this._textures){this._effect.setTexture(name,this._textures[name]);}for(name in this._floats){this._effect.setFloat(name,this._floats[name]);}for(name in this._floatsArrays){this._effect.setArray(name,this._floatsArrays[name]);}for(name in this._colors3){this._effect.setColor3(name,this._colors3[name]);}for(name in this._colors4){var color=this._colors4[name];this._effect.setFloat4(name,color.r,color.g,color.b,color.a);}for(name in this._vectors2){this._effect.setVector2(name,this._vectors2[name]);}for(name in this._vectors3){this._effect.setVector3(name,this._vectors3[name]);}for(name in this._matrices){this._effect.setMatrix(name,this._matrices[name]);}};ShaderMaterial.prototype.dispose=function(forceDisposeEffect){for(var name in this._textures){this._textures[name].dispose();}this._textures=[];_super.prototype.dispose.call(this,forceDisposeEffect);};return ShaderMaterial;})(BABYLON.Material);BABYLON.ShaderMaterial=ShaderMaterial;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var VertexData=(function(){function VertexData(){}VertexData.prototype.set=function(data,kind){switch(kind){case BABYLON.VertexBuffer.PositionKind:this.positions=data;break;case BABYLON.VertexBuffer.NormalKind:this.normals=data;break;case BABYLON.VertexBuffer.UVKind:this.uvs=data;break;case BABYLON.VertexBuffer.UV2Kind:this.uv2s=data;break;case BABYLON.VertexBuffer.ColorKind:this.colors=data;break;case BABYLON.VertexBuffer.MatricesIndicesKind:this.matricesIndices=data;break;case BABYLON.VertexBuffer.MatricesWeightsKind:this.matricesWeights=data;break;}};VertexData.prototype.applyToMesh=function(mesh,updatable){this._applyTo(mesh,updatable);};VertexData.prototype.applyToGeometry=function(geometry,updatable){this._applyTo(geometry,updatable);};VertexData.prototype.updateMesh=function(mesh,updateExtends,makeItUnique){this._update(mesh);};VertexData.prototype.updateGeometry=function(geometry,updateExtends,makeItUnique){this._update(geometry);};VertexData.prototype._applyTo=function(meshOrGeometry,updatable){if(this.positions){meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind,this.positions,updatable);}if(this.normals){meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind,this.normals,updatable);}if(this.uvs){meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind,this.uvs,updatable);}if(this.uv2s){meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind,this.uv2s,updatable);}if(this.colors){meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind,this.colors,updatable);}if(this.matricesIndices){meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind,this.matricesIndices,updatable);}if(this.matricesWeights){meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind,this.matricesWeights,updatable);}if(this.indices){meshOrGeometry.setIndices(this.indices);}};VertexData.prototype._update=function(meshOrGeometry,updateExtends,makeItUnique){if(this.positions){meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind,this.positions,updateExtends,makeItUnique);}if(this.normals){meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind,this.normals,updateExtends,makeItUnique);}if(this.uvs){meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind,this.uvs,updateExtends,makeItUnique);}if(this.uv2s){meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind,this.uv2s,updateExtends,makeItUnique);}if(this.colors){meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind,this.colors,updateExtends,makeItUnique);}if(this.matricesIndices){meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind,this.matricesIndices,updateExtends,makeItUnique);}if(this.matricesWeights){meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind,this.matricesWeights,updateExtends,makeItUnique);}if(this.indices){meshOrGeometry.setIndices(this.indices);}};VertexData.prototype.transform=function(matrix){var transformed=BABYLON.Vector3.Zero();if(this.positions){var position=BABYLON.Vector3.Zero();for(var index=0;index0){var verticesCount=positions.length/3;for(var firstIndex=verticesCount-2*(totalYRotationSteps+1);(firstIndex+totalYRotationSteps+2)0){indices.push(index-1);indices.push(index);}}var vertexData=new BABYLON.VertexData();vertexData.indices=indices;vertexData.positions=positions;return vertexData;};VertexData.CreateGround=function(width,height,subdivisions){var indices=[];var positions=[];var normals=[];var uvs=[];var row,col;width=width||1;height=height||1;subdivisions=subdivisions||1;for(row=0;row<=subdivisions;row++){for(col=0;col<=subdivisions;col++){var position=new BABYLON.Vector3((col*width)/subdivisions-(width/2.0),0,((subdivisions-row)*height)/subdivisions-(height/2.0));var normal=new BABYLON.Vector3(0,1.0,0);positions.push(position.x,position.y,position.z);normals.push(normal.x,normal.y,normal.z);uvs.push(col/subdivisions,1.0-row/subdivisions);}}for(row=0;row1){for(var j=0;jdata.length){BABYLON.Tools.Error("Unable to load TGA file - Not enough data");return;}offset+=header.id_length;var use_rle=false;var use_pal=false;var use_rgb=false;var use_grey=false;switch(header.image_type){case TGATools._TYPE_RLE_INDEXED:use_rle=true;case TGATools._TYPE_INDEXED:use_pal=true;break;case TGATools._TYPE_RLE_RGB:use_rle=true;case TGATools._TYPE_RGB:use_rgb=true;break;case TGATools._TYPE_RLE_GREY:use_rle=true;case TGATools._TYPE_GREY:use_grey=true;break;}var pixel_data;var numAlphaBits=header.flags&0xf;var pixel_size=header.pixel_size>>3;var pixel_total=header.width*header.height*pixel_size;var palettes;if(use_pal){palettes=data.subarray(offset,offset+=header.colormap_length*(header.colormap_size>>3));}if(use_rle){pixel_data=new Uint8Array(pixel_total);var c,count,i;var localOffset=0;var pixels=new Uint8Array(pixel_size);while(offset>TGATools._ORIGIN_SHIFT){default:case TGATools._ORIGIN_UL:x_start=0;x_step=1;x_end=header.width;y_start=0;y_step=1;y_end=header.height;break;case TGATools._ORIGIN_BL:x_start=0;x_step=1;x_end=header.width;y_start=header.height-1;y_step=-1;y_end=-1;break;case TGATools._ORIGIN_UR:x_start=header.width-1;x_step=-1;x_end=-1;y_start=0;y_step=1;y_end=header.height;break;case TGATools._ORIGIN_BR:x_start=header.width-1;x_step=-1;x_end=-1;y_start=header.height-1;y_step=-1;y_end=-1;break;}var func='_getImageData'+(use_grey?'Grey':'')+(header.pixel_size)+'bits';var imageData=TGATools[func](header,palettes,pixel_data,y_start,y_step,y_end,x_start,x_step,x_end);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,header.width,header.height,0,gl.RGBA,gl.UNSIGNED_BYTE,imageData);};TGATools._getImageData8bits=function(header,palettes,pixel_data,y_start,y_step,y_end,x_start,x_step,x_end){var image=pixel_data,colormap=palettes;var width=header.width,height=header.height;var color,i=0,x,y;var imageData=new Uint8Array(width*height*4);for(y=y_start;y!==y_end;y+=y_step){for(x=x_start;x!==x_end;x+=x_step,i++){color=image[i];imageData[(x+width*y)*4+3]=255;imageData[(x+width*y)*4+2]=colormap[(color*3)+0];imageData[(x+width*y)*4+1]=colormap[(color*3)+1];imageData[(x+width*y)*4+0]=colormap[(color*3)+2];}}return imageData;};TGATools._getImageData16bits=function(header,palettes,pixel_data,y_start,y_step,y_end,x_start,x_step,x_end){var image=pixel_data;var width=header.width,height=header.height;var color,i=0,x,y;var imageData=new Uint8Array(width*height*4);for(y=y_start;y!==y_end;y+=y_step){for(x=x_start;x!==x_end;x+=x_step,i+=2){color=image[i+0]+(image[i+1]<<8);imageData[(x+width*y)*4+0]=(color&0x7C00)>>7;imageData[(x+width*y)*4+1]=(color&0x03E0)>>2;imageData[(x+width*y)*4+2]=(color&0x001F)>>3;imageData[(x+width*y)*4+3]=(color&0x8000)?0:255;}}return imageData;};TGATools._getImageData24bits=function(header,palettes,pixel_data,y_start,y_step,y_end,x_start,x_step,x_end){var image=pixel_data;var width=header.width,height=header.height;var i=0,x,y;var imageData=new Uint8Array(width*height*4);for(y=y_start;y!==y_end;y+=y_step){for(x=x_start;x!==x_end;x+=x_step,i+=3){imageData[(x+width*y)*4+3]=255;imageData[(x+width*y)*4+2]=image[i+0];imageData[(x+width*y)*4+1]=image[i+1];imageData[(x+width*y)*4+0]=image[i+2];}}return imageData;};TGATools._getImageData32bits=function(header,palettes,pixel_data,y_start,y_step,y_end,x_start,x_step,x_end){var image=pixel_data;var width=header.width,height=header.height;var i=0,x,y;var imageData=new Uint8Array(width*height*4);for(y=y_start;y!==y_end;y+=y_step){for(x=x_start;x!==x_end;x+=x_step,i+=4){imageData[(x+width*y)*4+2]=image[i+0];imageData[(x+width*y)*4+1]=image[i+1];imageData[(x+width*y)*4+0]=image[i+2];imageData[(x+width*y)*4+3]=image[i+3];}}return imageData;};TGATools._getImageDataGrey8bits=function(header,palettes,pixel_data,y_start,y_step,y_end,x_start,x_step,x_end){var image=pixel_data;var width=header.width,height=header.height;var color,i=0,x,y;var imageData=new Uint8Array(width*height*4);for(y=y_start;y!==y_end;y+=y_step){for(x=x_start;x!==x_end;x+=x_step,i++){color=image[i];imageData[(x+width*y)*4+0]=color;imageData[(x+width*y)*4+1]=color;imageData[(x+width*y)*4+2]=color;imageData[(x+width*y)*4+3]=255;}}return imageData;};TGATools._getImageDataGrey16bits=function(header,palettes,pixel_data,y_start,y_step,y_end,x_start,x_step,x_end){var image=pixel_data;var width=header.width,height=header.height;var i=0,x,y;var imageData=new Uint8Array(width*height*4);for(y=y_start;y!==y_end;y+=y_step){for(x=x_start;x!==x_end;x+=x_step,i+=2){imageData[(x+width*y)*4+0]=image[i+0];imageData[(x+width*y)*4+1]=image[i+0];imageData[(x+width*y)*4+2]=image[i+0];imageData[(x+width*y)*4+3]=image[i+1];}}return imageData;};TGATools._TYPE_NO_DATA=0;TGATools._TYPE_INDEXED=1;TGATools._TYPE_RGB=2;TGATools._TYPE_GREY=3;TGATools._TYPE_RLE_INDEXED=9;TGATools._TYPE_RLE_RGB=10;TGATools._TYPE_RLE_GREY=11;TGATools._ORIGIN_MASK=0x30;TGATools._ORIGIN_SHIFT=0x04;TGATools._ORIGIN_BL=0x00;TGATools._ORIGIN_BR=0x01;TGATools._ORIGIN_UL=0x02;TGATools._ORIGIN_UR=0x03;return TGATools;})();Internals.TGATools=TGATools;})(BABYLON.Internals||(BABYLON.Internals={}));var Internals=BABYLON.Internals;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){(function(Internals){var DDS_MAGIC=0x20534444;var DDSD_CAPS=0x1,DDSD_HEIGHT=0x2,DDSD_WIDTH=0x4,DDSD_PITCH=0x8,DDSD_PIXELFORMAT=0x1000,DDSD_MIPMAPCOUNT=0x20000,DDSD_LINEARSIZE=0x80000,DDSD_DEPTH=0x800000;var DDSCAPS_COMPLEX=0x8,DDSCAPS_MIPMAP=0x400000,DDSCAPS_TEXTURE=0x1000;var DDSCAPS2_CUBEMAP=0x200,DDSCAPS2_CUBEMAP_POSITIVEX=0x400,DDSCAPS2_CUBEMAP_NEGATIVEX=0x800,DDSCAPS2_CUBEMAP_POSITIVEY=0x1000,DDSCAPS2_CUBEMAP_NEGATIVEY=0x2000,DDSCAPS2_CUBEMAP_POSITIVEZ=0x4000,DDSCAPS2_CUBEMAP_NEGATIVEZ=0x8000,DDSCAPS2_VOLUME=0x200000;var DDPF_ALPHAPIXELS=0x1,DDPF_ALPHA=0x2,DDPF_FOURCC=0x4,DDPF_RGB=0x40,DDPF_YUV=0x200,DDPF_LUMINANCE=0x20000;function FourCCToInt32(value){return value.charCodeAt(0)+(value.charCodeAt(1)<<8)+(value.charCodeAt(2)<<16)+(value.charCodeAt(3)<<24);}function Int32ToFourCC(value){return String.fromCharCode(value&0xff,(value>>8)&0xff,(value>>16)&0xff,(value>>24)&0xff);}var FOURCC_DXT1=FourCCToInt32("DXT1");var FOURCC_DXT3=FourCCToInt32("DXT3");var FOURCC_DXT5=FourCCToInt32("DXT5");var headerLengthInt=31;var off_magic=0;var off_size=1;var off_flags=2;var off_height=3;var off_width=4;var off_mipmapCount=7;var off_pfFlags=20;var off_pfFourCC=21;var off_RGBbpp=22;var off_RMask=23;var off_GMask=24;var off_BMask=25;var off_AMask=26;var off_caps1=27;var off_caps2=28;;var DDSTools=(function(){function DDSTools(){}DDSTools.GetDDSInfo=function(arrayBuffer){var header=new Int32Array(arrayBuffer,0,headerLengthInt);var mipmapCount=1;if(header[off_flags]&DDSD_MIPMAPCOUNT){mipmapCount=Math.max(1,header[off_mipmapCount]);}return{width:header[off_width],height:header[off_height],mipmapCount:mipmapCount,isFourCC:(header[off_pfFlags]&DDPF_FOURCC)===DDPF_FOURCC,isRGB:(header[off_pfFlags]&DDPF_RGB)===DDPF_RGB,isLuminance:(header[off_pfFlags]&DDPF_LUMINANCE)===DDPF_LUMINANCE,isCube:(header[off_caps2]&DDSCAPS2_CUBEMAP)===DDSCAPS2_CUBEMAP};};DDSTools.GetRGBAArrayBuffer=function(width,height,dataOffset,dataLength,arrayBuffer){var byteArray=new Uint8Array(dataLength);var srcData=new Uint8Array(arrayBuffer);var index=0;for(var y=height-1;y>=0;y--){for(var x=0;x=0;y--){for(var x=0;x=0;y--){for(var x=0;xthis.data.length){this.data.length*=2;}if(!value.__smartArrayFlags){value.__smartArrayFlags={};}value.__smartArrayFlags[this._id]=this._duplicateId;};SmartArray.prototype.pushNoDuplicate=function(value){if(value.__smartArrayFlags&&value.__smartArrayFlags[this._id]===this._duplicateId){return;}this.push(value);};SmartArray.prototype.sort=function(compareFn){this.data.sort(compareFn);};SmartArray.prototype.reset=function(){this.length=0;this._duplicateId++;};SmartArray.prototype.concat=function(array){if(array.length===0){return;}if(this.length+array.length>this.data.length){this.data.length=(this.length+array.length)*2;}for(var index=0;indexthis.data.length){this.data.length=(this.length+array.length)*2;}for(var index=0;index=this.length){return-1;}return position;};SmartArray._GlobalId=0;return SmartArray;})();BABYLON.SmartArray=SmartArray;})(BABYLON||(BABYLON={}));var BABYLON;(function(BABYLON){var CannonJSPlugin=(function(){function CannonJSPlugin(){this._registeredMeshes=[];this._physicsMaterials=[];this.updateBodyPosition=function(mesh){for(var index=0;indexthis.value;case ValueCondition.IsLesser:return this._target[this._property]-1){this._scene._actionManagers.splice(index,1);}};ActionManager.prototype.getScene=function(){return this._scene;};ActionManager.prototype.hasSpecificTriggers=function(triggers){for(var index=0;index-1){return true;}}return false;};Object.defineProperty(ActionManager.prototype,"hasPointerTriggers",{get:function(){for(var index=0;index=ActionManager._OnPickTrigger&&action.trigger<=ActionManager._OnPointerOutTrigger){return true;}}return false;},enumerable:true,configurable:true});Object.defineProperty(ActionManager.prototype,"hasPickTriggers",{get:function(){for(var index=0;index=ActionManager._OnPickTrigger&&action.trigger<=ActionManager._OnCenterPickTrigger){return true;}}return false;},enumerable:true,configurable:true});ActionManager.prototype.registerAction=function(action){if(action.trigger===ActionManager.OnEveryFrameTrigger){if(this.getScene().actionManager!==this){BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");return null;}}this.actions.push(action);action._actionManager=this;action._prepare();return action;};ActionManager.prototype.processTrigger=function(trigger,evt){for(var index=0;index-1){geometries.splice(index,1);}};Geometry.prototype.copy=function(id){var vertexData=new BABYLON.VertexData();vertexData.indices=[];var indices=this.getIndices();for(var index=0;indexto activate gamepad";Gamepads.gamepadDOMInfo.appendChild(buttonAImage);Gamepads.gamepadDOMInfo.appendChild(spanMessage);Gamepads.gamepadDOMInfo.style.position="absolute";Gamepads.gamepadDOMInfo.style.width="100%";Gamepads.gamepadDOMInfo.style.height="48px";Gamepads.gamepadDOMInfo.style.bottom="0px";Gamepads.gamepadDOMInfo.style.backgroundColor="rgba(1, 1, 1, 0.15)";Gamepads.gamepadDOMInfo.style.textAlign="center";Gamepads.gamepadDOMInfo.style.zIndex="10";buttonAImage.style.position="relative";buttonAImage.style.bottom="8px";spanMessage.style.position="relative";spanMessage.style.fontSize="32px";spanMessage.style.bottom="32px";spanMessage.style.color="green";document.body.appendChild(Gamepads.gamepadDOMInfo);};Gamepads.prototype._insertGamepadDOMNotSupported=function(){Gamepads.gamepadDOMInfo=document.createElement("div");var spanMessage=document.createElement("span");spanMessage.innerHTML="gamepad not supported";Gamepads.gamepadDOMInfo.appendChild(spanMessage);Gamepads.gamepadDOMInfo.style.position="absolute";Gamepads.gamepadDOMInfo.style.width="100%";Gamepads.gamepadDOMInfo.style.height="40px";Gamepads.gamepadDOMInfo.style.bottom="0px";Gamepads.gamepadDOMInfo.style.backgroundColor="rgba(1, 1, 1, 0.15)";Gamepads.gamepadDOMInfo.style.textAlign="center";Gamepads.gamepadDOMInfo.style.zIndex="10";spanMessage.style.position="relative";spanMessage.style.fontSize="32px";spanMessage.style.color="red";document.body.appendChild(Gamepads.gamepadDOMInfo);};Gamepads.prototype.dispose=function(){document.body.removeChild(Gamepads.gamepadDOMInfo);};Gamepads.prototype._onGamepadConnected=function(evt){var newGamepad=this._addNewGamepad(evt.gamepad);if(this._callbackGamepadConnected)this._callbackGamepadConnected(newGamepad);this._startMonitoringGamepads();};Gamepads.prototype._addNewGamepad=function(gamepad){if(!this.oneGamepadConnected){this.oneGamepadConnected=true;if(Gamepads.gamepadDOMInfo){document.body.removeChild(Gamepads.gamepadDOMInfo);Gamepads.gamepadDOMInfo=null;}}var newGamepad;if(gamepad.id.search("Xbox 360")!==-1||gamepad.id.search("xinput")!==-1){newGamepad=new BABYLON.Xbox360Pad(gamepad.id,gamepad.index,gamepad);}else{newGamepad=new BABYLON.GenericPad(gamepad.id,gamepad.index,gamepad);}this.babylonGamepads.push(newGamepad);return newGamepad;};Gamepads.prototype._onGamepadDisconnected=function(evt){for(var i in this.babylonGamepads){if(this.babylonGamepads[i].index==evt.gamepad.index){this.babylonGamepads.splice(i,1);break;}}if(this.babylonGamepads.length==0){this._stopMonitoringGamepads();}};Gamepads.prototype._startMonitoringGamepads=function(){if(!this.isMonitoring){this.isMonitoring=true;this._checkGamepadsStatus();}};Gamepads.prototype._stopMonitoringGamepads=function(){this.isMonitoring=false;};Gamepads.prototype._checkGamepadsStatus=function(){var _this=this;this._updateGamepadObjects();for(var i in this.babylonGamepads){this.babylonGamepads[i].update();}if(this.isMonitoring){if(window.requestAnimationFrame){window.requestAnimationFrame(function(){_this._checkGamepadsStatus();});}else if(window.mozRequestAnimationFrame){window.mozRequestAnimationFrame(function(){_this._checkGamepadsStatus();});}else if(window.webkitRequestAnimationFrame){window.webkitRequestAnimationFrame(function(){_this._checkGamepadsStatus();});}}};Gamepads.prototype._updateGamepadObjects=function(){var gamepads=navigator.getGamepads?navigator.getGamepads():(navigator.webkitGetGamepads?navigator.webkitGetGamepads():[]);for(var i=0;i=2){this._leftStick={x:this.browserGamepad.axes[0],y:this.browserGamepad.axes[1]};}if(this.browserGamepad.axes.length>=4){this._rightStick={x:this.browserGamepad.axes[2],y:this.browserGamepad.axes[3]};}}Gamepad.prototype.onleftstickchanged=function(callback){this._onleftstickchanged=callback;};Gamepad.prototype.onrightstickchanged=function(callback){this._onrightstickchanged=callback;};Object.defineProperty(Gamepad.prototype,"leftStick",{get:function(){return this._leftStick;},set:function(newValues){if(this._onleftstickchanged&&(this._leftStick.x!==newValues.x||this._leftStick.y!==newValues.y)){this._onleftstickchanged(newValues);}this._leftStick=newValues;},enumerable:true,configurable:true});Object.defineProperty(Gamepad.prototype,"rightStick",{get:function(){return this._rightStick;},set:function(newValues){if(this._onrightstickchanged&&(this._rightStick.x!==newValues.x||this._rightStick.y!==newValues.y)){this._onrightstickchanged(newValues);}this._rightStick=newValues;},enumerable:true,configurable:true});Gamepad.prototype.update=function(){if(this._leftStick){this.leftStick={x:this.browserGamepad.axes[0],y:this.browserGamepad.axes[1]};}if(this._rightStick){this.rightStick={x:this.browserGamepad.axes[2],y:this.browserGamepad.axes[3]};}};return Gamepad;})();BABYLON.Gamepad=Gamepad;var GenericPad=(function(_super){__extends(GenericPad,_super);function GenericPad(id,index,gamepad){_super.call(this,id,index,gamepad);this.id=id;this.index=index;this.gamepad=gamepad;this._buttons=new Array(gamepad.buttons.length);}GenericPad.prototype.onbuttondown=function(callback){this._onbuttondown=callback;};GenericPad.prototype.onbuttonup=function(callback){this._onbuttonup=callback;};GenericPad.prototype._setButtonValue=function(newValue,currentValue,buttonIndex){if(newValue!==currentValue){if(this._onbuttondown&&newValue===1){this._onbuttondown(buttonIndex);}if(this._onbuttonup&&newValue===0){this._onbuttonup(buttonIndex);}}return newValue;};GenericPad.prototype.update=function(){_super.prototype.update.call(this);for(var index=0;index0.005?0+normalizedLX:0;LSValues.y=Math.abs(normalizedLY)>0.005?0+normalizedLY:0;var RSValues=this._gamepad.rightStick;var normalizedRX=RSValues.x/this.angularSensibility;var normalizedRY=RSValues.y/this.angularSensibility;RSValues.x=Math.abs(normalizedRX)>0.001?0+normalizedRX:0;RSValues.y=Math.abs(normalizedRY)>0.001?0+normalizedRY:0;;var cameraTransform=BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y,this.rotation.x,0);var deltaTransform=BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x,0,-LSValues.y),cameraTransform);this.cameraDirection=this.cameraDirection.add(deltaTransform);this.cameraRotation=this.cameraRotation.add(new BABYLON.Vector3(RSValues.y,RSValues.x,0));};GamepadCamera.prototype.dispose=function(){this._gamepads.dispose();};return GamepadCamera;})(BABYLON.FreeCamera);BABYLON.GamepadCamera=GamepadCamera;})(BABYLON||(BABYLON={}));var __extends=this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d;}__.prototype=b.prototype;d.prototype=new __();};var BABYLON;(function(BABYLON){var LinesMesh=(function(_super){__extends(LinesMesh,_super);function LinesMesh(name,scene,updatable){if(typeof updatable==="undefined"){updatable=false;}_super.call(this,name,scene);this.color=new BABYLON.Color3(1,1,1);this._indices=new Array();this._colorShader=new BABYLON.ShaderMaterial("colorShader",scene,"color",{attributes:["position"],uniforms:["worldViewProjection","color"]});}Object.defineProperty(LinesMesh.prototype,"material",{get:function(){return this._colorShader;},enumerable:true,configurable:true});Object.defineProperty(LinesMesh.prototype,"isPickable",{get:function(){return false;},enumerable:true,configurable:true});Object.defineProperty(LinesMesh.prototype,"checkCollisions",{get:function(){return false;},enumerable:true,configurable:true});LinesMesh.prototype._bind=function(subMesh,effect,wireframe){var engine=this.getScene().getEngine();var indexToBind=this._geometry.getIndexBuffer();engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(),indexToBind,[3],3*4,this._colorShader.getEffect());this._colorShader.setColor3("color",this.color);};LinesMesh.prototype._draw=function(subMesh,useTriangles,instancesCount){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._geometry.getIndexBuffer()){return;}var engine=this.getScene().getEngine();engine.draw(false,subMesh.indexStart,subMesh.indexCount);};LinesMesh.prototype.intersects=function(ray,fastCheck){return null;};LinesMesh.prototype.dispose=function(doNotRecurse){this._colorShader.dispose();_super.prototype.dispose.call(this,doNotRecurse);};return LinesMesh;})(BABYLON.Mesh);BABYLON.LinesMesh=LinesMesh;})(BABYLON||(BABYLON={}));