text: function lerp(e,t,i){return e+(t-e)*i}function clampAngle(e,t,i){return e<-2*Math.PI&&(e+=2*Math.PI),e>2*Math.PI&&(e-=2*Math.PI),e=Math.max(t,e),e=Math.min(i,e)}function nextLowestPowerOfTwo(e){return Math.max(Math.min(Math.pow(2,Math.floor(Math.log(e)/Math.log(2))),2048),1)}function nextHighestPowerOfTwo(e){return Math.max(Math.min(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))),2048),1)}function ClassCallback(e,t){return function(){return t.apply(e,arguments)}}function DownloadBinary(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(){t(200==this.status?this.response:!1)},i.send()}function LineLineIntersection2D(e,t,i,n,r){var s=(t[0]-e[0])*(n[1]-i[1])-(t[1]-e[1])*(n[0]-i[0]);if(0==s)return!1;var a=((e[1]-i[1])*(n[0]-i[0])-(e[0]-i[0])*(n[1]-i[1]))/s,o=((e[1]-i[1])*(t[0]-e[0])-(e[0]-i[0])*(t[1]-e[1]))/s;return 0>a||a>1||0>o||o>1?!1:(r&&(r[0]=e[0]+a*(t[0]-e[0]),r[1]=e[1]+a*(t[1]-e[1])),!0)}function LineRectIntersection2D(e,t,i,n){return LineLineIntersection2D(e,t,i,[i[0],n[1]])||LineLineIntersection2D(e,t,[i[0],n[1]],n)||LineLineIntersection2D(e,t,n,[n[0],i[1]])||LineLineIntersection2D(e,t,i,[n[0],i[1]])?!0:!1}function PointInTriangle2D(e,t,i,n){var r=(t[1]-i[1])*(e[0]-i[0])+(i[0]-t[0])*(e[1]-i[1]);if(0==r)return!1;var s=((t[1]-i[1])*(n[0]-i[0])+(i[0]-t[0])*(n[1]-i[1]))/r,a=((i[1]-e[1])*(n[0]-i[0])+(e[0]-i[0])*(n[1]-i[1]))/r;return s>=0&&a>=0&&1>=s+a?!0:!1}!function(){"use strict";var e={};"undefined"==typeof exports?"function"==typeof define&&"object"==typeof define.amd&&define.amd?(e.exports={},define(function(){return e.exports})):e.exports=window:e.exports=exports,function(e){var t={};if(!i)var i=1e-6;t.create=function(){return new Float32Array(2)},t.clone=function(e){var t=new Float32Array(2);return t[0]=e[0],t[1]=e[1],t},t.fromValues=function(e,t){var i=new Float32Array(2);return i[0]=e,i[1]=t,i},t.copy=function(e,t){return e[0]=t[0],e[1]=t[1],e},t.set=function(e,t,i){return e[0]=t,e[1]=i,e},t.add=function(e,t,i){return e[0]=t[0]+i[0],e[1]=t[1]+i[1],e},t.sub=t.subtract=function(e,t,i){return e[0]=t[0]-i[0],e[1]=t[1]-i[1],e},t.mul=t.multiply=function(e,t,i){return e[0]=t[0]*i[0],e[1]=t[1]*i[1],e},t.div=t.divide=function(e,t,i){return e[0]=t[0]/i[0],e[1]=t[1]/i[1],e},t.min=function(e,t,i){return e[0]=Math.min(t[0],i[0]),e[1]=Math.min(t[1],i[1]),e},t.max=function(e,t,i){return e[0]=Math.max(t[0],i[0]),e[1]=Math.max(t[1],i[1]),e},t.scale=function(e,t,i){return e[0]=t[0]*i,e[1]=t[1]*i,e},t.dist=t.distance=function(e,t){var i=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(i*i+n*n)},t.sqrDist=t.squaredDistance=function(e,t){var i=t[0]-e[0],n=t[1]-e[1];return i*i+n*n},t.len=t.length=function(e){var t=e[0],i=e[1];return Math.sqrt(t*t+i*i)},t.sqrLen=t.squaredLength=function(e){var t=e[0],i=e[1];return t*t+i*i},t.negate=function(e,t){return e[0]=-t[0],e[1]=-t[1],e},t.normalize=function(e,t){var i=t[0],n=t[1],r=i*i+n*n;return r>0&&(r=1/Math.sqrt(r),e[0]=t[0]*r,e[1]=t[1]*r),e},t.dot=function(e,t){return e[0]*t[0]+e[1]*t[1]},t.cross=function(e,t,i){var n=t[0]*i[1]-t[1]*i[0];return e[0]=e[1]=0,e[2]=n,e},t.lerp=function(e,t,i,n){var r=t[0],s=t[1];return e[0]=r+n*(i[0]-r),e[1]=s+n*(i[1]-s),e},t.transformMat2=function(e,t,i){var n=t[0],r=t[1];return e[0]=n*i[0]+r*i[1],e[1]=n*i[2]+r*i[3],e},t.forEach=function(){var e=new Float32Array(2);return function(t,i,n,r,s,a){var o,h;for(i||(i=2),n||(n=0),h=r?Math.min(r*i+n,t.length):t.length,o=n;h>o;o+=i)e[0]=t[o],e[1]=t[o+1],s(e,e,a),t[o]=e[0],t[o+1]=e[1];return t}}(),t.str=function(e){return"vec2("+e[0]+", "+e[1]+")"},"undefined"!=typeof e&&(e.vec2=t);var n={};if(!i)var i=1e-6;n.create=function(){return new Float32Array(3)},n.clone=function(e){var t=new Float32Array(3);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t},n.fromValues=function(e,t,i){var n=new Float32Array(3);return n[0]=e,n[1]=t,n[2]=i,n},n.copy=function(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},n.set=function(e,t,i,n){return e[0]=t,e[1]=i,e[2]=n,e},n.add=function(e,t,i){return e[0]=t[0]+i[0],e[1]=t[1]+i[1],e[2]=t[2]+i[2],e},n.sub=n.subtract=function(e,t,i){return e[0]=t[0]-i[0],e[1]=t[1]-i[1],e[2]=t[2]-i[2],e},n.mul=n.multiply=function(e,t,i){return e[0]=t[0]*i[0],e[1]=t[1]*i[1],e[2]=t[2]*i[2],e},n.div=n.divide=function(e,t,i){return e[0]=t[0]/i[0],e[1]=t[1]/i[1],e[2]=t[2]/i[2],e},n.min=function(e,t,i){return e[0]=Math.min(t[0],i[0]),e[1]=Math.min(t[1],i[1]),e[2]=Math.min(t[2],i[2]),e},n.max=function(e,t,i){return e[0]=Math.max(t[0],i[0]),e[1]=Math.max(t[1],i[1]),e[2]=Math.max(t[2],i[2]),e},n.scale=function(e,t,i){return e[0]=t[0]*i,e[1]=t[1]*i,e[2]=t[2]*i,e},n.dist=n.distance=function(e,t){var i=t[0]-e[0],n=t[1]-e[1],r=t[2]-e[2];return Math.sqrt(i*i+n*n+r*r)},n.sqrDist=n.squaredDistance=function(e,t){var i=t[0]-e[0],n=t[1]-e[1],r=t[2]-e[2];return i*i+n*n+r*r},n.len=n.length=function(e){var t=e[0],i=e[1],n=e[2];return Math.sqrt(t*t+i*i+n*n)},n.sqrLen=n.squaredLength=function(e){var t=e[0],i=e[1],n=e[2];return t*t+i*i+n*n},n.negate=function(e,t){return e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e},n.normalize=function(e,t){var i=t[0],n=t[1],r=t[2],s=i*i+n*n+r*r;return s>0&&(s=1/Math.sqrt(s),e[0]=t[0]*s,e[1]=t[1]*s,e[2]=t[2]*s),e},n.dot=function(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]},n.cross=function(e,t,i){var n=t[0],r=t[1],s=t[2],a=i[0],o=i[1],h=i[2];return e[0]=r*h-s*o,e[1]=s*a-n*h,e[2]=n*o-r*a,e},n.lerp=function(e,t,i,n){var r=t[0],s=t[1],a=t[2];return e[0]=r+n*(i[0]-r),e[1]=s+n*(i[1]-s),e[2]=a+n*(i[2]-a),e},n.transformMat4=function(e,t,i){var n=t[0],r=t[1],s=t[2];return e[0]=i[0]*n+i[4]*r+i[8]*s+i[12],e[1]=i[1]*n+i[5]*r+i[9]*s+i[13],e[2]=i[2]*n+i[6]*r+i[10]*s+i[14],e},n.transformQuat=function(e,t,i){var n=t[0],r=t[1],s=t[2],a=i[0],o=i[1],h=i[2],c=i[3],u=c*n+o*s-h*r,l=c*r+h*n-a*s,d=c*s+a*r-o*n,f=-a*n-o*r-h*s;return e[0]=u*c+f*-a+l*-h-d*-o,e[1]=l*c+f*-o+d*-a-u*-h,e[2]=d*c+f*-h+u*-o-l*-a,e},n.forEach=function(){var e=new Float32Array(3);return function(t,i,n,r,s,a){var o,h;for(i||(i=3),n||(n=0),h=r?Math.min(r*i+n,t.length):t.length,o=n;h>o;o+=i)e[0]=t[o],e[1]=t[o+1],e[2]=t[o+2],s(e,e,a),t[o]=e[0],t[o+1]=e[1],t[o+2]=e[2];return t}}(),n.str=function(e){return"vec3("+e[0]+", "+e[1]+", "+e[2]+")"},"undefined"!=typeof e&&(e.vec3=n);var r={};if(!i)var i=1e-6;r.create=function(){return new Float32Array(4)},r.clone=function(e){var t=new Float32Array(4);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t},r.fromValues=function(e,t,i,n){var r=new Float32Array(4);return r[0]=e,r[1]=t,r[2]=i,r[3]=n,r},r.copy=function(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e},r.set=function(e,t,i,n,r){return e[0]=t,e[1]=i,e[2]=n,e[3]=r,e},r.add=function(e,t,i){return e[0]=t[0]+i[0],e[1]=t[1]+i[1],e[2]=t[2]+i[2],e[3]=t[3]+i[3],e},r.sub=r.subtract=function(e,t,i){return e[0]=t[0]-i[0],e[1]=t[1]-i[1],e[2]=t[2]-i[2],e[3]=t[3]-i[3],e},r.mul=r.multiply=function(e,t,i){return e[0]=t[0]*i[0],e[1]=t[1]*i[1],e[2]=t[2]*i[2],e[3]=t[3]*i[3],e},r.div=r.divide=function(e,t,i){return e[0]=t[0]/i[0],e[1]=t[1]/i[1],e[2]=t[2]/i[2],e[3]=t[3]/i[3],e},r.min=function(e,t,i){return e[0]=Math.min(t[0],i[0]),e[1]=Math.min(t[1],i[1]),e[2]=Math.min(t[2],i[2]),e[3]=Math.min(t[3],i[3]),e},r.max=function(e,t,i){return e[0]=Math.max(t[0],i[0]),e[1]=Math.max(t[1],i[1]),e[2]=Math.max(t[2],i[2]),e[3]=Math.max(t[3],i[3]),e},r.scale=function(e,t,i){return e[0]=t[0]*i,e[1]=t[1]*i,e[2]=t[2]*i,e[3]=t[3]*i,e},r.dist=r.distance=function(e,t){var i=t[0]-e[0],n=t[1]-e[1],r=t[2]-e[2],s=t[3]-e[3];return Math.sqrt(i*i+n*n+r*r+s*s)},r.sqrDist=r.squaredDistance=function(e,t){var i=t[0]-e[0],n=t[1]-e[1],r=t[2]-e[2],s=t[3]-e[3];return i*i+n*n+r*r+s*s},r.len=r.length=function(e){var t=e[0],i=e[1],n=e[2],r=e[3];return Math.sqrt(t*t+i*i+n*n+r*r)},r.sqrLen=r.squaredLength=function(e){var t=e[0],i=e[1],n=e[2],r=e[3];return t*t+i*i+n*n+r*r},r.negate=function(e,t){return e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e[3]=-t[3],e},r.normalize=function(e,t){var i=t[0],n=t[1],r=t[2],s=t[3],a=i*i+n*n+r*r+s*s;return a>0&&(a=1/Math.sqrt(a),e[0]=t[0]*a,e[1]=t[1]*a,e[2]=t[2]*a,e[3]=t[3]*a),e},r.dot=function(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]},r.lerp=function(e,t,i,n){var r=t[0],s=t[1],a=t[2],o=t[3];return e[0]=r+n*(i[0]-r),e[1]=s+n*(i[1]-s),e[2]=a+n*(i[2]-a),e[3]=o+n*(i[3]-o),e},r.transformMat4=function(e,t,i){var n=t[0],r=t[1],s=t[2],a=t[3];return e[0]=i[0]*n+i[4]*r+i[8]*s+i[12]*a,e[1]=i[1]*n+i[5]*r+i[9]*s+i[13]*a,e[2]=i[2]*n+i[6]*r+i[10]*s+i[14]*a,e[3]=i[3]*n+i[7]*r+i[11]*s+i[15]*a,e},r.transformQuat=function(e,t,i){var n=t[0],r=t[1],s=t[2],a=i[0],o=i[1],h=i[2],c=i[3],u=c*n+o*s-h*r,l=c*r+h*n-a*s,d=c*s+a*r-o*n,f=-a*n-o*r-h*s;return e[0]=u*c+f*-a+l*-h-d*-o,e[1]=l*c+f*-o+d*-a-u*-h,e[2]=d*c+f*-h+u*-o-l*-a,e},r.forEach=function(){var e=new Float32Array(4);return function(t,i,n,r,s,a){var o,h;for(i||(i=4),n||(n=0),h=r?Math.min(r*i+n,t.length):t.length,o=n;h>o;o+=i)e[0]=t[o],e[1]=t[o+1],e[2]=t[o+2],e[3]=t[o+3],s(e,e,a),t[o]=e[0],t[o+1]=e[1],t[o+2]=e[2],t[o+3]=e[3];return t}}(),r.str=function(e){return"vec4("+e[0]+", "+e[1]+", "+e[2]+", "+e[3]+")"},"undefined"!=typeof e&&(e.vec4=r);var s={},a=new Float32Array([1,0,0,1]);if(!i)var i=1e-6;s.create=function(){return new Float32Array(a)},s.clone=function(e){var t=new Float32Array(4);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t},s.copy=function(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e},s.identity=function(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=1,e},s.transpose=function(e,t){if(e===t){var i=t[1];e[1]=t[2],e[2]=i}else e[0]=t[0],e[1]=t[2],e[2]=t[1],e[3]=t[3];return e},s.invert=function(e,t){var i=t[0],n=t[1],r=t[2],s=t[3],a=i*s-r*n;return a?(a=1/a,e[0]=s*a,e[1]=-n*a,e[2]=-r*a,e[3]=i*a,e):null},s.adjoint=function(e,t){var i=t[0];return e[0]=t[3],e[1]=-t[1],e[2]=-t[2],e[3]=i,e},s.determinant=function(e){return e[0]*e[3]-e[2]*e[1]},s.mul=s.multiply=function(e,t,i){var n=t[0],r=t[1],s=t[2],a=t[3],o=i[0],h=i[1],c=i[2],u=i[3];return e[0]=n*o+r*c,e[1]=n*h+r*u,e[2]=s*o+a*c,e[3]=s*h+a*u,e},s.rotate=function(e,t,i){var n=t[0],r=t[1],s=t[2],a=t[3],o=Math.sin(i),h=Math.cos(i);return e[0]=n*h+r*o,e[1]=n*-o+r*h,e[2]=s*h+a*o,e[3]=s*-o+a*h,e},s.scale=function(e,t,i){var n=t[0],r=t[1],s=t[2],a=t[3],o=i[0],h=i[1];return e[0]=n*o,e[1]=r*h,e[2]=s*o,e[3]=a*h,e},s.str=function(e){return"mat2("+e[0]+", "+e[1]+", "+e[2]+", "+e[3]+")"},"undefined"!=typeof e&&(e.mat2=s);var o={},h=new Float32Array([1,0,0,0,1,0,0,0,1]);if(!i)var i=1e-6;o.create=function(){return new Float32Array(h)},o.clone=function(e){var t=new Float32Array(9);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t},o.copy=function(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e},o.identity=function(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e},o.transpose=function(e,t){if(e===t){var i=t[1],n=t[2],r=t[5];e[1]=t[3],e[2]=t[6],e[3]=i,e[5]=t[7],e[6]=n,e[7]=r}else e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8];return e},o.invert=function(e,t){var i=t[0],n=t[1],r=t[2],s=t[3],a=t[4],o=t[5],h=t[6],c=t[7],u=t[8],l=u*a-o*c,d=-u*s+o*h,f=c*s-a*h,m=i*l+n*d+r*f;return m?(m=1/m,e[0]=l*m,e[1]=(-u*n+r*c)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(u*i-r*h)*m,e[5]=(-o*i+r*s)*m,e[6]=f*m,e[7]=(-c*i+n*h)*m,e[8]=(a*i-n*s)*m,e):null},o.adjoint=function(e,t){var i=t[0],n=t[1],r=t[2],s=t[3],a=t[4],o=t[5],h=t[6],c=t[7],u=t[8];return e[0]=a*u-o*c,e[1]=r*c-n*u,e[2]=n*o-r*a,e[3]=o*h-s*u,e[4]=i*u-r*h,e[5]=r*s-i*o,e[6]=s*c-a*h,e[7]=n*h-i*c,e[8]=i*a-n*s,e},o.determinant=function(e){var t=e[0],i=e[1],n=e[2],r=e[3],s=e[4],a=e[5],o=e[6],h=e[7],c=e[8];return t*(c*s-a*h)+i*(-c*r+a*o)+n*(h*r-s*o)},o.mul=o.multiply=function(e,t,i){var n=t[0],r=t[1],s=t[2],a=t[3],o=t[4],h=t[5],c=t[6],u=t[7],l=t[8],d=i[0],f=i[1],m=i[2],p=i[3],g=i[4],v=i[5],b=i[6],T=i[7],x=i[8];return e[0]=d*n+f*a+m*c,e[1]=d*r+f*o+m*u,e[2]=d*s+f*h+m*l,e[3]=p*n+g*a+v*c,e[4]=p*r+g*o+v*u,e[5]=p*s+g*h+v*l,e[6]=b*n+T*a+x*c,e[7]=b*r+T*o+x*u,e[8]=b*s+T*h+x*l,e},o.str=function(e){return"mat3("+e[0]+", "+e[1]+", "+e[2]+", "+e[3]+", "+e[4]+", "+e[5]+", "+e[6]+", "+e[7]+", "+e[8]+")"},"undefined"!=typeof e&&(e.mat3=o);var c={},u=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(!i)var i=1e-6;c.create=function(){return new Float32Array(u)},c.clone=function(e){var t=new Float32Array(16);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},c.copy=function(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},c.identity=function(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e},c.transpose=function(e,t){if(e===t){var i=t[1],n=t[2],r=t[3],s=t[6],a=t[7],o=t[11];e[1]=t[4],e[2]=t[8],e[3]=t[12],e[4]=i,e[6]=t[9],e[7]=t[13],e[8]=n,e[9]=s,e[11]=t[14],e[12]=r,e[13]=a,e[14]=o}else e[0]=t[0],e[1]=t[4],e[2]=t[8],e[3]=t[12],e[4]=t[1],e[5]=t[5],e[6]=t[9],e[7]=t[13],e[8]=t[2],e[9]=t[6],e[10]=t[10],e[11]=t[14],e[12]=t[3],e[13]=t[7],e[14]=t[11],e[15]=t[15];return e},c.invert=function(e,t){var i=t[0],n=t[1],r=t[2],s=t[3],a=t[4],o=t[5],h=t[6],c=t[7],u=t[8],l=t[9],d=t[10],f=t[11],m=t[12],p=t[13],g=t[14],v=t[15],b=i*o-n*a,T=i*h-r*a,x=i*c-s*a,E=n*h-r*o,w=n*c-s*o,S=r*c-s*h,y=u*p-l*m,M=u*g-d*m,R=u*v-f*m,_=l*g-d*p,D=l*v-f*p,C=d*v-f*g,P=b*C-T*D+x*_+E*R-w*M+S*y;return P?(P=1/P,e[0]=(o*C-h*D+c*_)*P,e[1]=(r*D-n*C-s*_)*P,e[2]=(p*S-g*w+v*E)*P,e[3]=(d*w-l*S-f*E)*P,e[4]=(h*R-a*C-c*M)*P,e[5]=(i*C-r*R+s*M)*P,e[6]=(g*x-m*S-v*T)*P,e[7]=(u*S-d*x+f*T)*P,e[8]=(a*D-o*R+c*y)*P,e[9]=(n*R-i*D-s*y)*P,e[10]=(m*w-p*x+v*b)*P,e[11]=(l*x-u*w-f*b)*P,e[12]=(o*M-a*_-h*y)*P,e[13]=(i*_-n*M+r*y)*P,e[14]=(p*T-m*E-g*b)*P,e[15]=(u*E-l*T+d*b)*P,e):null},c.adjoint=function(e,t){var i=t[0],n=t[1],r=t[2],s=t[3],a=t[4],o=t[5],h=t[6],c=t[7],u=t[8],l=t[9],d=t[10],f=t[11],m=t[12],p=t[13],g=t[14],v=t[15];return e[0]=o*(d*v-f*g)-l*(h*v-c*g)+p*(h*f-c*d),e[1]=-(n*(d*v-f*g)-l*(r*v-s*g)+p*(r*f-s*d)),e[2]=n*(h*v-c*g)-o*(r*v-s*g)+p*(r*c-s*h),e[3]=-(n*(h*f-c*d)-o*(r*f-s*d)+l*(r*c-s*h)),e[4]=-(a*(d*v-f*g)-u*(h*v-c*g)+m*(h*f-c*d)),e[5]=i*(d*v-f*g)-u*(r*v-s*g)+m*(r*f-s*d),e[6]=-(i*(h*v-c*g)-a*(r*v-s*g)+m*(r*c-s*h)),e[7]=i*(h*f-c*d)-a*(r*f-s*d)+u*(r*c-s*h),e[8]=a*(l*v-f*p)-u*(o*v-c*p)+m*(o*f-c*l),e[9]=-(i*(l*v-f*p)-u*(n*v-s*p)+m*(n*f-s*l)),e[10]=i*(o*v-c*p)-a*(n*v-s*p)+m*(n*c-s*o),e[11]=-(i*(o*f-c*l)-a*(n*f-s*l)+u*(n*c-s*o)),e[12]=-(a*(l*g-d*p)-u*(o*g-h*p)+m*(o*d-h*l)),e[13]=i*(l*g-d*p)-u*(n*g-r*p)+m*(n*d-r*l),e[14]=-(i*(o*g-h*p)-a*(n*g-r*p)+m*(n*h-r*o)),e[15]=i*(o*d-h*l)-a*(n*d-r*l)+u*(n*h-r*o),e},c.determinant=function(e){var t=e[0],i=e[1],n=e[2],r=e[3],s=e[4],a=e[5],o=e[6],h=e[7],c=e[8],u=e[9],l=e[10],d=e[11],f=e[12],m=e[13],p=e[14],g=e[15],v=t*a-i*s,b=t*o-n*s,T=t*h-r*s,x=i*o-n*a,E=i*h-r*a,w=n*h-r*o,S=c*m-u*f,y=c*p-l*f,M=c*g-d*f,R=u*p-l*m,_=u*g-d*m,D=l*g-d*p;return v*D-b*_+T*R+x*M-E*y+w*S},c.mul=c.multiply=function(e,t,i){var n=t[0],r=t[1],s=t[2],a=t[3],o=t[4],h=t[5],c=t[6],u=t[7],l=t[8],d=t[9],f=t[10],m=t[11],p=t[12],g=t[13],v=t[14],b=t[15],T=i[0],x=i[1],E=i[2],w=i[3];return e[0]=T*n+x*o+E*l+w*p,e[1]=T*r+x*h+E*d+w*g,e[2]=T*s+x*c+E*f+w*v,e[3]=T*a+x*u+E*m+w*b,T=i[4],x=i[5],E=i[6],w=i[7],e[4]=T*n+x*o+E*l+w*p,e[5]=T*r+x*h+E*d+w*g,e[6]=T*s+x*c+E*f+w*v,e[7]=T*a+x*u+E*m+w*b,T=i[8],x=i[9],E=i[10],w=i[11],e[8]=T*n+x*o+E*l+w*p,e[9]=T*r+x*h+E*d+w*g,e[10]=T*s+x*c+E*f+w*v,e[11]=T*a+x*u+E*m+w*b,T=i[12],x=i[13],E=i[14],w=i[15],e[12]=T*n+x*o+E*l+w*p,e[13]=T*r+x*h+E*d+w*g,e[14]=T*s+x*c+E*f+w*v,e[15]=T*a+x*u+E*m+w*b,e},c.translate=function(e,t,i){var n,r,s,a,o,h,c,u,l,d,f,m,p=i[0],g=i[1],v=i[2];return t===e?(e[12]=t[0]*p+t[4]*g+t[8]*v+t[12],e[13]=t[1]*p+t[5]*g+t[9]*v+t[13],e[14]=t[2]*p+t[6]*g+t[10]*v+t[14],e[15]=t[3]*p+t[7]*g+t[11]*v+t[15]):(n=t[0],r=t[1],s=t[2],a=t[3],o=t[4],h=t[5],c=t[6],u=t[7],l=t[8],d=t[9],f=t[10],m=t[11],e[0]=n,e[1]=r,e[2]=s,e[3]=a,e[4]=o,e[5]=h,e[6]=c,e[7]=u,e[8]=l,e[9]=d,e[10]=f,e[11]=m,e[12]=n*p+o*g+l*v+t[12],e[13]=r*p+h*g+d*v+t[13],e[14]=s*p+c*g+f*v+t[14],e[15]=a*p+u*g+m*v+t[15]),e},c.scale=function(e,t,i){var n=i[0],r=i[1],s=i[2];return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e[3]=t[3]*n,e[4]=t[4]*r,e[5]=t[5]*r,e[6]=t[6]*r,e[7]=t[7]*r,e[8]=t[8]*s,e[9]=t[9]*s,e[10]=t[10]*s,e[11]=t[11]*s,e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},c.rotate=function(e,t,n,r){var s,a,o,h,c,u,l,d,f,m,p,g,v,b,T,x,E,w,S,y,M,R,_,D,C=r[0],P=r[1],F=r[2],N=Math.sqrt(C*C+P*P+F*F);return Math.abs(N)<i?null:(N=1/N,C*=N,P*=N,F*=N,s=Math.sin(n),a=Math.cos(n),o=1-a,h=t[0],c=t[1],u=t[2],l=t[3],d=t[4],f=t[5],m=t[6],p=t[7],g=t[8],v=t[9],b=t[10],T=t[11],x=C*C*o+a,E=P*C*o+F*s,w=F*C*o-P*s,S=C*P*o-F*s,y=P*P*o+a,M=F*P*o+C*s,R=C*F*o+P*s,_=P*F*o-C*s,D=F*F*o+a,e[0]=h*x+d*E+g*w,e[1]=c*x+f*E+v*w,e[2]=u*x+m*E+b*w,e[3]=l*x+p*E+T*w,e[4]=h*S+d*y+g*M,e[5]=c*S+f*y+v*M,e[6]=u*S+m*y+b*M,e[7]=l*S+p*y+T*M,e[8]=h*R+d*_+g*D,e[9]=c*R+f*_+v*D,e[10]=u*R+m*_+b*D,e[11]=l*R+p*_+T*D,t!==e&&(e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e)},c.rotateX=function(e,t,i){var n=Math.sin(i),r=Math.cos(i),s=t[4],a=t[5],o=t[6],h=t[7],c=t[8],u=t[9],l=t[10],d=t[11];return t!==e&&(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[4]=s*r+c*n,e[5]=a*r+u*n,e[6]=o*r+l*n,e[7]=h*r+d*n,e[8]=c*r-s*n,e[9]=u*r-a*n,e[10]=l*r-o*n,e[11]=d*r-h*n,e},c.rotateY=function(e,t,i){var n=Math.sin(i),r=Math.cos(i),s=t[0],a=t[1],o=t[2],h=t[3],c=t[8],u=t[9],l=t[10],d=t[11];return t!==e&&(e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=s*r-c*n,e[1]=a*r-u*n,e[2]=o*r-l*n,e[3]=h*r-d*n,e[8]=s*n+c*r,e[9]=a*n+u*r,e[10]=o*n+l*r,e[11]=h*n+d*r,e},c.rotateZ=function(e,t,i){var n=Math.sin(i),r=Math.cos(i),s=t[0],a=t[1],o=t[2],h=t[3],c=t[4],u=t[5],l=t[6],d=t[7];return t!==e&&(e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=s*r+c*n,e[1]=a*r+u*n,e[2]=o*r+l*n,e[3]=h*r+d*n,e[4]=c*r-s*n,e[5]=u*r-a*n,e[6]=l*r-o*n,e[7]=d*r-h*n,e},c.fromRotationTranslation=function(e,t,i){var n=t[0],r=t[1],s=t[2],a=t[3],o=n+n,h=r+r,c=s+s,u=n*o,l=n*h,d=n*c,f=r*h,m=r*c,p=s*c,g=a*o,v=a*h,b=a*c;return e[0]=1-(f+p),e[1]=l+b,e[2]=d-v,e[3]=0,e[4]=l-b,e[5]=1-(u+p),e[6]=m+g,e[7]=0,e[8]=d+v,e[9]=m-g,e[10]=1-(u+f),e[11]=0,e[12]=i[0],e[13]=i[1],e[14]=i[2],e[15]=1,e},c.frustum=function(e,t,i,n,r,s,a){var o=1/(i-t),h=1/(r-n),c=1/(s-a);return e[0]=2*s*o,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=2*s*h,e[6]=0,e[7]=0,e[8]=(i+t)*o,e[9]=(r+n)*h,e[10]=(a+s)*c,e[11]=-1,e[12]=0,e[13]=0,e[14]=a*s*2*c,e[15]=0,e},c.perspective=function(e,t,i,n,r){var s=1/Math.tan(t/2),a=1/(n-r);return e[0]=s/i,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=s,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=(r+n)*a,e[11]=-1,e[12]=0,e[13]=0,e[14]=2*r*n*a,e[15]=0,e},c.ortho=function(e,t,i,n,r,s,a){var o=1/(t-i),h=1/(n-r),c=1/(s-a);return e[0]=-2*o,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=-2*h,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=2*c,e[11]=0,e[12]=(t+i)*o,e[13]=(r+n)*h,e[14]=(a+s)*c,e[15]=1,e},c.lookAt=function(e,t,n,r){var s,a,o,h,u,l,d,f,m,p,g=t[0],v=t[1],b=t[2],T=r[0],x=r[1],E=r[2],w=n[0],S=n[1],y=n[2];return Math.abs(g-w)<i&&Math.abs(v-S)<i&&Math.abs(b-y)<i?c.identity(e):(d=g-w,f=v-S,m=b-y,p=1/Math.sqrt(d*d+f*f+m*m),d*=p,f*=p,m*=p,s=x*m-E*f,a=E*d-T*m,o=T*f-x*d,p=Math.sqrt(s*s+a*a+o*o),p?(p=1/p,s*=p,a*=p,o*=p):(s=0,a=0,o=0),h=f*o-m*a,u=m*s-d*o,l=d*a-f*s,p=Math.sqrt(h*h+u*u+l*l),p?(p=1/p,h*=p,u*=p,l*=p):(h=0,u=0,l=0),e[0]=s,e[1]=h,e[2]=d,e[3]=0,e[4]=a,e[5]=u,e[6]=f,e[7]=0,e[8]=o,e[9]=l,e[10]=m,e[11]=0,e[12]=-(s*g+a*v+o*b),e[13]=-(h*g+u*v+l*b),e[14]=-(d*g+f*v+m*b),e[15]=1,e)},c.str=function(e){return"mat4("+e[0]+", "+e[1]+", "+e[2]+", "+e[3]+", "+e[4]+", "+e[5]+", "+e[6]+", "+e[7]+", "+e[8]+", "+e[9]+", "+e[10]+", "+e[11]+", "+e[12]+", "+e[13]+", "+e[14]+", "+e[15]+")"},"undefined"!=typeof e&&(e.mat4=c);var l={},d=new Float32Array([0,0,0,1]);if(!i)var i=1e-6;l.create=function(){return new Float32Array(d)},l.clone=r.clone,l.fromValues=r.fromValues,l.copy=r.copy,l.set=r.set,l.identity=function(e){return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e},l.setAxisAngle=function(e,t,i){i=.5*i;var n=Math.sin(i);return e[0]=n*t[0],e[1]=n*t[1],e[2]=n*t[2],e[3]=Math.cos(i),e},l.add=r.add,l.mul=l.multiply=function(e,t,i){var n=t[0],r=t[1],s=t[2],a=t[3],o=i[0],h=i[1],c=i[2],u=i[3];return e[0]=n*u+a*o+r*c-s*h,e[1]=r*u+a*h+s*o-n*c,e[2]=s*u+a*c+n*h-r*o,e[3]=a*u-n*o-r*h-s*c,e},l.scale=r.scale,l.rotateX=function(e,t,i){i*=.5;var n=t[0],r=t[1],s=t[2],a=t[3],o=Math.sin(i),h=Math.cos(i);return e[0]=n*h+a*o,e[1]=r*h+s*o,e[2]=s*h-r*o,e[3]=a*h-n*o,e},l.rotateY=function(e,t,i){i*=.5;var n=t[0],r=t[1],s=t[2],a=t[3],o=Math.sin(i),h=Math.cos(i);return e[0]=n*h-s*o,e[1]=r*h+a*o,e[2]=s*h+n*o,e[3]=a*h-r*o,e},l.rotateZ=function(e,t,i){i*=.5;var n=t[0],r=t[1],s=t[2],a=t[3],o=Math.sin(i),h=Math.cos(i);return e[0]=n*h+r*o,e[1]=r*h-n*o,e[2]=s*h+a*o,e[3]=a*h-s*o,e},l.calculateW=function(e,t){var i=t[0],n=t[1],r=t[2];return e[0]=i,e[1]=n,e[2]=r,e[3]=-Math.sqrt(Math.abs(1-i*i-n*n-r*r)),e},l.dot=r.dot,l.lerp=r.lerp,l.slerp=function(e,t,i,n){var r,s,a,o,h=t[0],c=t[1],u=t[2],l=t[3],d=i[0],f=i[1],m=i[2],p=t[3],g=h*d+c*f+u*m+l*p;return Math.abs(g)>=1?(e!==t&&(e[0]=h,e[1]=c,e[2]=u,e[3]=l),e):(r=Math.acos(g),s=Math.sqrt(1-g*g),Math.abs(s)<.001?(e[0]=.5*h+.5*d,e[1]=.5*c+.5*f,e[2]=.5*u+.5*m,e[3]=.5*l+.5*p,e):(a=Math.sin((1-n)*r)/s,o=Math.sin(n*r)/s,e[0]=h*a+d*o,e[1]=c*a+f*o,e[2]=u*a+m*o,e[3]=l*a+p*o,e))},l.invert=function(e,t){var i=t[0],n=t[1],r=t[2],s=t[3],a=i*i+n*n+r*r+s*s,o=a?1/a:0;return e[0]=-i*o,e[1]=-n*o,e[2]=-r*o,e[3]=s*o,e},l.conjugate=function(e,t){return e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e[3]=t[3],e},l.len=l.length=r.length,l.sqrLen=l.squaredLength=r.squaredLength,l.normalize=r.normalize,l.str=function(e){return"quat("+e[0]+", "+e[1]+", "+e[2]+", "+e[3]+")"},"undefined"!=typeof e&&(e.quat=l)}(e.exports)}();var EPSILON=1e-6;mat3.normalize=function(e,t){var i;return i=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),e[0]=t[0]/i,e[1]=t[1]/i,e[2]=t[2]/i,i=Math.sqrt(t[3]*t[3]+t[4]*t[4]+t[5]*t[5]),e[3]=t[3]/i,e[4]=t[4]/i,e[5]=t[5]/i,i=Math.sqrt(t[6]*t[6]+t[7]*t[7]+t[8]*t[8]),e[6]=t[6]/i,e[7]=t[7]/i,e[8]=t[8]/i,e},mat4.submat3=function(e,t,i){return e[0]=t[0+i[0]+4*i[1]],e[1]=t[1+i[0]+4*i[1]],e[2]=t[2+i[0]+4*i[1]],e[3]=t[4+i[0]+4*i[1]],e[4]=t[5+i[0]+4*i[1]],e[5]=t[6+i[0]+4*i[1]],e[6]=t[8+i[0]+4*i[1]],e[7]=t[9+i[0]+4*i[1]],e[8]=t[10+i[0]+4*i[1]],e},mat4.setsubmat3=function(e,t,i){return e[0+i[0]+4*i[1]]=t[0],e[1+i[0]+4*i[1]]=t[1],e[2+i[0]+4*i[1]]=t[2],e[4+i[0]+4*i[1]]=t[3],e[5+i[0]+4*i[1]]=t[4],e[6+i[0]+4*i[1]]=t[5],e[8+i[0]+4*i[1]]=t[6],e[9+i[0]+4*i[1]]=t[7],e[10+i[0]+4*i[1]]=t[8],e},mat4.rotation=function(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=0,e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=0,e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e},mat4.translation=function(e,t){return e[0]=t[12],e[1]=t[13],e[2]=t[14],e},mat4.getScale=function(e,t){return e[0]=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]),e[1]=Math.sqrt(t[4]*t[4]+t[5]*t[5]+t[6]*t[6]+t[7]*t[7]),e[2]=Math.sqrt(t[8]*t[8]+t[9]*t[9]+t[10]*t[10]+t[11]*t[11]),e},mat4.normalize=function(e,t){var i;return i=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]),e[0]=t[0]/i,e[1]=t[1]/i,e[2]=t[2]/i,e[3]=t[3]/i,i=Math.sqrt(t[4]*t[4]+t[5]*t[5]+t[6]*t[6]+t[7]*t[7]),e[4]=t[4]/i,e[5]=t[5]/i,e[6]=t[6]/i,e[7]=t[7]/i,i=Math.sqrt(t[8]*t[8]+t[9]*t[9]+t[10]*t[10]+t[11]*t[11]),e[8]=t[8]/i,e[9]=t[9]/i,e[10]=t[10]/i,e[11]=t[11]/i,i=Math.sqrt(t[12]*t[12]+t[13]*t[13]+t[14]*t[14]+t[15]*t[15]),e[12]=t[12]/i,e[13]=t[13]/i,e[14]=t[14]/i,e[15]=t[15]/i,e},mat4.fromRotationTranslationScale=function(e,t,i,n){return mat4.fromRotationTranslation(e,t,i),mat4.scale(e,e,n),e},mat4.fromTranslation=function(e,t){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=t[0],e[13]=t[1],e[14]=t[2],e[15]=1,e},mat4.decompose=function(e,t,i,n){mat4.translation(e,n),quat.fromMat4(t,n),mat4.getScale(i,n)},mat4.isIdentity=function(e){return Math.abs(e[0]-1)>EPSILON?!1:Math.abs(e[5]-1)>EPSILON?!1:Math.abs(e[10]-1)>EPSILON?!1:Math.abs(e[15]-1)>EPSILON?!1:Math.abs(e[1])>EPSILON?!1:Math.abs(e[2])>EPSILON?!1:Math.abs(e[3])>EPSILON?!1:Math.abs(e[4])>EPSILON?!1:Math.abs(e[6])>EPSILON?!1:Math.abs(e[7])>EPSILON?!1:Math.abs(e[8])>EPSILON?!1:Math.abs(e[9])>EPSILON?!1:Math.abs(e[11])>EPSILON?!1:Math.abs(e[12])>EPSILON?!1:Math.abs(e[13])>EPSILON?!1:Math.abs(e[14])>EPSILON?!1:!0},quat.euler=function(e,t,i,n){var r=2*Math.PI/360,s=quat.create(),a=vec3.fromValues(0,0,1);return quat.setAxisAngle(e,a,r*n),vec3.set(a,0,1,0),quat.setAxisAngle(s,a,r*i),quat.mul(e,e,s),vec3.set(a,1,0,0),quat.setAxisAngle(s,a,r*t),quat.mul(e,e,s),e},quat.getEuler=function(e,t){var i=360/(2*Math.PI),n=mat4.fromRotationTranslation(mat4.create(),t,[0,0,0]),r=function(e,t){return Math.abs(e-t)<=EPSILON},s=function(e,t){var i=quat.euler(quat.create(),t[0],t[1],t[2]);quat.normalize(i,i);var n=quat.rotationDifference(quat.create(),e,i);return Math.abs(1-n[3])<EPSILON};if(r(Math.abs(n[2]),1))r(n[2],-1)?(e[0]=0,e[1]=90,e[2]=-i*Math.atan2(n[4],n[8])):(e[0]=0,e[1]=-90,e[2]=i*Math.atan2(-n[4],-n[8]));else{var a=function(t){var r=Math.cos(t);e[0]=Math.atan2(n[6]/r,n[10]/r)*i,e[1]=t*i,e[2]=Math.atan2(n[1]/r,n[0]/r)*i},o=-Math.asin(n[2]);a(o),s(t,e)||(o=Math.PI-o,a(o))}return e},quat.fromMat3=function(e,t){var i=t[0]+t[4]+t[8];if(i>EPSILON){var n=2*Math.sqrt(1+i);e[3]=.25*n,e[0]=(t[5]-t[7])/n,e[1]=(t[6]-t[2])/n,e[2]=(t[1]-t[3])/n}else if(t[0]>t[4]&&t[0]>t[8]){var n=2*Math.sqrt(1+t[0]-t[4]-t[8]);e[3]=(t[5]-t[7])/n,e[0]=.25*n,e[1]=(t[1]+t[3])/n,e[2]=(t[6]+t[2])/n}else if(t[4]>t[8]){var n=2*Math.sqrt(1+t[4]-t[0]-t[8]);e[3]=(t[6]-t[2])/n,e[0]=(t[1]+t[3])/n,e[1]=.25*n,e[2]=(t[5]+t[7])/n}else{var n=2*Math.sqrt(1+t[8]-t[0]-t[4]);e[3]=(t[1]-t[3])/n,e[0]=(t[6]+t[2])/n,e[1]=(t[5]+t[7])/n,e[2]=.25*n}return e},quat.fromMat4=function(e,t){var i=mat4.submat3(mat3.create(),t,[0,0]);return mat3.normalize(i,i),quat.fromMat3(e,i),quat.normalize(e,e),e},quat.rotationDifference=function(e,t,i){return quat.multiply(e,i,quat.conjugate(quat.create(),t)),e},quat.angle=function(e,t){var i=e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3];return Math.abs(1-i)<EPSILON&&(i=1),Math.abs(1+i)<EPSILON&&(i=-1),2*Math.acos(i)},quat.slerp=function(e,t,i,n){var r=t[0]*i[0]+t[1]*i[1]+t[2]*i[2]+t[3]*i[3];Math.abs(1-r)<EPSILON&&(r=1),Math.abs(1+r)<EPSILON&&(r=-1);var s,a;if(1-Math.abs(r)>EPSILON){var o=Math.acos(Math.abs(r)),h=Math.sin(o);s=Math.sin((1-n)*o/h),a=Math.sin(n*o/h)}else s=1-n,a=n;0>r&&(a=-a);var c=quat.scale(quat.create(),t,s),u=quat.scale(quat.create(),i,a);return quat.add(e,c,u),e},quat.getTwist=function(e,t){var i=vec3.create(),n=vec3.transformQuat(vec3.create(),t,quat.euler(quat.create(),90,0,0)),r=vec3.dot(t,n);Math.abs(r)>.6&&(n=vec3.transformQuat(t,quat.euler(quat.create(),0,90,0))),vec3.normalize(n,n),vec3.cross(i,t,n),vec3.normalize(i,i);var s=vec3.transformQuat(vec3.create(),i,e),a=vec3.sub(vec3.create(),s,vec3.scale(vec3.create(),t,vec3.dot(s,t)));return vec3.normalize(a,a),Math.acos(vec3.dot(i,a))},vec3.transformVertexArrayMat4=function(e,t,i){for(var n=0,r=0,s=0,a=i;a<e.length;a+=3)n=e[a],r=e[a+1],s=e[a+2],e[a]=t[0]*n+t[4]*r+t[8]*s+t[12],e[a+1]=t[1]*n+t[5]*r+t[9]*s+t[13],e[a+2]=t[2]*n+t[6]*r+t[10]*s+t[14];return e},vec3.transformVertexArrayQuat=function(e,t,i){for(var n=0,r=0,s=0,a=t[0],o=t[1],h=t[2],c=t[3],u=0,l=0,d=0,f=0,m=i;m<e.length;m+=3)n=e[m],r=e[m+1],s=e[m+2],u=c*n+o*s-h*r,l=c*r+h*n-a*s,d=c*s+a*r-o*n,f=-a*n-o*r-h*s,e[m]=u*c+f*-a+l*-h-d*-o,e[m+1]=l*c+f*-o+d*-a-u*-h,e[m+2]=d*c+f*-h+u*-o-l*-a;return e},vec3.scaleAndAdd=function(e,t,i,n){return e[0]=t[0]+i[0]*n,e[1]=t[1]+i[1]*n,e[2]=t[2]+i[2]*n,e},function(e){var t={ArrayBuffer:"undefined"!=typeof ArrayBuffer,DataView:"undefined"!=typeof DataView&&("getFloat64"in DataView.prototype||"getFloat64"in new DataView(new ArrayBuffer(1))),NodeBuffer:"undefined"!=typeof Buffer&&"readInt16LE"in Buffer.prototype},i={Int8:1,Int16:2,Int32:4,Uint8:1,Uint16:2,Uint32:4,Float32:4,Float64:8},n={Int8:"Int8",Int16:"Int16",Int32:"Int32",Uint8:"UInt8",Uint16:"UInt16",Uint32:"UInt32",Float32:"Float",Float64:"Double"},r=function(s,a,o,h){if(!(this instanceof r))throw new Error("jDataView constructor may not be called as a function");if(this.buffer=s,!(t.NodeBuffer&&s instanceof Buffer||t.ArrayBuffer&&s instanceof ArrayBuffer||"string"==typeof s))throw new TypeError("jDataView buffer has an incompatible type");this._isArrayBuffer=t.ArrayBuffer&&s instanceof ArrayBuffer,this._isDataView=t.DataView&&this._isArrayBuffer,this._isNodeBuffer=t.NodeBuffer&&s instanceof Buffer,this._littleEndian=void 0===h?!1:h;var c=this._isArrayBuffer?s.byteLength:s.length;if(void 0===a&&(a=0),this.byteOffset=a,void 0===o&&(o=c-a),this.byteLength=o,!this._isDataView){if("number"!=typeof a)throw new TypeError("jDataView byteOffset is not a number");if("number"!=typeof o)throw new TypeError("jDataView byteLength is not a number");if(0>a)throw new Error("jDataView byteOffset is negative");if(0>o)throw new Error("jDataView byteLength is negative")}if(this._isDataView&&(this._view=new DataView(s,a,o),this._start=0),this._start=a,a+o>c)throw new Error("jDataView (byteOffset + byteLength) value is out of bounds");if(this._offset=0,this._isDataView)for(var u in i)i.hasOwnProperty(u)&&!function(e,t){var n=i[e];t["get"+e]=function(i,r){return void 0===r&&(r=t._littleEndian),void 0===i&&(i=t._offset),t._offset=i+n,t._view["get"+e](i,r)}}(u,this);else if(this._isNodeBuffer&&t.NodeBuffer){for(var u in i)if(i.hasOwnProperty(u)){var l;l="Int8"===u||"Uint8"===u?"read"+n[u]:h?"read"+n[u]+"LE":"read"+n[u]+"BE",function(e,t,n){var r=i[e];t["get"+e]=function(e,i){return void 0===i&&(i=t._littleEndian),void 0===e&&(e=t._offset),t._offset=e+r,t.buffer[n](t._start+e)}}(u,this,l)}}else for(var u in i)i.hasOwnProperty(u)&&!function(t,n){var r=i[t];n["get"+t]=function(i,s){if(void 0===s&&(s=n._littleEndian),void 0===i&&(i=n._offset),n._offset=i+r,n._isArrayBuffer&&(n._start+i)%r===0&&(1===r||s))return new e[t+"Array"](n.buffer,n._start+i,1)[0];if("number"!=typeof i)throw new TypeError("jDataView byteOffset is not a number");if(i+r>n.byteLength)throw new Error("jDataView (byteOffset + size) value is out of bounds");return n["_get"+t](n._start+i,s)}}(u,this)};if(r.createBuffer=t.NodeBuffer?function(){for(var e=new Buffer(arguments.length),t=0;t<arguments.length;++t)e[t]=arguments[t];return e}:t.ArrayBuffer?function(){for(var e=new ArrayBuffer(arguments.length),t=new Int8Array(e),i=0;i<arguments.length;++i)t[i]=arguments[i];return e}:function(){return String.fromCharCode.apply(null,arguments)},r.prototype={compatibility:t,getString:function(e,t){var i;if(void 0===t&&(t=this._offset),"number"!=typeof t)throw new TypeError("jDataView byteOffset is not a number");if(0>e||t+e>this.byteLength)throw new Error("jDataView length or (byteOffset+length) value is out of bounds");if(this._isNodeBuffer)i=this.buffer.toString("ascii",this._start+t,this._start+t+e);else{i="";for(var n=0;e>n;++n){var r=this.getUint8(t+n);i+=String.fromCharCode(r>127?65533:r)}}return this._offset=t+e,i},getChar:function(e){return this.getString(1,e)},tell:function(){return this._offset},seek:function(e){if("number"!=typeof e)throw new TypeError("jDataView byteOffset is not a number");if(0>e||e>this.byteLength)throw new Error("jDataView byteOffset value is out of bounds");return this._offset=e},_endianness:function(e,t,i,n){return e+(n?i-t-1:t)},_getFloat64:function(e,t){var i=this._getUint8(this._endianness(e,0,8,t)),n=this._getUint8(this._endianness(e,1,8,t)),r=this._getUint8(this._endianness(e,2,8,t)),s=this._getUint8(this._endianness(e,3,8,t)),a=this._getUint8(this._endianness(e,4,8,t)),o=this._getUint8(this._endianness(e,5,8,t)),h=this._getUint8(this._endianness(e,6,8,t)),c=this._getUint8(this._endianness(e,7,8,t)),u=1-2*(i>>7),l=((i<<1&255)<<3|n>>4)-(Math.pow(2,10)-1),d=(15&n)*Math.pow(2,48)+r*Math.pow(2,40)+s*Math.pow(2,32)+a*Math.pow(2,24)+o*Math.pow(2,16)+h*Math.pow(2,8)+c;return 1024===l?0!==d?0/0:1/0*u:-1023===l?u*d*Math.pow(2,-1074):u*(1+d*Math.pow(2,-52))*Math.pow(2,l)},_getFloat32:function(e,t){var i=this._getUint8(this._endianness(e,0,4,t)),n=this._getUint8(this._endianness(e,1,4,t)),r=this._getUint8(this._endianness(e,2,4,t)),s=this._getUint8(this._endianness(e,3,4,t)),a=1-2*(i>>7),o=(i<<1&255|n>>7)-127,h=(127&n)<<16|r<<8|s;
  return 128===o?0!==h?0/0:1/0*a:-127===o?a*h*Math.pow(2,-149):a*(1+h*Math.pow(2,-23))*Math.pow(2,o)},_getInt32:function(e,t){var i=this._getUint32(e,t);return i>Math.pow(2,31)-1?i-Math.pow(2,32):i},_getUint32:function(e,t){var i=this._getUint8(this._endianness(e,0,4,t)),n=this._getUint8(this._endianness(e,1,4,t)),r=this._getUint8(this._endianness(e,2,4,t)),s=this._getUint8(this._endianness(e,3,4,t));return i*Math.pow(2,24)+(n<<16)+(r<<8)+s},_getInt16:function(e,t){var i=this._getUint16(e,t);return i>Math.pow(2,15)-1?i-Math.pow(2,16):i},_getUint16:function(e,t){var i=this._getUint8(this._endianness(e,0,2,t)),n=this._getUint8(this._endianness(e,1,2,t));return(i<<8)+n},_getInt8:function(e){var t=this._getUint8(e);return t>Math.pow(2,7)-1?t-Math.pow(2,8):t},_getUint8:function(e){return this._isArrayBuffer?new Uint8Array(this.buffer,e,1)[0]:this._isNodeBuffer?this.buffer[e]:255&this.buffer.charCodeAt(e)}},"undefined"!=typeof jQuery&&jQuery.fn.jquery>="1.6.2"){var s=function(e){var t;try{t=IEBinaryToArray_ByteStr(e)}catch(i){var n="Function IEBinaryToArray_ByteStr(Binary)\r\n	IEBinaryToArray_ByteStr = CStr(Binary)\r\nEnd Function\r\nFunction IEBinaryToArray_ByteStr_Last(Binary)\r\n	Dim lastIndex\r\n	lastIndex = LenB(Binary)\r\n	if lastIndex mod 2 Then\r\n		IEBinaryToArray_ByteStr_Last = AscB( MidB( Binary, lastIndex, 1 ) )\r\n	Else\r\n		IEBinaryToArray_ByteStr_Last = -1\r\n	End If\r\nEnd Function\r\n";window.execScript(n,"vbscript"),t=IEBinaryToArray_ByteStr(e)}for(var r,s=IEBinaryToArray_ByteStr_Last(e),a="",o=0,h=t.length%8;h>o;)r=t.charCodeAt(o++),a+=String.fromCharCode(255&r,r>>8);for(h=t.length;h>o;)a+=String.fromCharCode((r=t.charCodeAt(o++),255&r),r>>8,(r=t.charCodeAt(o++),255&r),r>>8,(r=t.charCodeAt(o++),255&r),r>>8,(r=t.charCodeAt(o++),255&r),r>>8,(r=t.charCodeAt(o++),255&r),r>>8,(r=t.charCodeAt(o++),255&r),r>>8,(r=t.charCodeAt(o++),255&r),r>>8,(r=t.charCodeAt(o++),255&r),r>>8);return s>-1&&(a+=String.fromCharCode(s)),a};jQuery.ajaxSetup({converters:{"* dataview":function(e){return new r(e)}},accepts:{dataview:"text/plain; charset=x-user-defined"},responseHandler:{dataview:function(e,t,i){e.text="mozResponseArrayBuffer"in i?i.mozResponseArrayBuffer:"responseType"in i&&"arraybuffer"===i.responseType&&i.response?i.response:"responseBody"in i?s(i.responseBody):i.responseText}}}),jQuery.ajaxPrefilter("dataview",function(e){jQuery.support.ajaxResponseType&&(e.hasOwnProperty("xhrFields")||(e.xhrFields={}),e.xhrFields.responseType="arraybuffer"),e.mimeType="text/plain; charset=x-user-defined"})}e.jDataView=(e.module||{}).exports=r,"undefined"!=typeof module&&(module.exports=r)}(this),function(){var e=!1,t=/\b_super\b/;this.Class=function(){},Class.extend=function(i){function n(){!e&&this.init&&this.init.apply(this,arguments)}var r=this.prototype;e=!0;var s=new this;e=!1;for(var a in i)s[a]="function"==typeof i[a]&&"function"==typeof r[a]&&t.test(i[a])?function(e,t){return function(){var i=this._super;this._super=r[e];var n=t.apply(this,arguments);return this._super=i,n}}(a,i[a]):i[a];return s._getset=function(e,t){var n,r=function(){return e},a=function(t){e=t};n="get"+t,s[n]=n in i?function(e){return function(){var t=this._super;this._super=r;var i=e.apply(this,arguments);return this._super=t,i}}(i[n]):r,n="set"+t,s[n]=n in i?function(e){return function(){var t=this._super;this._super=a;var i=e.apply(this,arguments);return this._super=t,i}}(i[n]):a},n.prototype=s,n.prototype.constructor=n,n.extend=arguments.callee,n}}(),window.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(e){window.setTimeout(e,16)}}(),function(){window.cancelAnimationFrame||(window.cancelAnimationFrame=function(e){clearTimeout(e)})}(),"function"!=typeof String.prototype.format&&(String.prototype.format=function(){var e=arguments;return this.replace(/{(\d+)}/g,function(t,i){return"undefined"!=typeof e[i]?e[i]:t})});var Logistics=function(){var e=!1;"undefined"!=typeof window&&(e="localStorage"in window&&null!==window.localStorage);var t=[],i=[],n=0,r=!1,s=null,a=null,o=null,h={loadFromLocalStorage:!1,storeToLocalStorage:!1,loadFromFile:!1,enableCORS:!0,useCookies:!1,fallbackFromStorage:!1},c={text:{load:function(e){E(e)},parse:function(e,t){e.data=t.responseText},store:function(e){return e.data},restore:function(e,t){return t}},json:{load:function(e){E(e)},parse:function(e,t){try{e.data=JSON.parse(t.responseText)}catch(i){"undefined"!=typeof console&&console.error&&console.error("JSON parsing failed for "+e.url,i)}},store:function(e){return JSON.stringify(e.data)},restore:function(e,t){return t?JSON.parse(t):{}}},xml:{load:function(e){E(e)},parse:function(e,t){e.data=t.responseXML?t.responseXML:w(t.responseText)},store:function(e){return XMLSerializer?(new XMLSerializer).serializeToString(e.data):""},restore:function(e,t){return w(t)}},image:{load:function(e){e&&(e.data=new Image,e.useCORS&&(e.data.crossOrigin="Anonymous"),e.data.onload=function(){e.ready()},e.data.onerror=function(){e.failed()},e.data.src=e.url)},parse:function(){},store:function(e){var t=document.createElement("canvas");t.width=e.data.width,t.height=e.data.height;var i=t.getContext("2d");i.drawImage(e.data,0,0);var n=t.toDataURL("image/png");return t=null,n},restore:function(e,t){var i=new Image;return i.src=t,i}},binary:{load:function(e){E(e)},parse:function(e,t){e.data=t.response},store:function(e){for(var t="",i=new Uint8Array(e.data),n=i.byteLength,r=0;n>r;r++)t+=String.fromCharCode(i[r]);return window.btoa(t)},restore:function(e,t){for(var i=new ArrayBuffer(2*t.length),n=new Uint16Array(i),r=0,s=t.length;s>r;r++)n[r]=t.charCodeAt(r);return i}}},u=function(e,t,i,r,s){this.url=e,this.params=t,this.success=i,this.dataType=r,this.loaded=!1,this.data=!1,this.requestType=s,this.useCORS=!1,this.options={},this.successCallback=i,this.errorCallback=!1,this.alwaysCallback=!1,this.progressCallback=!1,this.setOption=function(e,t){this.options[e]=t},this.getOption=function(e){return this.options[e]},this.ready=function(){this.loaded=!0,n++,C(this),F()},this.failed=function(){n++,F(),P(this)},this.done=function(e){this.successCallback=e},this.fail=function(e){this.errorCallback=e},this.error=function(e){this.errorCallback=e},this.always=function(e){this.alwaysCallback=e},this.progress=function(e){this.progressCallback=e},this.toString=function(){return this.data}},l=function(e,t){this.urls=e,this.results={},this.loadedCount=0,this.count=0,this.successCallback=t,this.load=function(){var e=null,t=null;for(var i in this.urls)this.urls.hasOwnProperty(i)&&this.count++;for(var n in this.urls)t=this.urls[n],t&&t.url&&t.type&&(e=d(t.url,void 0,I(this,this.ready,n),t.type),e.setOption("logistics.multi.key",n),e.fail(I(this,this.fail)))},this.ready=function(e,t,i){var n=i.getOption("logistics.multi.key");this.results[n]=e,this.loadedCount++,this.checkIfAllReady()},this.fail=function(){this.loadedCount++,this.checkIfAllReady()},this.getKeyForURL=function(){},this.checkIfAllReady=function(){this.loadedCount>=this.count&&"function"==typeof this.successCallback&&this.successCallback(this.results)}},d=function(e,i,n,r){var s="GET";"function"==typeof i?(n=i,i=void 0):i&&"object"==typeof i&&(s="POST");var a=new u(e,i,n,r,s);return h.enableCORS&&(a.useCORS=m(e)),a&&(t.push(a),p(a)),a},f=function(e,t){var n=new l(e,t);i.push(n),n.load()},m=function(e){if("undefined"==typeof document)return!1;var t=e.match(/(https?:)?\/\/([^\/]+)\/(.*)/);return t?t[1]===document.location.origin?!1:!0:!1},p=function(e){return g(e),!0},g=function(e){h.loadFromLocalStorage&&v(e)?b(e):T(e.dataType,"load")(e)},v=function(t){return e&&null!==localStorage.getItem(t.url)?!0:!1},b=function(e){e.data=T(e.dataType,"restore")(e,D(e)),e.ready()},T=function(e,t){return c&&c[e]&&c[e][t]?c[e][t]:c&&c[e]?c[e]:function(){"undefined"!=typeof console&&console.warn&&console.warn("Method "+t+" for "+e+" not found")}},x=function(e,t){e&&t&&(c[e]=t)},E=function(e){var t=S(e);if(!t||!e)throw"http failed";var i=e.url;t.open(e.requestType,i,!0),t.overrideMimeType&&t.overrideMimeType("text/xml"),"binary"==e.dataType&&(t.responseType="arraybuffer",e.useCORS&&t.setRequestHeader("Content-Type","application/x-3dtechdata")),e.useCORS&&h.useCookies&&(t.withCredentials=!0),t.onreadystatechange=function(){4==t.readyState?200==t.status?(e.loaded=!0,n++,T(e.dataType,"parse")(e,t),C(e)):(n++,P(e)):"function"==typeof e.progressCallback&&e.progressCallback(t)},t.ontimeout=function(){n++,P(e)},F(),t.send(null)},w=function(e){var t=null;if(!e||"string"!=typeof e)return t;if(window.DOMParser){var i=new DOMParser;t=i.parseFromString(e,"text/xml")}else t=new ActiveXObject("Microsoft.XMLDOM"),t.async=!1,t.loadXML(e);if(!t||t.getElementsByTagName("parsererror").length)throw"XML parsing failed";return t},S=function(e){var t=!1;if(e.useCORS&&window.XDomainRequest)try{t=new XDomainRequest}catch(i){t=!1}else if(XMLHttpRequest)try{t=new XMLHttpRequest}catch(n){t=!1}else if("undefined"!=typeof ActiveXObject)try{t=new ActiveXObject("Msxml2.XMLHTTP"),alert(2)}catch(n){try{t=new ActiveXObject("Microsoft.XMLHTTP"),alert(3)}catch(i){t=!1}}return t},y=function(){t=[],i=[],n=0,r=!1},M=function(){if(e)for(var i in t)_(t[i]);else console.warn("localStorage isn't supported")},R=function(){localStorage.clear()},_=function(t){if(e)try{localStorage[t.url]=T(t.dataType,"store")(t)}catch(i){console.warn("localStorage limit exceeded")}else console.warn("localStorage isn't supported")},D=function(e){return localStorage[e.url]},C=function(e){e&&"function"==typeof e.successCallback&&(e.successCallback(e.data,"success",e),N()),e&&h.storeToLocalStorage&&_(e)},P=function(e){return e&&h.fallbackFromStorage&&v(e)?void b(e):(e&&"function"==typeof e.errorCallback&&e.errorCallback(e,"error",""),void N())},F=function(){a&&"function"==typeof a&&t.length&&n&&a(n/t.length)},N=function(){null===o&&(o=setTimeout(A,5))},A=function(){o=null,t.length==n&&s&&"function"==typeof s&&s()},I=function(e,t){return function(){return t.apply(e,arguments)}},U=function(e,t){h[e]=t},B=function(e){return h[e]};return{count:function(){return t.length},loadedCount:function(){return n},clear:function(){y()},get:function(e,t,i,n){return d(e,t,i,toLowerCase(n))},getJSON:function(e,t,i,n){return d(e,t,i,"json",n)},getImage:function(e,t,i,n){return d(e,t,i,"image",n)},getBinary:function(e,t,i,n){return d(e,t,i,"binary",n)},getXML:function(e,t,i,n){return d(e,t,i,"xml",n)},getText:function(e,t,i,n){return d(e,t,i,"text",n)},getMultiple:function(e,t,i){f(e,t,i)},store:function(){M()},clearStorage:function(){R()},types:function(){return c},onFinishedLoading:function(e){s=e},onProgress:function(e){a=e},getQueue:function(){return t},getTypeFunction:function(e,t){return T(e,t)},setTypeFunction:function(e,t){return x(e,t)},getOption:function(e){return B(e)},setOption:function(e,t){U(e,t)}}}();!function(e,t,i,n){"use strict";function r(e,t,i){return setTimeout(u(e,i),t)}function s(e,t,i){return Array.isArray(e)?(a(e,i[t],i),!0):!1}function a(e,t,i){var r;if(e)if(e.forEach)e.forEach(t,i);else if(e.length!==n)for(r=0;r<e.length;)t.call(i,e[r],r,e),r++;else for(r in e)e.hasOwnProperty(r)&&t.call(i,e[r],r,e)}function o(e,t,i){for(var r=Object.keys(t),s=0;s<r.length;)(!i||i&&e[r[s]]===n)&&(e[r[s]]=t[r[s]]),s++;return e}function h(e,t){return o(e,t,!0)}function c(e,t,i){var n,r=t.prototype;n=e.prototype=Object.create(r),n.constructor=e,n._super=r,i&&o(n,i)}function u(e,t){return function(){return e.apply(t,arguments)}}function l(e,t){return typeof e==ut?e.apply(t?t[0]||n:n,t):e}function d(e,t){return e===n?t:e}function f(e,t,i){a(v(t),function(t){e.addEventListener(t,i,!1)})}function m(e,t,i){a(v(t),function(t){e.removeEventListener(t,i,!1)})}function p(e,t){for(;e;){if(e==t)return!0;e=e.parentNode}return!1}function g(e,t){return e.indexOf(t)>-1}function v(e){return e.trim().split(/\s+/g)}function b(e,t,i){if(e.indexOf&&!i)return e.indexOf(t);for(var n=0;n<e.length;){if(i&&e[n][i]==t||!i&&e[n]===t)return n;n++}return-1}function T(e){return Array.prototype.slice.call(e,0)}function x(e,t,i){for(var n=[],r=[],s=0;s<e.length;){var a=t?e[s][t]:e[s];b(r,a)<0&&n.push(e[s]),r[s]=a,s++}return i&&(n=t?n.sort(function(e,i){return e[t]>i[t]}):n.sort()),n}function E(e,t){for(var i,r,s=t[0].toUpperCase()+t.slice(1),a=0;a<ht.length;){if(i=ht[a],r=i?i+s:t,r in e)return r;a++}return n}function w(){return mt++}function S(t){var i=t.ownerDocument||t;return i.defaultView||i.parentWindow||e}function y(e,t){var i=this;this.manager=e,this.callback=t,this.element=e.element,this.target=e.options.inputTarget,this.domHandler=function(t){l(e.options.enable,[e])&&i.handler(t)},this.init()}function M(e){var t,i=e.options.inputClass;return new(t=i?i:vt?z:bt?q:gt?H:L)(e,R)}function R(e,t,i){var n=i.pointers.length,r=i.changedPointers.length,s=t&yt&&n-r===0,a=t&(Rt|_t)&&n-r===0;i.isFirst=!!s,i.isFinal=!!a,s&&(e.session={}),i.eventType=t,_(e,i),e.emit("hammer.input",i),e.recognize(i),e.session.prevInput=i}function _(e,t){var i=e.session,n=t.pointers,r=n.length;i.firstInput||(i.firstInput=P(t)),r>1&&!i.firstMultiple?i.firstMultiple=P(t):1===r&&(i.firstMultiple=!1);var s=i.firstInput,a=i.firstMultiple,o=a?a.center:s.center,h=t.center=F(n);t.timeStamp=ft(),t.deltaTime=t.timeStamp-s.timeStamp,t.angle=U(o,h),t.distance=I(o,h),D(i,t),t.offsetDirection=A(t.deltaX,t.deltaY),t.scale=a?O(a.pointers,n):1,t.rotation=a?B(a.pointers,n):0,C(i,t);var c=e.element;p(t.srcEvent.target,c)&&(c=t.srcEvent.target),t.target=c}function D(e,t){var i=t.center,n=e.offsetDelta||{},r=e.prevDelta||{},s=e.prevInput||{};(t.eventType===yt||s.eventType===Rt)&&(r=e.prevDelta={x:s.deltaX||0,y:s.deltaY||0},n=e.offsetDelta={x:i.x,y:i.y}),t.deltaX=r.x+(i.x-n.x),t.deltaY=r.y+(i.y-n.y)}function C(e,t){var i,r,s,a,o=e.lastInterval||t,h=t.timeStamp-o.timeStamp;if(t.eventType!=_t&&(h>St||o.velocity===n)){var c=o.deltaX-t.deltaX,u=o.deltaY-t.deltaY,l=N(h,c,u);r=l.x,s=l.y,i=dt(l.x)>dt(l.y)?l.x:l.y,a=A(c,u),e.lastInterval=t}else i=o.velocity,r=o.velocityX,s=o.velocityY,a=o.direction;t.velocity=i,t.velocityX=r,t.velocityY=s,t.direction=a}function P(e){for(var t=[],i=0;i<e.pointers.length;)t[i]={clientX:lt(e.pointers[i].clientX),clientY:lt(e.pointers[i].clientY)},i++;return{timeStamp:ft(),pointers:t,center:F(t),deltaX:e.deltaX,deltaY:e.deltaY}}function F(e){var t=e.length;if(1===t)return{x:lt(e[0].clientX),y:lt(e[0].clientY)};for(var i=0,n=0,r=0;t>r;)i+=e[r].clientX,n+=e[r].clientY,r++;return{x:lt(i/t),y:lt(n/t)}}function N(e,t,i){return{x:t/e||0,y:i/e||0}}function A(e,t){return e===t?Dt:dt(e)>=dt(t)?e>0?Ct:Pt:t>0?Ft:Nt}function I(e,t,i){i||(i=Bt);var n=t[i[0]]-e[i[0]],r=t[i[1]]-e[i[1]];return Math.sqrt(n*n+r*r)}function U(e,t,i){i||(i=Bt);var n=t[i[0]]-e[i[0]],r=t[i[1]]-e[i[1]];return 180*Math.atan2(r,n)/Math.PI}function B(e,t){return U(t[1],t[0],Ot)-U(e[1],e[0],Ot)}function O(e,t){return I(t[0],t[1],Ot)/I(e[0],e[1],Ot)}function L(){this.evEl=zt,this.evWin=kt,this.allow=!0,this.pressed=!1,y.apply(this,arguments)}function z(){this.evEl=Xt,this.evWin=Ht,y.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}function k(){this.evTarget=jt,this.evWin=Wt,this.started=!1,y.apply(this,arguments)}function V(e,t){var i=T(e.touches),n=T(e.changedTouches);return t&(Rt|_t)&&(i=x(i.concat(n),"identifier",!0)),[i,n]}function q(){this.evTarget=Qt,this.targetIds={},y.apply(this,arguments)}function X(e,t){var i=T(e.touches),n=this.targetIds;if(t&(yt|Mt)&&1===i.length)return n[i[0].identifier]=!0,[i,i];var r,s,a=T(e.changedTouches),o=[],h=this.target;if(s=i.filter(function(e){return p(e.target,h)}),t===yt)for(r=0;r<s.length;)n[s[r].identifier]=!0,r++;for(r=0;r<a.length;)n[a[r].identifier]&&o.push(a[r]),t&(Rt|_t)&&delete n[a[r].identifier],r++;return o.length?[x(s.concat(o),"identifier",!0),o]:void 0}function H(){y.apply(this,arguments);var e=u(this.handler,this);this.touch=new q(this.manager,e),this.mouse=new L(this.manager,e)}function G(e,t){this.manager=e,this.set(t)}function j(e){if(g(e,ti))return ti;var t=g(e,ii),i=g(e,ni);return t&&i?ii+" "+ni:t||i?t?ii:ni:g(e,ei)?ei:Jt}function W(e){this.id=w(),this.manager=null,this.options=h(e||{},this.defaults),this.options.enable=d(this.options.enable,!0),this.state=ri,this.simultaneous={},this.requireFail=[]}function Y(e){return e&ci?"cancel":e&oi?"end":e&ai?"move":e&si?"start":""}function Q(e){return e==Nt?"down":e==Ft?"up":e==Ct?"left":e==Pt?"right":""}function $(e,t){var i=t.manager;return i?i.get(e):e}function K(){W.apply(this,arguments)}function Z(){K.apply(this,arguments),this.pX=null,this.pY=null}function J(){K.apply(this,arguments)}function et(){W.apply(this,arguments),this._timer=null,this._input=null}function tt(){K.apply(this,arguments)}function it(){K.apply(this,arguments)}function nt(){W.apply(this,arguments),this.pTime=!1,this.pCenter=!1,this._timer=null,this._input=null,this.count=0}function rt(e,t){return t=t||{},t.recognizers=d(t.recognizers,rt.defaults.preset),new st(e,t)}function st(e,t){t=t||{},this.options=h(t,rt.defaults),this.options.inputTarget=this.options.inputTarget||e,this.handlers={},this.session={},this.recognizers=[],this.element=e,this.input=M(this),this.touchAction=new G(this,this.options.touchAction),at(this,!0),a(t.recognizers,function(e){var t=this.add(new e[0](e[1]));e[2]&&t.recognizeWith(e[2]),e[3]&&t.requireFailure(e[3])},this)}function at(e,t){var i=e.element;i.style&&a(e.options.cssProps,function(e,n){i.style[E(i.style,n)]=t?e:""})}function ot(e,i){var n=t.createEvent("Event");n.initEvent(e,!0,!0),n.gesture=i,i.target.dispatchEvent(n)}var ht=["","webkit","moz","MS","ms","o"],ct=t.createElement("div"),ut="function",lt=Math.round,dt=Math.abs,ft=Date.now,mt=1,pt=/mobile|tablet|ip(ad|hone|od)|android/i,gt="ontouchstart"in e,vt=E(e,"PointerEvent")!==n,bt=gt&&pt.test(navigator.userAgent),Tt="touch",xt="pen",Et="mouse",wt="kinect",St=25,yt=1,Mt=2,Rt=4,_t=8,Dt=1,Ct=2,Pt=4,Ft=8,Nt=16,At=Ct|Pt,It=Ft|Nt,Ut=At|It,Bt=["x","y"],Ot=["clientX","clientY"];y.prototype={handler:function(){},init:function(){this.evEl&&f(this.element,this.evEl,this.domHandler),this.evTarget&&f(this.target,this.evTarget,this.domHandler),this.evWin&&f(S(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&m(this.element,this.evEl,this.domHandler),this.evTarget&&m(this.target,this.evTarget,this.domHandler),this.evWin&&m(S(this.element),this.evWin,this.domHandler)}};var Lt={mousedown:yt,mousemove:Mt,mouseup:Rt},zt="mousedown",kt="mousemove mouseup";c(L,y,{handler:function(e){var t=Lt[e.type];t&yt&&0===e.button&&(this.pressed=!0),t&Mt&&1!==e.which&&(t=Rt),this.pressed&&this.allow&&(t&Rt&&(this.pressed=!1),this.callback(this.manager,t,{pointers:[e],changedPointers:[e],pointerType:Et,srcEvent:e}))}});var Vt={pointerdown:yt,pointermove:Mt,pointerup:Rt,pointercancel:_t,pointerout:_t},qt={2:Tt,3:xt,4:Et,5:wt},Xt="pointerdown",Ht="pointermove pointerup pointercancel";e.MSPointerEvent&&(Xt="MSPointerDown",Ht="MSPointerMove MSPointerUp MSPointerCancel"),c(z,y,{handler:function(e){var t=this.store,i=!1,n=e.type.toLowerCase().replace("ms",""),r=Vt[n],s=qt[e.pointerType]||e.pointerType,a=s==Tt,o=b(t,e.pointerId,"pointerId");r&yt&&(0===e.button||a)?0>o&&(t.push(e),o=t.length-1):r&(Rt|_t)&&(i=!0),0>o||(t[o]=e,this.callback(this.manager,r,{pointers:t,changedPointers:[e],pointerType:s,srcEvent:e}),i&&t.splice(o,1))}});var Gt={touchstart:yt,touchmove:Mt,touchend:Rt,touchcancel:_t},jt="touchstart",Wt="touchstart touchmove touchend touchcancel";c(k,y,{handler:function(e){var t=Gt[e.type];if(t===yt&&(this.started=!0),this.started){var i=V.call(this,e,t);t&(Rt|_t)&&i[0].length-i[1].length===0&&(this.started=!1),this.callback(this.manager,t,{pointers:i[0],changedPointers:i[1],pointerType:Tt,srcEvent:e})}}});var Yt={touchstart:yt,touchmove:Mt,touchend:Rt,touchcancel:_t},Qt="touchstart touchmove touchend touchcancel";c(q,y,{handler:function(e){var t=Yt[e.type],i=X.call(this,e,t);i&&this.callback(this.manager,t,{pointers:i[0],changedPointers:i[1],pointerType:Tt,srcEvent:e})}}),c(H,y,{handler:function(e,t,i){var n=i.pointerType==Tt,r=i.pointerType==Et;if(n)this.mouse.allow=!1;else if(r&&!this.mouse.allow)return;t&(Rt|_t)&&(this.mouse.allow=!0),this.callback(e,t,i)},destroy:function(){this.touch.destroy(),this.mouse.destroy()}});var $t=E(ct.style,"touchAction"),Kt=$t!==n,Zt="compute",Jt="auto",ei="manipulation",ti="none",ii="pan-x",ni="pan-y";G.prototype={set:function(e){e==Zt&&(e=this.compute()),Kt&&this.manager.element.style&&(this.manager.element.style[$t]=e),this.actions=e.toLowerCase().trim()},update:function(){this.set(this.manager.options.touchAction)},compute:function(){var e=[];return a(this.manager.recognizers,function(t){l(t.options.enable,[t])&&(e=e.concat(t.getTouchAction()))}),j(e.join(" "))},preventDefaults:function(e){if(!Kt){var t=e.srcEvent,i=e.offsetDirection;if(this.manager.session.prevented)return void t.preventDefault();var n=this.actions,r=g(n,ti),s=g(n,ni),a=g(n,ii);return r||s&&i&At||a&&i&It?this.preventSrc(t):void 0}},preventSrc:function(e){this.manager.session.prevented=!0,e.preventDefault()}};var ri=1,si=2,ai=4,oi=8,hi=oi,ci=16,ui=32;W.prototype={defaults:{},set:function(e){return o(this.options,e),this.manager&&this.manager.touchAction.update(),this},recognizeWith:function(e){if(s(e,"recognizeWith",this))return this;var t=this.simultaneous;return e=$(e,this),t[e.id]||(t[e.id]=e,e.recognizeWith(this)),this},dropRecognizeWith:function(e){return s(e,"dropRecognizeWith",this)?this:(e=$(e,this),delete this.simultaneous[e.id],this)},requireFailure:function(e){if(s(e,"requireFailure",this))return this;var t=this.requireFail;return e=$(e,this),-1===b(t,e)&&(t.push(e),e.requireFailure(this)),this},dropRequireFailure:function(e){if(s(e,"dropRequireFailure",this))return this;e=$(e,this);var t=b(this.requireFail,e);return t>-1&&this.requireFail.splice(t,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(e){return!!this.simultaneous[e.id]},emit:function(e){function t(t){i.manager.emit(i.options.event+(t?Y(n):""),e)}var i=this,n=this.state;oi>n&&t(!0),t(),n>=oi&&t(!0)},tryEmit:function(e){return this.canEmit()?this.emit(e):void(this.state=ui)},canEmit:function(){for(var e=0;e<this.requireFail.length;){if(!(this.requireFail[e].state&(ui|ri)))return!1;e++}return!0},recognize:function(e){var t=o({},e);return l(this.options.enable,[this,t])?(this.state&(hi|ci|ui)&&(this.state=ri),this.state=this.process(t),void(this.state&(si|ai|oi|ci)&&this.tryEmit(t))):(this.reset(),void(this.state=ui))},process:function(){},getTouchAction:function(){},reset:function(){}},c(K,W,{defaults:{pointers:1},attrTest:function(e){var t=this.options.pointers;return 0===t||e.pointers.length===t},process:function(e){var t=this.state,i=e.eventType,n=t&(si|ai),r=this.attrTest(e);return n&&(i&_t||!r)?t|ci:n||r?i&Rt?t|oi:t&si?t|ai:si:ui}}),c(Z,K,{defaults:{event:"pan",threshold:10,pointers:1,direction:Ut},getTouchAction:function(){var e=this.options.direction,t=[];return e&At&&t.push(ni),e&It&&t.push(ii),t},directionTest:function(e){var t=this.options,i=!0,n=e.distance,r=e.direction,s=e.deltaX,a=e.deltaY;return r&t.direction||(t.direction&At?(r=0===s?Dt:0>s?Ct:Pt,i=s!=this.pX,n=Math.abs(e.deltaX)):(r=0===a?Dt:0>a?Ft:Nt,i=a!=this.pY,n=Math.abs(e.deltaY))),e.direction=r,i&&n>t.threshold&&r&t.direction},attrTest:function(e){return K.prototype.attrTest.call(this,e)&&(this.state&si||!(this.state&si)&&this.directionTest(e))},emit:function(e){this.pX=e.deltaX,this.pY=e.deltaY;var t=Q(e.direction);t&&this.manager.emit(this.options.event+t,e),this._super.emit.call(this,e)}}),c(J,K,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[ti]},attrTest:function(e){return this._super.attrTest.call(this,e)&&(Math.abs(e.scale-1)>this.options.threshold||this.state&si)},emit:function(e){if(this._super.emit.call(this,e),1!==e.scale){var t=e.scale<1?"in":"out";this.manager.emit(this.options.event+t,e)}}}),c(et,W,{defaults:{event:"press",pointers:1,time:500,threshold:5},getTouchAction:function(){return[Jt]},process:function(e){var t=this.options,i=e.pointers.length===t.pointers,n=e.distance<t.threshold,s=e.deltaTime>t.time;if(this._input=e,!n||!i||e.eventType&(Rt|_t)&&!s)this.reset();else if(e.eventType&yt)this.reset(),this._timer=r(function(){this.state=hi,this.tryEmit()},t.time,this);else if(e.eventType&Rt)return hi;return ui},reset:function(){clearTimeout(this._timer)},emit:function(e){this.state===hi&&(e&&e.eventType&Rt?this.manager.emit(this.options.event+"up",e):(this._input.timeStamp=ft(),this.manager.emit(this.options.event,this._input)))}}),c(tt,K,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[ti]},attrTest:function(e){return this._super.attrTest.call(this,e)&&(Math.abs(e.rotation)>this.options.threshold||this.state&si)}}),c(it,K,{defaults:{event:"swipe",threshold:10,velocity:.65,direction:At|It,pointers:1},getTouchAction:function(){return Z.prototype.getTouchAction.call(this)},attrTest:function(e){var t,i=this.options.direction;return i&(At|It)?t=e.velocity:i&At?t=e.velocityX:i&It&&(t=e.velocityY),this._super.attrTest.call(this,e)&&i&e.direction&&e.distance>this.options.threshold&&dt(t)>this.options.velocity&&e.eventType&Rt},emit:function(e){var t=Q(e.direction);t&&this.manager.emit(this.options.event+t,e),this.manager.emit(this.options.event,e)}}),c(nt,W,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:2,posThreshold:10},getTouchAction:function(){return[ei]},process:function(e){var t=this.options,i=e.pointers.length===t.pointers,n=e.distance<t.threshold,s=e.deltaTime<t.time;if(this.reset(),e.eventType&yt&&0===this.count)return this.failTimeout();if(n&&s&&i){if(e.eventType!=Rt)return this.failTimeout();var a=this.pTime?e.timeStamp-this.pTime<t.interval:!0,o=!this.pCenter||I(this.pCenter,e.center)<t.posThreshold;this.pTime=e.timeStamp,this.pCenter=e.center,o&&a?this.count+=1:this.count=1,this._input=e;var h=this.count%t.taps;if(0===h)return this.hasRequireFailures()?(this._timer=r(function(){this.state=hi,this.tryEmit()},t.interval,this),si):hi}return ui},failTimeout:function(){return this._timer=r(function(){this.state=ui},this.options.interval,this),ui},reset:function(){clearTimeout(this._timer)},emit:function(){this.state==hi&&(this._input.tapCount=this.count,this.manager.emit(this.options.event,this._input))}}),rt.VERSION="2.0.4",rt.defaults={domEvents:!1,touchAction:Zt,enable:!0,inputTarget:null,inputClass:null,preset:[[tt,{enable:!1}],[J,{enable:!1},["rotate"]],[it,{direction:At}],[Z,{direction:At},["swipe"]],[nt],[nt,{event:"doubletap",taps:2},["tap"]],[et]],cssProps:{userSelect:"none",touchSelect:"none",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}};var li=1,di=2;st.prototype={set:function(e){return o(this.options,e),e.touchAction&&this.touchAction.update(),e.inputTarget&&(this.input.destroy(),this.input.target=e.inputTarget,this.input.init()),this},stop:function(e){this.session.stopped=e?di:li},recognize:function(e){var t=this.session;if(!t.stopped){this.touchAction.preventDefaults(e);var i,n=this.recognizers,r=t.curRecognizer;(!r||r&&r.state&hi)&&(r=t.curRecognizer=null);for(var s=0;s<n.length;)i=n[s],t.stopped===di||r&&i!=r&&!i.canRecognizeWith(r)?i.reset():i.recognize(e),!r&&i.state&(si|ai|oi)&&(r=t.curRecognizer=i),s++}},get:function(e){if(e instanceof W)return e;for(var t=this.recognizers,i=0;i<t.length;i++)if(t[i].options.event==e)return t[i];return null},add:function(e){if(s(e,"add",this))return this;var t=this.get(e.options.event);return t&&this.remove(t),this.recognizers.push(e),e.manager=this,this.touchAction.update(),e},remove:function(e){if(s(e,"remove",this))return this;var t=this.recognizers;return e=this.get(e),t.splice(b(t,e),1),this.touchAction.update(),this},on:function(e,t){var i=this.handlers;return a(v(e),function(e){i[e]=i[e]||[],i[e].push(t)}),this},off:function(e,t){var i=this.handlers;return a(v(e),function(e){t?i[e].splice(b(i[e],t),1):delete i[e]}),this},emit:function(e,t){this.options.domEvents&&ot(e,t);var i=this.handlers[e]&&this.handlers[e].slice();if(i&&i.length){t.type=e,t.preventDefault=function(){t.srcEvent.preventDefault()};for(var n=0;n<i.length;)i[n](t),n++}},destroy:function(){this.element&&at(this,!1),this.handlers={},this.session={},this.input.destroy(),this.element=null}},o(rt,{INPUT_START:yt,INPUT_MOVE:Mt,INPUT_END:Rt,INPUT_CANCEL:_t,STATE_POSSIBLE:ri,STATE_BEGAN:si,STATE_CHANGED:ai,STATE_ENDED:oi,STATE_RECOGNIZED:hi,STATE_CANCELLED:ci,STATE_FAILED:ui,DIRECTION_NONE:Dt,DIRECTION_LEFT:Ct,DIRECTION_RIGHT:Pt,DIRECTION_UP:Ft,DIRECTION_DOWN:Nt,DIRECTION_HORIZONTAL:At,DIRECTION_VERTICAL:It,DIRECTION_ALL:Ut,Manager:st,Input:y,TouchAction:G,TouchInput:q,MouseInput:L,PointerEventInput:z,TouchMouseInput:H,SingleTouchInput:k,Recognizer:W,AttrRecognizer:K,Tap:nt,Pan:Z,Swipe:it,Pinch:J,Rotate:tt,Press:et,on:f,off:m,each:a,merge:h,extend:o,inherit:c,bindFn:u,prefixed:E}),typeof define==ut&&define.amd?define(function(){return rt}):"undefined"!=typeof module&&module.exports?module.exports=rt:e[i]=rt}(window,document,"HammerWF"),frakVersion="1.1.15";var FRAK=Class.extend({init:function(e,t,i,n,r,s){n||(n="js/"),this.prefix=n,t||(t=[]),i||(i=!1),this.useCache=i,this.stack=[],this.callback=e,this.onEachItem=s,this.onProgress=r,this.total=0,this.loaded=0,$.ajaxSetup({cache:i});for(var a in t)this.include(t[a]);this.load()},include:function(e){this.stack.push(e),this.total++},getVersion:function(){return frakVersion},load:function(){if(0==this.stack.length)return void this.callback();var e=this.prefix+this.stack.shift(),t=this;$.getScript(e,function(i){t.loaded++,$.isFunction(t.onEachItem)&&t.onEachItem(e,i),$.isFunction(t.onProgress)&&t.onProgress(100*t.loaded/t.total),t.load()}).fail(function(t,i,n){console.warn("Failed to load '"+e+"' at "+n.lineNumber+": "+n),console.trace()})}}),Cloneable=Class.extend({type:function(){return!1},clone:function(){return"function"==typeof window[this.type()]?new(window[this.type()]):{}}}),nextSerializableID=1,Serializable=Cloneable.extend({init:function(){this.serializable=!0,this.id=nextSerializableID++},included:function(){return!0},excluded:function(){return[]},getSerializableFields:function(e){var t=this.included();if(excluded=this.excluded(),t===!0&&excluded===!0)throw"Quantum classes not allowed. A subclass of Serializable tries to both include and exclude all fields.";if(t===!1&&excluded===!1)throw"Quantum classes not allowed. A subclass of Serializable tries both not to include and not to exclude all fields.";if(t===!1||excluded===!0)return{};var i={};if(t===!0){for(var n in this){var r={};this[n]&&"[object Function]"==r.toString.call(this[n])||"serializable"==n||"_super"==n||(i[n]=this[n])}if(excluded instanceof Array){excluded=excluded.concat(e);for(var s=0;s<excluded.length;s++)i[excluded[s]]&&delete i[excluded[s]]}}if(excluded===!0){i=[];for(var a=0;a<t.length;a++){var n=t[a],r={};this[n]&&"[object Function]"==r.toString.call(this[n])||"serializable"==n||"_super"==n||(i[n]=this[n])}}return i},serialize:function(e){try{var t=new Serializer;return t.serialize(this,e,32)}catch(i){throw console.warn("Caught serialization exception: ",i),i}},unserialize:function(e){$.parseJSON(e);return!1},serializeCyclic:function(e){try{var t=new CyclicSerializer;return t.serialize(this,e,32)}catch(i){throw console.warn("Caught serialization exception: ",i),i}},unserializeCyclic:function(e){try{var t=new CyclicSerializer;return t.unserialize(e)}catch(i){throw console.warn("Caught serialization exception: ",i),i}},onBeforeSerialize:function(){},onAfterSerialize:function(){},onBeforeUnserialize:function(){},onAfterUnserialize:function(){}}),Serializer=Class.extend({init:function(){this.serializables={}},serializableCopy:function(e,t,i,n,r){var s={},a=t.getSerializableFields(i);if(n>=r){var o=[];for(var h in e)o.push(e[h].type());throw"Reached maximum depth for serialization: "+n+" at "+t.type()}e=e.slice(0),e.splice(0,0,t);for(var c in a){var u=a[c];if(u instanceof Serializable)s[c]=this.serializableCopy(e,u,i,n+1,r);
  else if(u instanceof Array||u instanceof Float32Array){var l=[];for(var d in u)l.push(u[d]instanceof Serializable?this.serializableCopy(e,u[d],i,n+1,r):u[d]);s[c]=l}else s[c]=a[c]}return{_type_:t.type(),_properties_:s}},serialize:function(e,t,i){this.serializables={};var n=this.serializableCopy([],e,t,0,i);return JSON.stringify({_root_:n,_serializables_:this.serializables},void 0,2)},unserializeSerializables:function(e){for(var t in e)this.serializables[t]=this.unserializeCopy(e[t])},unserializeCopy:function(e){if(e instanceof Array){for(var t in e)e[t]=this.unserializeCopy(e[t]);return e}if(e instanceof Object){if(e._reference_)return e;if(e._type_){var i=new window[e._type_];i.onBeforeUnserialize();for(var t in e._properties_)i[t]=this.unserializeCopy(e._properties_[t]);return i.onAfterUnserialize(),i}return e}return i},resolveReferences:function(e,t){if(e[t]instanceof Array)for(var i in e[t])e[t][i]=this.resolveReferences(e[t],i);else if(e[t]instanceof Object)if(e[t]._reference_)e[t]=this.serializables[e[t]._id_];else for(var i in e[t])e[t][i]=this.resolveReferences(e[t],i)},unserialize:function(e){var t=$.parseJSON(e);this.serializables={},this.unserializeSerializables(t._serializables_);var i=this.unserializeCopy(t._root_);for(var n in this.serializables)this.resolveReferences(this.serializables,n);return this.resolveReferences(t,"_serializables_"),i}}),CyclicSerializer=Class.extend({init:function(){this.serializables={},this.visited=[]},serializableCopy:function(e,t,i,n,r){if(n>=r)return{};e=e.slice(0),e.push(t);try{if("object"==typeof t){if(!t)return null;if(t instanceof Serializable){if(!this.serializables[t.id]){this.serializables[t.id]=!0,t.onBeforeSerialize();var s=t.getSerializableFields(t,i);for(var a in s)s[a]=this.serializableCopy(e,s[a],i,n+1,r);t.onAfterSerialize(),this.serializables[t.id]={_type_:t.type(),_properties_:s}}return{_reference_:!0,_id_:t.id}}if(t instanceof Array||t instanceof Float32Array){var o=[];for(var a in t)o.push(this.serializableCopy(e,t[a],i,n+1,r));return o}if(t._visited_)return void console.warn("Already visited object: ",t);t._visited_=!0;var s={};for(var a in t)s[a]=this.serializableCopy(e,t[a],i,n+1,r);return s}return t}catch(h){throw console.warn("Caught: ",t,h),console.warn("Stack: "),console.warn(e),h}},serialize:function(e,t,i){this.serializables={};var n=this.serializableCopy([],e,t,0,i);return JSON.stringify({_root_:n,_serializables_:this.serializables},void 0,2)},unserializeSerializables:function(e){for(var t in e)this.serializables[t]=this.unserializeCopy(e[t])},unserializeCopy:function(e){if(e instanceof Array){for(var t in e)e[t]=this.unserializeCopy(e[t]);return e}if(e instanceof Object){if(e._reference_)return e;if(e._type_){var i=new window[e._type_];i.onBeforeUnserialize();for(var t in e._properties_)i[t]=this.unserializeCopy(e._properties_[t]);return i}return e}return e},resolveReferences:function(e,t,i){if(!(i>32))if(e[t]instanceof Array)for(var n in e[t])this.resolveReferences(e[t],n,i+1);else if(e[t]instanceof Object&&!("_visited_"in e[t]))if(e[t]._reference_)e[t]=this.serializables[e[t]._id_];else if(e[t]instanceof Serializable){e[t]._visited_=!0,this.visited.push(e[t]);for(var r in e[t])this.resolveReferences(e[t],r,i+1)}},unserialize:function(e){var t=$.parseJSON(e);this.serializables={},this.unserializeSerializables(t._serializables_);var i={_root_:this.unserializeCopy(t._root_)};this.resolveReferences(i,"_root_",0);for(var n in this.serializables)this.resolveReferences(this.serializables,n,0);for(var n in this.visited)this.visited[n]instanceof Serializable&&this.visited[n].onAfterUnserialize();for(var n in this.visited)delete this.visited[n]._visited_;return i._root_}}),TypeReference=Serializable.extend({init:function(e,t){this._super(),this.valueType=e,this.value=t},type:function(){return"TypeReference"},isNull:function(){return!this.value}}),Color=function(e,t,i,n){this.r=1,this.g=1,this.b=1,this.a=1,this.clone=function(){return new Color(this.r,this.g,this.b,this.a)},this.fromHex=function(e){var t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(e);return t&&(this.r=parseInt(t[1],16)/255,this.g=parseInt(t[2],16)/255,this.b=parseInt(t[3],16)/255,t[4]&&(this.a=parseInt(t[4],16)/255)),this},this.toHex=function(){var e=function(e){var t=e.toString(16);return 1==t.length?"0"+t:t};return"#"+e(255*this.r)+e(255*this.g)+e(255*this.b)+e(255*this.a)},this.toString=function(){return"rgba("+Math.floor(255*this.r)+", "+Math.floor(255*this.g)+", "+Math.floor(255*this.b)+", "+this.a+")"},this.toVector=function(){return vec4.fromValues(this.r,this.g,this.b,this.a)},this.set=function(e,t,i,n){"number"==typeof e&&(this.r=e),"number"==typeof t&&(this.g=t),"number"==typeof i&&(this.b=i),"number"==typeof n&&(this.a=n)},this.set(e,t,i,n)},MatrixStack=Class.extend({init:function(){this.stack=[mat4.identity(mat4.create())],this.allocated=[];for(var e=0;64>e;e++)this.allocated.push(mat4.create())},top:function(){return this.stack[this.stack.length-1]},push:function(){0==this.allocated.length&&this.allocated.push(mat4.create()),this.stack.push(mat4.copy(this.allocated.pop(),this.stack[this.stack.length-1]))},pop:function(){this.allocated.push(this.stack.pop())},multiply:function(e){mat4.multiply(this.stack[this.stack.length-1],this.stack[this.stack.length-1],e)},load:function(e){mat4.copy(this.stack[this.stack.length-1],e)},size:function(){return this.stack.length}}),RenderingContext=Class.extend({init:function(e,t){function i(e,t,i){throw WebGLDebugUtils.glEnumToString(e)+" was caused by call to: "+t+JSON.stringify(i)}if(!("WebGLRenderingContext"in window))throw"Unable to create rendering context, because browser doesn't support WebGL";if(!e||0===e.length)throw"RenderingContext requires canvas element";if(this.canvas=e,t=t||{alpha:!1},this.gl=e[0].getContext("webgl",t),this.gl||(this.gl=e[0].getContext("experimental-webgl",t)),this.gl||(this.gl=e[0].getContext("moz-webgl",t)),this.gl||(this.gl=e[0].getContext("webkit-3d",t)),!this.gl){var n=(e.offset(),$("<div>").css("position","relative").css("z-index",100).css("background-color","red").css("padding",8).text("WebGL seems to be unavailable in this browser."));throw e.parent().prepend(n),"Failed to acquire GL context from canvas"}"undefined"!=typeof WebGLDebugUtils&&(this.gl=WebGLDebugUtils.makeDebugContext(this.gl,i),console.warn("Using WebGLDebugUtils")),this.gl.enable(this.gl.DEPTH_TEST),this.gl.viewport(0,0,e.width(),e.height()),this.modelview=new MatrixStack,this.projection=new MatrixStack,this.light=!1,this.shadow=!1,this.camera=!1,this.engine=!1}}),Subshader=Class.extend({init:function(e,t,i){this.shader=e,this.context=e.context,this.code=t,this.type=i,this.VERTEX_SHADER=0,this.FRAGMENT_SHADER=1,this.compiledShader=!1,this.failedCompilation=!1},attach:function(){this.context.gl.attachShader(this.shader.program,this.compiledShader)},getFilename:function(){return"Unknown"},compile:function(){if(!this.failedCompilation){if(!this.compiledShader)throw"WebGL shader has not been created. FragmentShader or VertexShader class instances should be used, not Shader.";if(this.context.gl.shaderSource(this.compiledShader,this.code),this.context.gl.compileShader(this.compiledShader),!this.context.gl.getShaderParameter(this.compiledShader,this.context.gl.COMPILE_STATUS)&&!this.failedCompilation)throw this.failedCompilation=!0,"Shader '"+this.getFilename()+"' failed to compile: "+this.context.gl.getShaderInfoLog(this.compiledShader)}}}),VertexShader=Subshader.extend({init:function(e,t){this._super(e,t,this.VERTEX_SHADER),this.compiledShader=this.context.gl.createShader(this.context.gl.VERTEX_SHADER)},getFilename:function(){return this.shader.descriptor.vertexSource}}),FragmentShader=Subshader.extend({init:function(e,t){this._super(e,t,this.FRAGMENT_SHADER),this.compiledShader=this.context.gl.createShader(this.context.gl.FRAGMENT_SHADER)},getFilename:function(){return this.shader.descriptor.fragmentSource}}),ShaderRequirements=Class.extend({init:function(){this.barycentric=!1,this.bitangents=!1,this.tangents=!1,this.transparent=!1,this.texCoords2D=!0},apply:function(e){this.barycentric&&!e.buffers.barycentric&&e.generateBarycentric(),this.texCoords2D&&!e.buffers.texcoord2d0&&e.generateTexCoords()}}),Shader=Serializable.extend({init:function(e,t){if(this._super(),!e)throw"RenderingContext not passed to canvas";this.descriptor=t,this.context=e,this.program=e.gl.createProgram(),this.shaders=[],this.requirements=new ShaderRequirements,this.linked=!1,this.failed=!1,this.uniformLocations={},this.explicitLocations={position:0,normal:1,texcoord2d0:2,tangent:3,bitangent:4}},excluded:function(){return!0},included:function(){return["descriptor"]},addVertexShader:function(e){var t=new VertexShader(this,e);this.addShader(t)},addFragmentShader:function(e){var t=new FragmentShader(this,e);this.addShader(t)},addShader:function(e){this.shaders.push(e),e.attach()},link:function(){if(!this.failed){for(var e=0;e<this.shaders.length;e++)this.shaders[e].compile(this.context);for(var t in this.explicitLocations)this.context.gl.bindAttribLocation(this.program,this.explicitLocations[t],t);this.uniformLocations={},this.linked=!0,this.context.gl.linkProgram(this.program),this.context.gl.getProgramParameter(this.program,this.context.gl.LINK_STATUS)||(this.linked=!1,this.failed=!0)}},use:function(e){this.failed||this.shaders.length<2||(this.linked||this.link(),this.linked&&(this.context.gl.useProgram(this.program),this.bindUniforms(e)))},getAttribLocation:function(e){return e in this.explicitLocations?this.explicitLocations[e]:this.context.gl.getAttribLocation(this.program,e)},getUniformLocation:function(e){return e in this.uniformLocations||(this.uniformLocations[e]=this.context.gl.getUniformLocation(this.program,e)),this.uniformLocations[e]},bindUniforms:function(e){if(e&&this.linked)for(var t in e){var i=this.getUniformLocation(t);if(i&&-1!=i){var n=e[t];if(!n)throw"Uniform '"+t+"' is undefined.";n.bind(this.context,i)}}},bindSamplers:function(e){if(e&&0!=e.length&&this.linked){for(var t=this.context.gl,i=0,n=0;n<e.length;n++){var r=e[n],s=this.getUniformLocation(r.name);-1!=s&&(r.bind(this.context,s,i),i++)}t.activeTexture(t.TEXTURE0)}},unbindSamplers:function(e){if(e&&0!=e.length&&this.linked){for(var t=this.context.gl,i=0,n=0;n<e.length;n++){var r=e[n],s=this.getUniformLocation(r.name);-1!=s&&(r.unbind(this.context,s,i),i++)}t.activeTexture(t.TEXTURE0)}}}),Uniform=Cloneable.extend({init:function(e){this.value=e},bind:function(){},clone:function(){var e=this._super();return e.value=this.value,e}}),UniformInt=Uniform.extend({bind:function(e,t){e.gl.uniform1i(t,this.value)},type:function(){return"UniformInt"}}),UniformFloat=Uniform.extend({bind:function(e,t){e.gl.uniform1f(t,this.value)},type:function(){return"UniformFloat"}}),UniformVec2=Uniform.extend({init:function(e){this._super(e instanceof Float32Array?e:new Float32Array(e))},type:function(){return"UniformVec2"},bind:function(e,t){e.gl.uniform2fv(t,this.value)},clone:function(){var e=this._super();return e.value=vec2.clone(this.value),e}}),UniformVec3=Uniform.extend({init:function(e){this._super(e instanceof Float32Array?e:new Float32Array(e))},type:function(){return"UniformVec3"},bind:function(e,t){e.gl.uniform3fv(t,this.value)},clone:function(){var e=this._super();return e.value=vec3.clone(this.value),e}}),UniformVec4=Uniform.extend({init:function(e){this._super(e instanceof Float32Array?e:new Float32Array(e))},type:function(){return"UniformVec4"},bind:function(e,t){e.gl.uniform4fv(t,this.value)},clone:function(){var e=this._super();return e.value=vec4.clone(this.value),e}}),UniformColor=UniformVec4.extend({init:function(e){return e?e instanceof Color?void this._super(e.toVector()):"r"in e&&"g"in e&&"b"in e&&"a"in e?void this._super(vec4.fromValues(e.r,e.g,e.b,e.a)):void this._super(vec4.fromValues(1,1,1,1)):void this._super(vec4.fromValues(1,1,1,1))},type:function(){return"UniformColor"}}),UniformMat4=Uniform.extend({bind:function(e,t){e.gl.uniformMatrix4fv(t,!1,this.value)},type:function(){return"UniformMat4"},clone:function(){var e=this._super();return e.value=mat4.clone(this.value),e}}),fallbackTexture=!1,Sampler=Serializable.extend({init:function(e,t){this.name=e,this.texture=t},type:function(){return"Sampler"},createFallbackTexture:function(e){fallbackTexture=new Texture(e);var t=document.createElement("canvas");t.width=2,t.height=2;var i=t.getContext("2d");i.fillStyle="rgb(255,255,255)",i.fillRect(0,0,2,2),fallbackTexture.setImage(e,t)},bind:function(e,t,i){return e.gl.activeTexture(i+e.gl.TEXTURE0),e.gl.uniform1i(t,i),this.texture&&this.texture.loaded?void this.texture.bind(e):(fallbackTexture||this.createFallbackTexture(e),void fallbackTexture.bind(e))},unbind:function(e,t,i){return e.gl.activeTexture(i+e.gl.TEXTURE0),this.texture&&this.texture.loaded?void this.texture.unbind(e):void fallbackTexture.unbind(e)},clone:function(){var e=this._super();return e.name=this.name,e.texture=this.texture,e}}),Camera=Serializable.extend({init:function(e,t,i){this.viewMatrix=e,this.viewInverseMatrix=mat4.invert(mat4.create(),this.viewMatrix),this.projectionMatrix=t,this.renderStage=i,this.target=new TargetScreen,this.backgroundColor=new Color(0,0,0,0),this.clearMask=!1,this.order=0,this.layerMask=4294967295,this.frustum=!1},type:function(){return"Camera"},excluded:function(){return["renderStage","target"]},startRender:function(e){e.projection.push(),e.projection.multiply(this.projectionMatrix),e.modelview.push(),e.modelview.multiply(this.viewMatrix),mat4.invert(this.viewInverseMatrix,this.viewMatrix),e.gl.clearColor(this.backgroundColor.r,this.backgroundColor.g,this.backgroundColor.b,this.backgroundColor.a),e.gl.clearDepth(1),e.gl.depthMask(!0),e.gl.clear(this.clearMask===!1?e.gl.COLOR_BUFFER_BIT|e.gl.DEPTH_BUFFER_BIT:this.clearMask)},endRender:function(e){e.modelview.pop(),e.projection.pop()},render:function(e,t){e.camera=this,this.renderStage.render(e,t,this),e.camera=!1},getFieldOfView:function(){return 2*Math.atan(1/this.projectionMatrix[5])},getDirection:function(e){return e||(e=vec3.create()),e[0]=-this.viewMatrix[2],e[1]=-this.viewMatrix[6],e[2]=-this.viewMatrix[10],e},getPosition:function(e){e||(e=vec3.create());var t=mat4.invert(mat4.create(),this.viewMatrix);return mat4.translation(e,t),e},setPosition:function(e){var t=this.getPosition();vec3.sub(t,t,e);var i=mat4.fromTranslation(mat4.create(),t);mat4.mul(this.viewMatrix,this.viewMatrix,i)},center:function(e){var t=this.getDirection(),i=this.getPosition(),n=new Plane;n.setByNormalAndPoint(t,i);var r=n.projectToPlane(e);this.setPosition(r)},fitToView:function(e){if(e instanceof BoundingVolume&&e.center&&(this.center(e.center),!e.isPoint())){var t=0;e instanceof BoundingSphere?t=2*e.radius:e instanceof BoundingBox&&(t=2*e.getOuterSphereRadius());var i=t/Math.sin(this.getFieldOfView()/2)-t,n=this.getDirection(),r=vec3.create();vec3.scale(n,n,-i),vec3.add(r,e.center,n),this.setPosition(r)}}}),RenderStage=Class.extend({init:function(){this.parent=!1,this.substages=[],this.started=!1,this.enabled=!0},addStage:function(e){return e.parent=this,this.substages.push(e),e},removeStage:function(e){for(var t=0;t<this.substages.length;t++)if(this.substages[t]===e)return e.parent=!1,this.substages.splice(t,1),!0;return!1},removeStagesByType:function(e){for(var t=[],i=0;i<this.substages.length;i++)this.substages[i]instanceof e&&(t.push(this.substages[i]),this.substages.splice(i,1),i--);for(var i in t)t[i].parent=!1;return t},clearStages:function(){for(var e in this.substages)this.substages[e].parent=!1;this.substages=[]},getStageByType:function(e){for(var t=0;t<this.substages.length;t++)if(this.substages[t]instanceof e)return this.substages[t];return!1},start:function(e,t,i){this.started=!0,this.onStart(e,t,i);for(var n in this.substages)this.substages[n].start(e,t,i)},render:function(e,t,i){if(this.enabled){this.onPreRender(e,t,i);for(var n=0;n<this.substages.length;n++)this.substages[n].started||this.substages[n].start(e,t.engine,i),this.substages[n].render(e,t,i);this.onPostRender(e,t,i)}},enable:function(){return this.enabled=!0,this.onEnable(),this},disable:function(){return this.enabled=!1,this.onDisable(),this},onStart:function(){},onPreRender:function(){},onPostRender:function(){},onEnable:function(){},onDisable:function(){}}),MaterialRenderStage=RenderStage.extend({init:function(){this._super(),this.enableDynamicBatching=!0,this.visibleRenderers=0,this.visibleSolidRenderers=0,this.visibleSolidBatches=0,this.visibleSolidFaces=0,this.visibleTransparentRenderers=0,this.visibleTransparentFaces=0,this.visibleTransparentBatches=0,this.solidRenderers=[],this.solidRendererBatches={},this.transparentRenderers=[],this.transparentRendererBatches={},this.shadowMapFallbackSampler=null,this.diffuseFallback=null,this.bindCameraTarget={started:!0,start:function(){},render:function(e,t,i){i.target.bind(e)}},this.unbindCameraTarget={started:!0,start:function(){},render:function(e,t,i){i.target.unbind(e)}},this.shadowMapStage=this.addStage(new ShadowMapRenderStage),this.depthStage=this.addStage(new DepthRenderStage).disable(),this.oitStage=this.addStage(new OITRenderStage).disable(),this.addStage(this.bindCameraTarget),this.skyboxStage=this.addStage(new SkyboxRenderStage),this.opaqueStage=this.addStage(new OpaqueGeometryRenderStage),this.transparentStage=this.addStage(new TransparentGeometryRenderStage),this.addStage(this.unbindCameraTarget),this.eyePosition=vec3.create(),this.invModelview=mat4.create(),this.sharedUniforms={view:new UniformMat4(mat4.create()),viewInverse:new UniformMat4(mat4.create()),projection:new UniformMat4(mat4.create())},this.rendererUniforms={model:new UniformMat4(null),modelview:new UniformMat4(null),modelviewInverse:new UniformMat4(null),receiveShadows:new UniformInt(1)},this.shadowUniforms={lightView:new UniformMat4(mat4.create()),lightProjection:new UniformMat4(mat4.create()),shadowIntensity:new UniformFloat(0)}},onStart:function(e,t){this.diffuseFallback=new Sampler("diffuse0",t.WhiteTexture),t.options.ssao===!0&&this.depthStage.enable(),"sorted"!=t.options.transparencyMode&&this.oitStage.enable()},prepareShadowContext:function(e,t){if(null===this.shadowMapFallbackSampler&&(this.shadowMapFallbackSampler=new Sampler("shadow0",t.engine.WhiteTexture)),this.shadowMapStage.active){var i=this.shadowMapStage.getFirstShadowCastingLight(t);i&&(mat4.copy(this.shadowUniforms.lightView.value,this.shadowMapStage.lightView),mat4.copy(this.shadowUniforms.lightProjection.value,this.shadowMapStage.lightProj),this.shadowUniforms.shadowIntensity.value=i.shadowIntensity,e.shadow={shadow0:this.shadowMapStage.shadowSampler,linearDepthConstant:this.shadowMapStage.material.uniforms.linearDepthConstant,lightProjection:this.shadowUniforms.lightProjection,lightView:this.shadowUniforms.lightView,shadowIntensity:this.shadowUniforms.shadowIntensity})}},prepareLightContext:function(e,t){for(var i=0;i<t.lights.length;i++){var n=t.lights[i];n.uniforms?(vec3.copy(n.uniforms.lightDirection.value,n.direction),n.uniforms.lightIntensity.value=n.intensity,n.uniforms.lightColor.value[0]=n.color.r,n.uniforms.lightColor.value[1]=n.color.g,n.uniforms.lightColor.value[2]=n.color.b,n.uniforms.lightColor.value[3]=n.color.a,n.uniforms.useShadows.value=n.shadowCasting?1:0):n.uniforms={lightDirection:new UniformVec3(n.direction),lightColor:new UniformColor(n.color),lightIntensity:new UniformFloat(n.intensity),useShadows:new UniformInt(n.shadowCasting?1:0)}}},prepareShared:function(e){mat4.invert(this.invModelview,e.modelview.top()),mat4.translation(this.eyePosition,this.invModelview),mat4.copy(this.sharedUniforms.projection.value,e.projection.top()),mat4.copy(this.sharedUniforms.view.value,e.camera.viewMatrix),mat4.copy(this.sharedUniforms.viewInverse.value,e.camera.viewInverseMatrix)},onPreRender:function(e,t,i){this.solidRendererBatches={},this.transparentRendererBatches={},this.solidRenderers.length=0,this.transparentRenderers.length=0,this.visibleSolidRenderers=0,this.visibleSolidBatches=0,this.visibleSolidFaces=0,this.visibleTransparentRenderers=0,this.visibleTransparentFaces=0,this.visibleTransparentBatches=0;var n=t.dynamicSpace.frustumCast(i.frustum,i.layerMask);this.visibleRenderers=n.length;for(var r=0;r<n.length;r++)n[r].transparent?(this.enableDynamicBatching&&"sorted"!=t.engine.options.transparencyMode&&(n[r].material.id in this.transparentRendererBatches?this.transparentRendererBatches[n[r].material.id].push(n[r]):(this.transparentRendererBatches[n[r].material.id]=[n[r]],this.visibleTransparentBatches++)),this.transparentRenderers.push(n[r]),this.visibleTransparentFaces+=n[r].submesh.faces.length/3):(this.enableDynamicBatching&&(n[r].material.id in this.solidRendererBatches?this.solidRendererBatches[n[r].material.id].push(n[r]):(this.solidRendererBatches[n[r].material.id]=[n[r]],this.visibleSolidBatches++)),this.visibleSolidFaces+=n[r].submesh.faces.length/3,this.solidRenderers.push(n[r]));if(this.visibleTransparentRenderers=this.transparentRenderers.length,this.visibleSolidRenderers=this.solidRenderers.length,"sorted"==t.engine.options.transparencyMode){var s=this.eyePosition;this.transparentRenderers.sort(function(e,t){var i=vec3.squaredDistance(s,e.globalBoundingSphere.center),n=vec3.squaredDistance(s,t.globalBoundingSphere.center);return i>n?-1:n>i?1:0})}this.prepareShared(e),this.prepareLightContext(e,t),this.prepareShadowContext(e,t)},onPostRender:function(e){e.shadow=!1,e.light=!1},renderBatched:function(e,t){var i=[];i.push(e.shadow?e.shadow.shadow0:this.shadowMapFallbackSampler);var n=!1;for(var r in t){var s=t[r],a=s[0].material,o=a.shader;o!=n&&(o.use(),n=o,e.shadow&&o.bindUniforms(this.shadowUniforms),o.bindUniforms(this.sharedUniforms),e.light&&e.light.uniforms&&o.bindUniforms(e.light.uniforms));var h=i.concat(a.samplers);0==a.samplers.length&&h.push(this.diffuseFallback),o.bindSamplers(h),o.bindUniforms(a.uniforms);for(var c=0;c<s.length;++c)e.modelview.push(),e.modelview.multiply(s[c].matrix),this.rendererUniforms.model.value=s[c].matrix,this.rendererUniforms.modelview.value=e.modelview.top(),this.rendererUniforms.modelviewInverse.value=this.invModelview,this.rendererUniforms.receiveShadows.value=s[c].receiveShadows,o.bindUniforms(this.rendererUniforms),s[c].render(e),e.modelview.pop();o.unbindSamplers(h)}},renderBruteForce:function(e,t){var i=[];i.push(e.shadow?e.shadow.shadow0:this.shadowMapFallbackSampler);for(var n=0;n<t.length;++n){var r=t[n];e.modelview.push(),e.modelview.multiply(r.matrix);var s;s=r.material.samplers.length>0?i:i.concat([this.diffuseFallback]),r.material.bind(r.getDefaultUniforms(e),s),r.render(e),r.material.unbind(i),e.modelview.pop()}}}),ShaderRenderStage=RenderStage.extend({init:function(e,t){this._super(t),this.shader=e,this.uniforms={}},onPostRender:function(e,t,i){this.shader.use(this.uniforms),this.shader.requirements.transparent&&(e.gl.blendFunc(e.gl.SRC_ALPHA,e.gl.ONE),e.gl.enable(e.gl.BLEND));var n=t.dynamicSpace.frustumCast(i.frustum,i.layerMask);for(var r in n)n[r].renderGeometry(e,this.shader);this.shader.requirements.transparent&&e.gl.disable(e.gl.BLEND)}}),DebugRenderStage=RenderStage.extend({init:function(e,t){this._super(e),this.shader=t.assetsManager.addShaderSource("shaders/default/debug"),t.assetsManager.load()},onPostRender:function(e,t,i){var n=t.dynamicSpace.frustumCast(i.frustum,i.layerMask);e.gl.blendFunc(e.gl.SRC_ALPHA,e.gl.ONE_MINUS_SRC_ALPHA),e.gl.enable(e.gl.BLEND),this.shader.use({color:new UniformVec4([.5,1,0,.3])});var r=[];for(var s in n)n[s].transparent?r.push(n[s]):(n[s].renderGeometry(e,this.shader),this.visibleSolidRenderers++);this.shader.use({color:new UniformVec4([.5,.5,1,.3])});for(var s in r)r[s].renderGeometry(e,this.shader);e.gl.disable(e.gl.BLEND)}}),DepthRenderStage=RenderStage.extend({init:function(e){this._super(),this.target=null,this.sampler=new Sampler("depth0",null),this.size=vec2.fromValues(1024,1024),e&&vec2.copy(this.size,e)},onStart:function(e,t){try{this.target=new TargetTextureFloat(this.size,e,!1),this.sampler.texture=this.target.texture}catch(i){return console.warn("DepthRenderStage: ",i),void this.disable()}this.material=new Material(t.assetsManager.addShaderSource("shaders/default/depth"),{zNear:new UniformFloat(.1),zFar:new UniformFloat(1e3)},[])},onPreRender:function(e,t,i){if(i.target.size[0]!=this.size[0]||i.target.size[1]!=this.size[1]){var n=i.target.size;vec2.copy(this.size,n),this.target.setSize(n[0],n[1])}},onPostRender:function(e,t,i){this.material.uniforms.zNear.value=i.near,this.material.uniforms.zFar.value=i.far,this.target.bind(e);var n=e.gl;n.enable(n.DEPTH_TEST),n.depthFunc(n.LESS),n.depthMask(!0),this.material.bind();for(var r=this.parent.solidRenderers,s=0;s<r.length;++s)e.modelview.push(),e.modelview.multiply(r[s].matrix),this.material.shader.bindUniforms(r[s].material.uniforms),r[s].renderGeometry(e,this.material.shader),e.modelview.pop();this.material.unbind(),this.renderAlphaMapped(e,t,i),n.disable(n.DEPTH_TEST),this.target.unbind(e)},renderAlphaMapped:function(e){var t=this.parent.transparentRendererBatches,i=this.material.shader;i.use(),i.bindUniforms(this.material.uniforms),i.bindUniforms(this.parent.sharedUniforms),e.light&&e.light.uniforms&&i.bindUniforms(e.light.uniforms);for(var n in t){var r,s=t[n],a=s[0].material;r=this.material.samplers.length>0?this.material.samplers.concat(a.samplers):a.samplers,i.bindUniforms(a.uniforms),i.bindSamplers(r);for(var o=0;o<s.length;++o)e.modelview.push(),e.modelview.multiply(s[o].matrix),this.parent.rendererUniforms.model.value=s[o].matrix,this.parent.rendererUniforms.modelview.value=e.modelview.top(),this.parent.rendererUniforms.modelviewInverse.value=this.parent.invModelview,i.bindUniforms(this.parent.rendererUniforms),s[o].renderGeometry(e,i),e.modelview.pop();i.unbindSamplers(r)}}}),ShadowMapRenderStage=RenderStage.extend({init:function(e){this._super(),this.size=2048,e&&(this.size=e),this.target=!1,this.shadowSampler=!1,this.material=!1,this.lightView=mat4.create(),this.lightProj=mat4.create(),this.active=!1,this.blurEnabled=!1,this.lightPosition=vec3.create(),this.blurProj=mat4.create(),this.blurView=mat4.identity(mat4.create())},onStart:function(e,t){this.target=new TargetTexture([this.size,this.size],e,!1),this.shadowSampler=new Sampler("shadow0",this.target.texture),this.blurSampler=new Sampler("tex0",this.target.texture),this.helperTarget=new TargetTexture([this.size,this.size],e,!1),this.helperTargetSampler=new Sampler("tex0",this.helperTarget.texture),this.material=new Material(t.assetsManager.addShaderSource("DepthRGBA"),{linearDepthConstant:new UniformFloat(1),packingType:new UniformInt(2)},[]),this.gaussianBlurMaterial=new Material(t.assetsManager.addShaderSource("GaussianBlur"),{screenWidth:new UniformFloat(1),screenHeight:new UniformFloat(1),orientation:new UniformInt(0),kernelSize:new UniformInt(5),modelview:new UniformMat4(!1),projection:new UniformMat4(!1)},[]);var i=[0,0,0,0,1,0,1,1,0,1,0,0],n=[0,1,0,0,1,0,1,1],r=[0,1,2,0,2,3];this.quad=new TrianglesRenderBuffer(e,r),this.quad.add("position",i,3),this.quad.add("texcoord2d0",n,2),t.assetsManager.load(function(){})},onPostRender:function(e,t){if(this.active=!1,this.parent&&this.parent instanceof MaterialRenderStage&&this.target&&this.material){var i=this.getFirstShadowCastingLight(t);i&&(this.renderShadows(e,t,i),this.blurEnabled&&(this.blurShadows(e,this.helperTarget,this.blurSampler,0,i.shadowBlurKernelSize),this.blurShadows(e,this.target,this.helperTargetSampler,1,i.shadowBlurKernelSize)),this.active=!0)}},getFirstShadowCastingLight:function(e){for(var t in e.lights)if(e.lights[t].shadowCasting===!0)return e.lights[t];return!1},getSceneBounds:function(e){var t=new BoundingSphere;return e.root.onEachChild(function(e){var i=e.getComponent(MeshRendererComponent);i&&i.enabled&&i.castShadows&&t.encapsulateSphere(i.getBoundingSphere())}),t},renderShadows:function(e,t,i){var n=this.getSceneBounds(t);mat4.ortho(this.lightProj,-n.radius,n.radius,-n.radius,n.radius,.1,2*n.radius),vec3.scale(this.lightPosition,i.direction,n.radius),mat4.lookAt(this.lightView,this.lightPosition,[0,0,0],[0,1,0]),this.target.bind(e);var r=e.gl;r.depthMask(!0),r.clearDepth(1),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),e.projection.push(),e.projection.load(this.lightProj),e.modelview.push(),e.modelview.load(this.lightView),r.enable(r.DEPTH_TEST),r.depthFunc(r.LESS),this.material.uniforms.linearDepthConstant.value=1/(2*n.radius),this.material.bind();for(var s in this.parent.solidRenderers)this.parent.solidRenderers[s].layer&i.shadowMask&&this.parent.solidRenderers[s].visible&&this.parent.solidRenderers[s].castShadows&&(e.modelview.push(),e.modelview.multiply(this.parent.solidRenderers[s].matrix),this.parent.solidRenderers[s].renderGeometry(e,this.material.shader),e.modelview.pop());this.material.unbind(),r.depthMask(!0),r.disable(r.DEPTH_TEST),e.modelview.pop(),e.projection.pop(),this.target.unbind(e)},blurShadows:function(e,t,i,n,r){if(this.gaussianBlurMaterial.shader.use(),this.gaussianBlurMaterial.shader.linked){var s=e.gl,a=t.getSize();mat4.ortho(this.blurProj,0,a[0],a[1],0,-10,10),this.gaussianBlurMaterial.uniforms.screenWidth.value=a[0],this.gaussianBlurMaterial.uniforms.screenHeight.value=a[1],this.gaussianBlurMaterial.uniforms.orientation.value=n,this.gaussianBlurMaterial.uniforms.kernelSize.value=r,e.projection.push(),e.projection.load(this.blurProj),e.modelview.push(),e.modelview.load(this.blurView),t.bind(e),s.disable(s.DEPTH_TEST),s.disable(s.CULL_FACE),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT),this.gaussianBlurMaterial.uniforms.modelview.value=e.modelview.top(),this.gaussianBlurMaterial.uniforms.projection.value=e.projection.top(),this.gaussianBlurMaterial.bind({},[i]);var o=this.gaussianBlurMaterial.shader,h=[];for(var c in this.quad.buffers){s.bindBuffer(s.ARRAY_BUFFER,this.quad.buffers[c]);var u=o.getAttribLocation(c);-1!=u&&(s.enableVertexAttribArray(u),h.push(u),s.vertexAttribPointer(u,this.quad.buffers[c].itemSize,s.FLOAT,!1,0,0))}this.quad.drawElements();for(var l in h)s.disableVertexAttribArray(h[l]);this.gaussianBlurMaterial.unbind(),t.unbind(e),e.modelview.pop(),e.projection.pop()}}}),PositionBufferRenderStage=RenderStage.extend({init:function(e){this._super(),this.size=2048,e&&(this.size=e),this.target=!1},onStart:function(e,t){this.target=new TargetTextureFloat([this.size,this.size],e,!1),this.material=new Material(t.assetsManager.addShaderSource("shaders/default/positionbuffer"),{ViewportSize:new UniformVec2(vec2.clone(t.scene.camera.target.size))},[]);var i=[0,0,0,0,1,0,1,1,0,1,0,0],n=[0,1,0,0,1,0,1,1],r=[0,1,2,0,2,3];this.quad=new TrianglesRenderBuffer(e,r),this.quad.add("position",i,3),this.quad.add("texcoord2d0",n,2),t.assetsManager.load(function(){})},onPreRender:function(e,t,i){vec2.set(this.material.uniforms.ViewportSize.value,i.target.size[0],i.target.size[1])},onPostRender:function(e){if(this.parent&&this.parent instanceof MaterialRenderStage&&this.target&&this.material){this.target.bind(e);var t=e.gl;t.depthMask(!0),t.clearDepth(1),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),t.enable(t.DEPTH_TEST),t.depthFunc(t.LESS),this.material.bind();for(var i in this.parent.solidRenderers)this.parent.solidRenderers[i].layer&&this.parent.solidRenderers[i].visible&&(e.modelview.push(),e.modelview.multiply(this.parent.solidRenderers[i].matrix),this.parent.solidRenderers[i].renderGeometry(e,this.material.shader),e.modelview.pop());this.material.unbind(),t.depthMask(!0),t.disable(t.DEPTH_TEST),this.target.unbind(e)}}}),SSAOBufferRenderStage=RenderStage.extend({init:function(){this._super(),this.size=!1,this.quad=!1,this.target=!1},setSize:function(e,t){this.size===!1&&(this.size=vec2.create()),this.size[0]=e,this.size[1]=t},onStart:function(e,t){this.size||(this.size=vec2.clone(t.scene.camera.target.size)),this.target=new TargetTextureFloat([t.scene.camera.target.size[0],t.scene.camera.target.size[1]],e,!1),this.material=new Material(t.assetsManager.addShaderSource("shaders/default/ssao"),{ViewportSize:new UniformVec2(vec2.clone(t.scene.camera.target.size)),ssaoGDisplace:new UniformFloat(t.options.ssaoGDisplace?t.options.ssaoGDisplace:6),ssaoRadius:new UniformFloat(t.options.ssaoRadius?t.options.ssaoRadius:8),ssaoDivider:new UniformFloat(t.options.ssaoDivider?t.options.ssaoDivider:.5)},[new Sampler("position0",this.parent.positionBufferStage.target.texture)]),this.material.name="SSAO";
  var i=[-1,-1,0,-1,1,0,1,1,0,1,-1,0],n=[0,1,0,0,1,0,1,1],r=[0,1,2,0,2,3];this.quad=new TrianglesRenderBuffer(e,r),this.quad.add("position",i,3),this.quad.add("texcoord2d0",n,2),t.assetsManager.load()},onPreRender:function(e,t,i){var n=i.target;(n.size[0]!=this.target.size[0]||n.size[1]!=this.target.size[1])&&(vec2.set(this.material.uniforms.ViewportSize.value,i.target.size[0],i.target.size[1]),this.setSize(n.size[0],n.size[1]),this.target.setSize(n.size[0],n.size[1]))},onPostRender:function(e){if(this.parent&&this.parent instanceof MaterialRenderStage&&this.target&&this.material){this.target.bind(e);var t=e.gl;if(t.disable(t.DEPTH_TEST),t.disable(t.CULL_FACE),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),this.material.bind(),this.material.shader.linked){var i=[];for(var n in this.quad.buffers){t.bindBuffer(t.ARRAY_BUFFER,this.quad.buffers[n]);var r=t.getAttribLocation(this.material.shader.program,n);-1!=r&&(t.enableVertexAttribArray(r),i.push(r),t.vertexAttribPointer(r,this.quad.buffers[n].itemSize,t.FLOAT,!1,0,0))}this.quad.drawElements();for(var s in i)t.disableVertexAttribArray(i[s])}this.material.unbind(),this.target.unbind(e)}}}),SkyboxRenderStage=RenderStage.extend({init:function(){this._super(),this.uniforms={model:new UniformMat4(mat4.create()),modelview:new UniformMat4(mat4.create()),modelviewInverse:new UniformMat4(mat4.create()),projection:new UniformMat4(mat4.create()),view:new UniformMat4(mat4.create()),viewInverse:new UniformMat4(mat4.create()),zNear:new UniformFloat(0),zFar:new UniformFloat(0),lightDirection:new UniformVec3(vec3.create()),lightColor:new UniformColor(new Color),lightIntensity:new UniformFloat(1)}},onPostRender:function(e,t,i){var n=t.cameraNode.getComponent(SkyboxComponent);if(n)for(var r=[this.parent.shadowMapFallbackSampler],s=n.meshNode.getComponent(MeshRendererComponent),a=s.meshRenderers,o=0;o<a.length;o++){var h=a[o],c=h.getDefaultUniforms(e,this.uniforms);mat4.identity(c.model.value),mat4.translate(c.model.value,c.model.value,i.getPosition()),h.material.bind(c,r),h.render(e),h.material.unbind(r)}}}),OpaqueGeometryRenderStage=RenderStage.extend({onPostRender:function(e,t){var i=e.gl;if(i.enable(i.DEPTH_TEST),i.depthFunc(i.LESS),i.depthMask(!0),t.lights.length>0&&(e.light=t.lights[0]),this.parent.enableDynamicBatching?this.parent.renderBatched(e,this.parent.solidRendererBatches):this.parent.renderBruteForce(e,this.parent.solidRenderers),t.lights.length>1){i.depthMask(!1),i.depthFunc(i.LEQUAL),i.blendFunc(i.ONE,i.ONE),i.enable(i.BLEND);for(var n=1;n<t.lights.length;n++)e.light=t.lights[n],this.parent.enableDynamicBatching?this.parent.renderBatched(e,this.parent.solidRendererBatches):this.parent.renderBruteForce(e,this.parent.solidRenderers);i.disable(i.BLEND),i.depthMask(!0),i.depthFunc(i.LESS)}i.disable(i.DEPTH_TEST),e.light=!1}}),TransparentGeometryRenderStage=RenderStage.extend({renderSorted:function(e){var t=e.gl;t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.enable(t.BLEND),t.depthMask(!1),t.depthFunc(t.LESS),t.enable(t.DEPTH_TEST),this.parent.renderBruteForce(e,this.parent.transparentRenderers),t.disable(t.BLEND),t.disable(t.DEPTH_TEST),t.depthMask(!0)},onPostRender:function(e,t,i){"sorted"==t.engine.options.transparencyMode?this.renderSorted(e,t,i):this.parent.oitStage.renderAlphaMapped(e,t,i)}}),OITRenderStage=RenderStage.extend({init:function(){this._super(),this.diffuseFallback=null,this.oitClearColor=new Color(0,0,0,0),this.transparencyTarget=!1,this.transparencySampler=!1,this.transparencyWeight=!1,this.transparencyWeightSampler=!1,this.transparencyAccum=!1},onStart:function(e,t,i){var n=i.target.size;this.diffuseFallback=new Sampler("diffuse0",t.WhiteTexture),this.transparencyTarget=new TargetTextureFloat(n,e,!1),this.transparencySampler=new Sampler("oitAccum",this.transparencyTarget.texture),this.transparencyWeight=new TargetTextureFloat(n,e,!1),this.transparencyWeightSampler=new Sampler("oitWeight",this.transparencyWeight.texture),this.transparencyAccum=new Material(t.assetsManager.addShaderSource("shaders/default/OITAccum"),{render_mode:new UniformInt(0)},[]),t.assetsManager.load()},onPostRender:function(e,t,i){(i.target.size[0]!=this.transparencyTarget.size[0]||i.target.size[1]!=this.transparencyTarget.size[1])&&(this.transparencyTarget.setSize(i.target.size[0],i.target.size[1]),this.transparencyWeight.setSize(i.target.size[0],i.target.size[1])),this.oitClearColor.set(0,0,0,0),this.transparencyTarget.bind(e,!1,this.oitClearColor),this.renderPass(e,t,i,!0),this.transparencyTarget.unbind(e),this.oitClearColor.set(1,1,1,1),this.transparencyWeight.bind(e,!1,this.oitClearColor),this.renderPass(e,t,i,!1),this.transparencyWeight.unbind(e)},renderTransparentBatches:function(e,t,i,n){var r=this.parent.transparentRendererBatches,s=n.shader;s.use(),s.bindUniforms(n.uniforms),s.bindUniforms(this.parent.sharedUniforms),e.light&&e.light.uniforms&&s.bindUniforms(e.light.uniforms);for(var a in r){var o,h=r[a],c=h[0].material;o=n.samplers.length>0?n.samplers.concat(c.samplers):c.samplers,0==c.samplers.length&&o.push(this.diffuseFallback),s.bindUniforms(c.uniforms),s.bindSamplers(o);for(var u=0;u<h.length;++u)e.modelview.push(),e.modelview.multiply(h[u].matrix),this.parent.rendererUniforms.model.value=h[u].matrix,this.parent.rendererUniforms.modelview.value=e.modelview.top(),this.parent.rendererUniforms.modelviewInverse.value=this.parent.invModelview,s.bindUniforms(this.parent.rendererUniforms),h[u].renderGeometry(e,s),e.modelview.pop();s.unbindSamplers(o)}},renderAlphaMapped:function(e,t,i){var n=e.gl;n.depthMask(!0),n.depthFunc(n.LESS),n.enable(n.DEPTH_TEST),this.transparencyAccum.uniforms.render_mode.value=2,this.renderTransparentBatches(e,t,i,this.transparencyAccum),n.disable(n.DEPTH_TEST)},renderPass:function(e,t,i,n){var r=e.gl;r.depthMask(!0),r.colorMask(!1,!1,!1,!1),this.parent.opaqueStage.render(e,t,i),this.renderAlphaMapped(e,t,i),r.colorMask(!0,!0,!0,!0),r.depthFunc(r.LESS),r.enable(r.DEPTH_TEST),"blended"==t.engine.options.transparencyMode&&(n?(r.depthMask(!1),r.blendEquation(r.FUNC_ADD),r.blendFunc(r.ONE,r.ONE),r.enable(r.BLEND),this.transparencyAccum.uniforms.render_mode.value=0):(r.depthMask(!1),r.blendEquation(r.FUNC_ADD),r.blendFunc(r.ZERO,r.ONE_MINUS_SRC_ALPHA),r.enable(r.BLEND),this.transparencyAccum.uniforms.render_mode.value=1)),"stochastic"==t.engine.options.transparencyMode&&(n?(r.depthMask(!0),this.transparencyAccum.uniforms.render_mode.value=3):(r.depthMask(!1),r.blendEquation(r.FUNC_ADD),r.blendFunc(r.ZERO,r.ONE_MINUS_SRC_ALPHA),r.enable(r.BLEND),this.transparencyAccum.uniforms.render_mode.value=1)),this.renderTransparentBatches(e,t,i,this.transparencyAccum),r.disable(r.BLEND),r.disable(r.DEPTH_TEST),r.depthMask(!0)}}),PostProcessRenderStage=RenderStage.extend({init:function(){this._super(),this.size=!1,this.src=!1,this.dst=!1,this.srcSampler=!1,this.dstSampler=!1,this.quad=!1,this.material=!1,this.generator=this.getGeneratorStage(),this.generator.parent=this},setSize:function(e,t){this.size===!1&&(this.size=vec2.create()),this.size[0]=e,this.size[1]=t},getGeneratorStage:function(){return new MaterialRenderStage},onStart:function(e,t,i){this.size||(this.size=vec2.clone(i.target.size)),this.src=new TargetTexture(this.size,e,!1),this.srcSampler=new Sampler("src",this.src.texture),this.dst=new TargetTexture(this.size,e,!1),this.dstSampler=new Sampler("src",this.dst.texture),this.material=new Material(t.assetsManager.addShaderSource("shaders/default/ScreenQuad"),{},[]),this.material.name="To Screen";var n=[-1,-1,0,-1,1,0,1,1,0,1,-1,0],r=[0,0,0,1,1,1,1,0],s=[0,1,2,0,2,3];this.quad=new TrianglesRenderBuffer(e,s),this.quad.add("position",n,3),this.quad.add("uv0",r,2),t.assetsManager.load(),this.generator.start(e,t,i)},onPreRender:function(e,t,i){var n=i.target;(n.size[0]!=this.src.size[0]||n.size[1]!=this.src.size[1])&&(this.setSize(n.size[0],n.size[1]),this.src.setSize(n.size[0],n.size[1]),this.dst.setSize(n.size[0],n.size[1])),this.substages.length>0&&(i.target=this.src),this.generator.render(e,t,i),i.target=n},onPostRender:function(e,t,i){0!=this.substages.length&&(i.target instanceof TargetTexture?(i.target.bind(e),this.renderEffect(e,this.material,this.srcSampler),i.target.unbind(e)):this.renderEffect(e,this.material,this.srcSampler),this.swapBuffers())},swapBuffers:function(){var e=this.src,t=this.srcSampler;this.src=this.dst,this.srcSampler=this.dstSampler,this.dst=e,this.dstSampler=t},renderEffect:function(e,t,i){var n=e.gl;n.disable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),t.bind({},[i]),this.renderQuad(e,t.shader),t.unbind([i])},renderQuad:function(e,t){if(t.linked){var i=e.gl,n=[];for(var r in this.quad.buffers){i.bindBuffer(i.ARRAY_BUFFER,this.quad.buffers[r]);var s=t.getAttribLocation(r);-1!=s&&(i.enableVertexAttribArray(s),n.push(s),i.vertexAttribPointer(s,this.quad.buffers[r].itemSize,i.FLOAT,!1,0,0))}this.quad.drawElements();for(var a=0;a<n.length;a++)i.disableVertexAttribArray(n[a])}}}),PostProcess=RenderStage.extend({init:function(){this._super(),this.material=!1},onPostRender:function(e){if(!(this.parent instanceof PostProcessRenderStage))throw"PostProcess can only be the sub-stage of a PostProcessRenderStage";if(!this.material)throw"PostProcess must have a material defined";this.parent.dst.bind(e),this.parent.renderEffect(e,this.material,this.parent.srcSampler),this.parent.dst.unbind(e),this.parent.swapBuffers()}}),AntiAliasPostProcess=PostProcess.extend({init:function(){this._super()},onStart:function(e,t){this.material=new Material(t.assetsManager.addShaderSource("shaders/default/postprocess_fxaa"),{ViewportSize:new UniformVec2(vec2.clone(this.parent.size)),reduce_min:new UniformFloat(1/16),reduce_mul:new UniformFloat(1/8),span_max:new UniformFloat(8)},[]),this.material.name="AntiAlias",t.assetsManager.load()},onPreRender:function(e,t,i){this._super(e,t,i),vec2.set(this.material.uniforms.ViewportSize.value,this.parent.size[0],this.parent.size[1])}}),OITPostProcess=PostProcess.extend({init:function(){this._super()},onStart:function(e,t){this.material=new Material(t.assetsManager.addShaderSource("shaders/default/OITRender"),{ViewportSize:new UniformVec2(vec2.clone(this.parent.size)),render_mode:new UniformInt(0)},[this.parent.generator.oitStage.transparencySampler,this.parent.generator.oitStage.transparencyWeightSampler]),this.material.name="OIT",t.assetsManager.load()},onPreRender:function(e,t,i){switch(this._super(e,t,i),vec2.set(this.material.uniforms.ViewportSize.value,this.parent.size[0],this.parent.size[1]),t.engine.options.transparencyMode){case"blended":this.material.uniforms.render_mode.value=0;break;case"stochastic":this.material.uniforms.render_mode.value=1}}}),SSAOPostProcess=PostProcess.extend({init:function(){this._super(),this.ssaoOnly=!1},onStart:function(e,t){this.material=new Material(t.assetsManager.addShaderSource("shaders/default/postprocess_ssao"),{ViewportSize:new UniformVec2(vec2.clone(this.parent.size)),ssaoOnly:new UniformInt(this.ssaoOnly===!0?1:0),gdisplace:new UniformFloat(t.options.ssaoGDisplace?t.options.ssaoGDisplace:.3),radius:new UniformFloat(t.options.ssaoRadius?t.options.ssaoRadius:2),luminanceInfluence:new UniformFloat(t.options.ssaoLuminanceInfluence?t.options.ssaoLuminanceInfluence:.7),brightness:new UniformFloat(t.options.ssaoBrightness?t.options.ssaoBrightness:1)},[this.parent.generator.depthStage.sampler]),this.material.name="SSAO",this.material.samplers.push("sorted"==t.options.transparencyMode?new Sampler("oitWeight",t.WhiteTexture):this.parent.generator.oitStage.transparencyWeightSampler),t.assetsManager.load()},onPreRender:function(e,t,i){this._super(e,t,i),vec2.set(this.material.uniforms.ViewportSize.value,this.parent.size[0],this.parent.size[1]),this.material.uniforms.ssaoOnly.value=this.ssaoOnly===!0?1:0}}),RenderTarget=Class.extend({init:function(e){this.size=vec2.create(),e&&vec2.copy(this.size,e)},type:function(){return"RenderTarget"},bind:function(e){e.gl.viewport(0,0,this.size[0],this.size[1])},unbind:function(){},setSize:function(e,t){this.size[0]=e,this.size[1]=t},getSize:function(){return this.size}}),TargetScreen=RenderTarget.extend({init:function(e){this._super(e),this.position=vec2.create()},type:function(){return"TargetScreen"},setPosition:function(e,t){this.position[0]=e,this.position[1]=t},getPosition:function(){return this.position},bind:function(e){e.gl.viewport(0,0,this.size[0],this.size[1])},unbind:function(){}}),TargetTexture=RenderTarget.extend({init:function(e,t,i){var n=e;if(e instanceof Texture&&(n=e.size,this.texture=e),this.useDepthTexture=i===!0,this.rebuild=!1,this._super(n),this.useDepthTexture){var r=t.gl.getExtension("WEBGL_depth_texture")||t.gl.getExtension("WEBKIT_WEBGL_depth_texture");if(!r)throw"TargetTexture: Depth texture reqeusted, but not available."}this.build(t)},type:function(){return"TargetTexture"},setSize:function(e,t){this._super(e,t),this.rebuild=!0},getDataType:function(e){return e.gl.UNSIGNED_BYTE},getTextureFilter:function(e){return e.gl.NEAREST},build:function(e){var t=e.gl;this.frameBuffer=t.createFramebuffer(),this.texture||(this.texture=new Texture(e),t.bindTexture(t.TEXTURE_2D,this.texture.glTexture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,this.getTextureFilter(e)),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,this.getTextureFilter(e)),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.size[0],this.size[1],0,t.RGBA,this.getDataType(e),null),t.bindTexture(t.TEXTURE_2D,null)),this.useDepthTexture?(this.depth=new Texture(e),t.bindTexture(t.TEXTURE_2D,this.depth.glTexture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.DEPTH_COMPONENT,this.size[0],this.size[1],0,t.DEPTH_COMPONENT,t.UNSIGNED_SHORT,null),t.bindTexture(t.TEXTURE_2D,null)):(this.depth=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.depth),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_COMPONENT16,this.size[0],this.size[1]),t.bindRenderbuffer(t.RENDERBUFFER,null)),t.bindFramebuffer(t.FRAMEBUFFER,this.frameBuffer),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,this.texture.glTexture,0),this.useDepthTexture?t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,this.depth.glTexture,0):t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,this.depth),this.checkStatus(e),t.bindFramebuffer(t.FRAMEBUFFER,null),this.texture.loaded=!0},checkStatus:function(e){var t=e.gl,i=t.checkFramebufferStatus(t.FRAMEBUFFER);switch(i){case t.FRAMEBUFFER_COMPLETE:return!0;case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case t.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+i}},bind:function(e,t,i){var n=e.gl;this.rebuild&&(n.bindTexture(n.TEXTURE_2D,this.texture.glTexture),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,this.getTextureFilter(e)),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,this.getTextureFilter(e)),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,this.size[0],this.size[1],0,n.RGBA,this.getDataType(e),null),n.bindTexture(n.TEXTURE_2D,null),this.useDepthTexture?(n.bindTexture(n.TEXTURE_2D,this.depth.glTexture),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texImage2D(n.TEXTURE_2D,0,n.DEPTH_COMPONENT,this.size[0],this.size[1],0,n.DEPTH_COMPONENT,n.UNSIGNED_SHORT,null),n.bindTexture(n.TEXTURE_2D,null)):(n.bindRenderbuffer(n.RENDERBUFFER,this.depth),n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH_COMPONENT16,this.size[0],this.size[1]),n.bindRenderbuffer(n.RENDERBUFFER,null)),this.rebuild=!1),t=t===!0,i=i instanceof Color?i:!1,i||(e.camera?i=e.camera.backgroundColor:t=!0),n.bindFramebuffer(n.FRAMEBUFFER,this.frameBuffer),this._super(e),t||(n.clearColor(i.r,i.g,i.b,i.a),n.clearDepth(1),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT))},unbind:function(e){this._super(e),e.gl.bindFramebuffer(e.gl.FRAMEBUFFER,null)}}),TargetTextureFloat=TargetTexture.extend({init:function(e,t,i,n){if(this.extHalfFloat=t.gl.getExtension("OES_texture_half_float"),this.extFloat=t.gl.getExtension("OES_texture_float"),!this.extFloat&&!this.extHalfFloat)throw"TargetTextureFloat: Floating point textures are not supported on this system.";this.linearFloat=null,this.linearHalf=null,n||(this.linearFloat=t.gl.getExtension("OES_texture_float_linear"),this.linearHalf=t.gl.getExtension("OES_texture_half_float_linear")),this._super(e,t,i)},type:function(){return"TargetTextureFloat"},getDataType:function(e){if(this.extHalfFloat&&navigator&&navigator.platform)switch(navigator.platform){case"iPad":case"iPod":case"iPhone":return this.extHalfFloat.HALF_FLOAT_OES;default:return e.gl.FLOAT}return e.gl.FLOAT},getTextureFilter:function(e){return this.linearFloat&&this.linearHalf?e.gl.LINEAR:e.gl.NEAREST},build:function(e){var t=e.gl;this.frameBuffer=t.createFramebuffer(),this.texture||(this.texture=new Texture(e),t.bindTexture(t.TEXTURE_2D,this.texture.glTexture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,this.getTextureFilter(e)),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,this.getTextureFilter(e)),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.size[0],this.size[1],0,t.RGBA,this.getDataType(e),null),t.bindTexture(t.TEXTURE_2D,null)),this.useDepthTexture?(this.depth=new Texture(e),t.bindTexture(t.TEXTURE_2D,this.depth.glTexture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.DEPTH_COMPONENT,this.size[0],this.size[1],0,t.DEPTH_COMPONENT,t.UNSIGNED_SHORT,null),t.bindTexture(t.TEXTURE_2D,null)):(this.depth=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.depth),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_COMPONENT16,this.size[0],this.size[1]),t.bindRenderbuffer(t.RENDERBUFFER,null)),t.bindFramebuffer(t.FRAMEBUFFER,this.frameBuffer),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,this.texture.glTexture,0),this.useDepthTexture?t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,this.depth.glTexture,0):t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,this.depth),this.checkStatus(e),t.bindFramebuffer(t.FRAMEBUFFER,null),this.texture.loaded=!0}}),RenderBuffer=Class.extend({init:function(e,t,i){i||(i=e.gl.STATIC_DRAW),this.type=i,this.context=e,this.debug=!1,this.buffers={},this.maxFaceIndex=0;for(var n in t)this.maxFaceIndex=t[n]>this.maxFaceIndex?t[n]:this.maxFaceIndex;this.createFacesBuffer(t)},add:function(e,t,i){if(t.length/i<=this.maxFaceIndex)throw"Buffer too small.";var n=this.context.gl;this.buffers[e]=n.createBuffer(),n.bindBuffer(n.ARRAY_BUFFER,this.buffers[e]),n.bufferData(n.ARRAY_BUFFER,new Float32Array(t),this.type),this.buffers[e].itemSize=i,this.buffers[e].numItems=t.length/this.buffers[e].itemSize,n.bindBuffer(n.ARRAY_BUFFER,null)},update:function(e,t){if(!(e in this.buffers))throw"Unknown buffer.";var i=this.buffers[e];if(t.length/i.itemSize<=this.maxFaceIndex)throw"Buffer too small.";if(t.length/i.itemSize!==i.numItems)throw"Passed buffer does not match the size of the existing buffer.";var n=this.context.gl;n.bindBuffer(n.ARRAY_BUFFER,i),n.bufferData(n.ARRAY_BUFFER,new Float32Array(t),this.type),n.bindBuffer(n.ARRAY_BUFFER,null)},render:function(e){if(e.linked){var t=this.context.gl,i=[];e.requirements.apply(this);for(var n in this.buffers){t.bindBuffer(t.ARRAY_BUFFER,this.buffers[n]);var r=e.getAttribLocation(n);-1!=r&&(t.enableVertexAttribArray(r),i.push(r),t.vertexAttribPointer(r,this.buffers[n].itemSize,t.FLOAT,!1,0,0))}this.drawElements();for(var s=0,a=i.length;a>s;s++)t.disableVertexAttribArray(i[s])}},generateBarycentric:function(){for(var e=new Float32Array(3*this.buffers.position.numItems),t=0;t<e.length;t+=9)e[t+0]=1,e[t+1]=0,e[t+2]=0,e[t+3]=0,e[t+4]=1,e[t+5]=0,e[t+6]=0,e[t+7]=0,e[t+8]=1;this.add("barycentric",e,3)},generateTexCoords:function(){for(var e=new Float32Array(2*this.buffers.position.numItems),t=0;t<e.length;t++)e[t]=0;this.add("texcoord2d0",e,2)},drawElements:function(){},createFacesBuffer:function(e){var t=this.context.gl;this.facesBuffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.facesBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array(e),this.type),this.facesBuffer.itemSize=1,this.facesBuffer.numItems=e.length}}),TrianglesRenderBuffer=RenderBuffer.extend({init:function(e,t,i){this._super(e,t,i)},drawElements:function(){var e=this.context.gl;e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.facesBuffer),e.drawElements(e.TRIANGLES,this.facesBuffer.numItems,e.UNSIGNED_SHORT,0)}}),QuadsRenderBuffer=TrianglesRenderBuffer.extend({init:function(e,t,i){for(var n=[],r=0;r<t.length-3;r++)n.push(t[r]),n.push(t[r+1]),n.push(t[r+2]),n.push(t[r]),n.push(t[r+2]),n.push(t[r+3]);this._super(e,n,i)}}),Texture=Serializable.extend({init:function(e){this.glTexture=!1,this.name=!1,this.size=!1,this.mipmapped=!0,this.clampToEdge=!1,this.loaded=!1,e&&this.create(e)},type:function(){return"Texture"},excluded:function(){return this._super().concat(["glTexture","context","loaded","size"])},create:function(e){this.glTexture=e.gl.createTexture()},clearImage:function(e,t,i){this.glTexture===!1&&this.create(e),i=i||1;var n=e.gl;n.bindTexture(e.gl.TEXTURE_2D,this.glTexture);for(var r=new Uint8Array(i*i*4),s=0;i*i*4>s;s+=4)r[s+0]=t[0],r[s+1]=t[1],r[s+2]=t[2],r[s+3]=t[3];n.texImage2D(n.TEXTURE_2D,0,n.RGBA,i,i,0,n.RGBA,n.UNSIGNED_BYTE,r),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.bindTexture(e.gl.TEXTURE_2D,null),this.size=[i,i],this.loaded=!0},pasteImage:function(e,t,i){if(this.loaded){var n=e.gl;this.bind(e),n.texSubImage2D(n.TEXTURE_2D,0,t[0]*this.size[0],t[1]*this.size[1],n.RGBA,n.UNSIGNED_BYTE,i),this.mipmapped&&n.generateMipmap(n.TEXTURE_2D),this.unbind(e),this.loaded=!0}},setImage:function(e,t){if(this.glTexture===!1&&this.create(e),!this.glTexture)throw"Unable to update texture. glTexture not available.";var i=e.gl;e.gl.bindTexture(e.gl.TEXTURE_2D,this.glTexture);var n=this.resizeToPowerOfTwo(t);this.size=[n.width,n.height],i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,!0),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,n),this.clampToEdge&&(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE)),this.mipmapped?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR_MIPMAP_NEAREST),i.generateMipmap(i.TEXTURE_2D)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST)),e.gl.bindTexture(e.gl.TEXTURE_2D,null),n!=t&&delete n,this.loaded=!0},getImage:function(e){if(!this.glTexture)throw"Unable to get image. glTexture not available.";var t=e.gl,i=new TargetTexture(this,e,!1);i.bind(e);var n=new Uint8Array(this.size[0]*this.size[1]*4);return e.gl.readPixels(0,0,this.size[0],this.size[1],t.RGBA,t.UNSIGNED_BYTE,n),i.unbind(e),n},bind:function(e){this.loaded&&((0!=(this.size[0]&this.size[0]-1)||0!=(this.size[1]&this.size[1]-1))&&console.warn("Binding not power of 2 texture: {0} ({1}x{2})".format(this.name,this.size[0],this.size[1])),e.gl.bindTexture(e.gl.TEXTURE_2D,this.glTexture))},unbind:function(e){this.loaded&&e.gl.bindTexture(e.gl.TEXTURE_2D,null)},resizeToPowerOfTwo:function(e){function t(e){return 0==(e&e-1)}function i(e){return Math.max(Math.min(Math.pow(2,Math.floor(Math.log(e)/Math.log(2))),2048),1)}if(!t(e.width)||!t(e.height)){var n=document.createElement("canvas");n.width=i(e.width),n.height=i(e.height);var r=n.getContext("2d");r.drawImage(e,0,0,e.width,e.height,0,0,n.width,n.height),e=n}return e}}),Material=Serializable.extend({init:function(e,t,i,n){this._super(),this.name="Unnamed",this.shader=e,this.uniforms=t,this.samplers=i,this.descriptor=n},type:function(){return"Material"},bind:function(e,t){this.shader&&(this.shader.use(this.uniforms),e&&this.shader.bindUniforms(e),this.samplers&&0!=this.samplers.length||t&&0!=t.length?this.shader.bindSamplers(t?this.samplers.concat(t):this.samplers):this.shader.context.engine&&this.shader.bindSamplers([this.shader.context.engine.WhiteTextureSampler]))},unbind:function(e){this.shader&&(this.samplers&&0!=this.samplers.length||e&&0!=e.length?this.shader.unbindSamplers(e?this.samplers.concat(e):this.samplers):this.shader.context.engine&&this.shader.unbindSamplers([this.shader.context.engine.WhiteTextureSampler]))},instantiate:function(){var e={};for(var t in this.uniforms)e[t]=this.uniforms[t].clone();var i=[];for(var t in this.samplers)i.push(this.samplers[t].clone());var n=new Material(this.shader,e,i,this.descriptor);return n.name=this.name+" (instance)",n}}),Space=Class.extend({init:function(){},frustumCast:function(){},rayCast:function(){},lineCast:function(){}}),DynamicSpace=Space.extend({init:function(){this.renderers=[],this.colliders=[]},addRenderer:function(e){this.renderers.push(e)},removeRenderer:function(e){for(var t in this.renderers)if(this.renderers[t]===e)return this.renderers.splice(t,1),!0;return!1},addCollider:function(e){this.colliders.push(e)},removeCollider:function(e){for(var t in this.colliders)if(this.colliders[t]===e)return this.colliders.splice(t,1),!0;return!1},frustumCast:function(e,t){for(var i=[],n=0;n<this.renderers.length;n++)this.renderers[n].visible&&this.renderers[n].layer&t&&i.push(this.renderers[n]);return i},rayCast:function(e,t,i){var n=new RayTestResult(e);if(!t)return n;for(var r=0;r<this.colliders.length;r++)this.colliders[r].enabled&&this.colliders[r].node.layer&t&&this.colliders[r].rayTest(e,n,i);return n}}),Renderer=Class.extend({init:function(e){this.matrix=e,this.layer=1,this.visible=!0,this.castShadows=!0,this.receiveShadows=!0,this.transparent=!1,this.localBoundingBox=new BoundingBox,this.localBoundingSphere=new BoundingSphere,this.globalBoundingBox=new BoundingBox,this.globalBoundingSphere=new BoundingSphere,this.cacheMatrix=mat4.create()},render:function(e,t){this.onRender(e,t)},renderGeometry:function(e,t){this.onRenderGeometry(e,t)},getDefaultUniforms:function(e,t){return t||(t={}),"model"in t?mat4.copy(t.model.value,this.matrix):t.model=new UniformMat4(this.matrix),"modelview"in t?mat4.copy(t.modelview.value,e.modelview.top()):t.modelview=new UniformMat4(e.modelview.top()),"modelviewInverse"in t?mat4.invert(t.modelviewInverse.value,e.modelview.top()):t.modelviewInverse=new UniformMat4(mat4.invert(mat4.create(),e.modelview.top())),"projection"in t?mat4.copy(t.projection.value,e.projection.top()):t.projection=new UniformMat4(e.projection.top()),"receiveShadows"in t?t.receiveShadows.value=this.receiveShadows?1:0:t.receiveShadows=new UniformInt(this.receiveShadows?1:0),e.camera&&("view"in t?mat4.copy(t.view.value,e.camera.viewMatrix):t.view=new UniformMat4(e.camera.viewMatrix),"viewInverse"in t?mat4.copy(t.viewInverse.value,e.camera.viewInverseMatrix):t.viewInverse=new UniformMat4(e.camera.viewInverseMatrix),e.camera.near&&("zNear"in t?t.zNear.value=e.camera.near:t.zNear=new UniformFloat(e.camera.near)),e.camera.far&&("zFar"in t?t.zFar.value=e.camera.far:t.zFar=new UniformFloat(e.camera.far))),e.light&&e.light.uniforms&&(t.lightDirection=e.light.uniforms.lightDirection,t.lightColor=e.light.uniforms.lightColor,t.lightIntensity=e.light.uniforms.lightIntensity),e.shadow&&(t.linearDepthConstant=e.shadow.linearDepthConstant,t.lightView=e.shadow.lightView,t.lightProjection=e.shadow.lightProjection,t.shadowIntensity=e.shadow.shadowIntensity),t},getGlobalSamplers:function(e){var t=[];return e.shadow&&t.push(e.shadow.shadow0),t},setMatrix:function(e){this.matrix=e,this.updateGlobalBoundingVolumes()},updateGlobalBoundingVolumes:function(){this.globalBoundingBox=this.localBoundingBox.transform(this.matrix),this.globalBoundingSphere=this.localBoundingSphere.transform(this.matrix)},onRender:function(){},onRenderGeometry:function(){}}),PrimitiveRenderer=Renderer.extend({init:function(e,t){this._super(e),this.material=t}}),MeshRenderer=Renderer.extend({init:function(e,t,i){this._super(t),this.mesh=i,this.buffers=[];for(var n in this.mesh.submeshes){var r=this.mesh.submeshes[n],s=new TrianglesRenderBuffer(e,r.faces);s.add("position",r.positions,3);for(var a in r.texCoords1D)s.add("texcoord1d"+a,r.texCoords1D[a],1);for(var o in r.texCoords2D)s.add("texcoord2d"+o,r.texCoords2D[o],2);for(var h in r.texCoords3D)s.add("texcoord3d"+h,r.texCoords3D[h],3);r.normals&&s.add("normal",r.normals,3),r.tangents&&s.add("tangent",r.tangents,3),r.bitangents&&s.add("bitangent",r.bitangents,3),this.buffers.push(s)}},onRender:function(e){var t=this.getDefaultUniforms(e);for(var i in this.mesh.submeshes){var n=this.mesh.submeshes[i],r=this.mesh.getMaterial(n.materialIndex);r&&(r.bind(t),this.buffers[i].render(r.shader),r.unbind())}},onRenderGeometry:function(e,t){t.bindUniforms(this.getDefaultUniforms(e));for(var i in this.buffers)this.buffers[i].render(t)}}),SubmeshRenderer=Renderer.extend({init:function(e,t,i,n){this._super(t),this.submesh=i,this.material=n,this.buffer=[],this.localBoundingBox=this.submesh.boundingBox,this.localBoundingSphere=this.submesh.boundingSphere,this.updateGlobalBoundingVolumes(),this.buffer=new TrianglesRenderBuffer(e,i.faces),this.buffer.add("position",i.positions,3);for(var r in i.texCoords1D)i.positions.length/3==i.texCoords1D[r].length?this.buffer.add("texcoord1d"+r,i.texCoords1D[r],1):console.warn("Wrong number of texture coordinates 1. Must be the same as positions.");for(var s in i.texCoords2D)i.positions.length/3==i.texCoords2D[s].length/2?this.buffer.add("texcoord2d"+s,i.texCoords2D[s],2):console.warn("Wrong number of texture coordinates 2 ("+i.texCoords2D[s].length+"). Must be the same as positions ("+i.positions.length+").");for(var a in i.texCoords3D)i.positions.length==i.texCoords3D[a].length?this.buffer.add("texcoord3d"+a,i.texCoords3D[a],3):console.warn("Wrong number of texture coordinates 3. Must be the same as positions.");i.normals&&(i.positions.length!=i.normals.length?console.warn("Wrong number of normals. Must be the same as positions."):this.buffer.add("normal",i.normals,3)),i.tangents&&(i.positions.length!=i.tangents.length?console.warn("Wrong number of tangents. Must be the same as positions."):this.buffer.add("tangent",i.tangents,3)),i.bitangents&&(i.positions.length!=i.bitangents.length?console.warn("Wrong number of bitangents. Must be the same as positions."):this.buffer.add("bitangent",i.bitangents,3)),n.uniforms.diffuse||(n.uniforms.diffuse=new UniformColor(new Color(1,1,1,1))),n.uniforms.ambient||(n.uniforms.ambient=new UniformColor(new Color(.2,.2,.2,1))),n.uniforms.specularStrength||(n.uniforms.specularStrength=new UniformFloat(0)),n.uniforms.specularPower||(n.uniforms.specularPower=new UniformInt(8)),this.transparent=n.shader.requirements.transparent||n.uniforms.diffuse&&n.uniforms.diffuse.value[3]<1||n.uniforms.ambient&&n.uniforms.ambient.value[3]<1,this.failed=!1
  },onRender:function(){this.buffer.render(this.material.shader)},onRenderGeometry:function(e,t){this._cache?this.getDefaultUniforms(e,this._cache):this._cache=this.getDefaultUniforms(e),t.bindUniforms(this._cache),this.buffer.render(t)}}),FontRenderer=SubmeshRenderer.extend({init:function(e,t,i,n){this._super(e,t,i,n),this.fontData=!1},onRender:function(e){var t=this.getGlobalSamplers(e),i=this.getDefaultUniforms(e);i.page=this.submesh.page,this.material.bind(i,this.material.samplers);try{this.buffer.render(this.material.shader)}catch(n){if(this.failed)return;this.failed=!0,console.warn("Failed to render buffer: ",this.buffer),console.warn("material: ",this.material.name,this.material),console.warn("positions: ",this.submesh.positions.length),console.warn("normals: ",this.submesh.normals.length),console.warn("texcoords: ",this.submesh.texCoords2D),console.warn("faces: ",this.submesh.faces.length),console.warn(n)}this.material.unbind(t)}}),CubeRenderer=PrimitiveRenderer.extend({init:function(e,t,i,n){this._super(t,n),this.size=i;var r=this.size/2,s=[-r,-r,r,r,-r,r,r,-r,-r,-r,-r,-r,-r,r,r,r,r,r,r,r,-r,-r,r,-r],a=[0,1,2,3,4,5,6,7,0,1,5,4,1,2,6,5,2,3,7,6,3,0,0,7];this.renderBuffer=new QuadsRenderBuffer(e,a),this.renderBuffer.add("position",s,3)},onRender:function(e){this.material.bind({modelview:new UniformMat4(e.modelview.top()),projection:new UniformMat4(e.projection.top())}),this.renderBuffer.render(this.material.shader),this.material.unbind()}}),FontData=Class.extend({init:function(e){this.xmlData=e;var t=$(e).find("font common");this.width=parseInt(t.attr("scaleW")),this.height=parseInt(t.attr("scaleH")),this.size=vec2.fromValues(this.width,this.height),this.lineHeight=parseInt(t.attr("lineHeight")),this.baseline=parseInt(t.attr("base")),this.characters={},this.kernings={};var i=this;$(e).find("font chars char").each(function(){var e=parseFloat($(this).attr("x")),t=parseFloat($(this).attr("y")),n=parseInt($(this).attr("width")),r=parseInt($(this).attr("height")),s=parseFloat($(this).attr("xoffset")),a=parseFloat($(this).attr("yoffset"));i.characters[$(this).attr("id")]={position:vec2.fromValues(e,t),size:vec2.fromValues(n,r),offset:vec2.fromValues(s,a),normalizedPosition:vec2.fromValues(e/i.width,1-t/i.height-r/i.height),normalizedSize:vec2.fromValues(-n/i.width,-r/i.height),xadvance:parseInt($(this).attr("xadvance")),page:parseInt($(this).attr("page"))}}),$(e).find("font kernings kerning").each(function(){i.kernings[$(this).attr("first")]||(i.kernings[$(this).attr("first")]={}),i.kernings[$(this).attr("first")][$(this).attr("second")]=parseInt($(this).attr("amount"))})}}),Font=Class.extend({init:function(e,t){this.data=!1,this.materialSource=e,this.descriptor=t}}),DataParserTypes={NODE_ROOT:4096,NODE_STRING:4097,NODE_MATRIX3X3:4098,NODE_MATRIX4X4:4099,NODE_MATERIALS:8192,NODE_MATERIAL:8193,NODE_COLOR_AMBIENT:8194,NODE_COLOR_DIFFUSE:8195,NODE_COLOR_SPECULAR:8196,NODE_COLOR_EMISSIVE:8197,NODE_TWOSIDED:8198,NODE_SHININESS:8199,NODE_SHININESS_STRENGTH:8200,NODE_TEXTURES_AMBIENT:8272,NODE_TEXTURES_DIFFUSE:8273,NODE_TEXTURES_SPECULAR:8274,NODE_TEXTURES_EMISSIVE:8275,NODE_TEXTURES_NORMALS:8276,NODE_TEXTURES_HEIGHT:8277,NODE_TEXTURES_SHININESS:8278,NODE_TEXTURES_OPACITY:8279,NODE_TEXTURES_DISPLACEMENT:8280,NODE_TEXTURES_LIGHTMAP:8281,NODE_TEXTURES_REFLECTION:8282,NODE_TEXTURE:8448,NODE_TEXTURE_SCALE:8449,NODE_SHADER_NAME:8704,NODE_GEOMETRY:12288,NODE_MESH:12544,NODE_MATERIAL_REFERENCE:12545,NODE_VERTICES:12546,NODE_NORMALS:12547,NODE_TANGENTS:12548,NODE_BITANGENTS:12549,NODE_TEXTURE_COORDINATES:12550,NODE_FACES:12551,NODE_SCENE:16384,NODE_GROUP:16385,NODE_MESH_REFERENCE:16386,NODE_TRANSFORM_POSITION:16387,NODE_TRANSFORM_ROTATION:16388,NODE_TRANSFORM_SCALE:16389,NODE_GROUP_ID:16390,NODE_COLLISION:20480,NODE_COLLISION_NODE:20481,NODE_COLLISION_AABB_CENTER:20482,NODE_COLLISION_AABB_EXTENTS:20483,NODE_COLLISION_FACE_LIST:20484,NODE_FACE_LIST_NODE_ID:20496,NODE_FACE_LIST_MESH_REFERENCE:20497,NODE_FACE_LIST_INDICES:20498,getName:function(e){for(var t in DataParserTypes)if(DataParserTypes[t]===e)return t;return!1}},DataParserNode=function(e,t,i){this.id=e,this.length=t,this.position=i,this.HEADER_LENGTH=8,this.end=function(){return this.position+this.HEADER_LENGTH+this.length}},DataParserResult=Class.extend({init:function(){this.data={meshes:[],materials:[],hierarchy:!1,collision:!1,hierarchyNodesByID:{}}},getData:function(){return this.data},linkReferences:function(){for(var e in this.data.meshes)-1!=this.data.meshes[e].material&&this.data.meshes[e].material in this.data.materials&&(this.data.meshes[e].material=this.data.materials[this.data.meshes[e].material]);if(this.data.hierarchy!==!1){var t=this,i=function(e){for(var n in e.meshes)e.meshes[n]>=0&&e.meshes[n]in t.data.meshes&&(e.meshes[n]=t.data.meshes[e.meshes[n]]);for(var r in e.children)i(e.children[r])};i(this.data.hierarchy)}},createGroup:function(){return{name:"",id:!1,parent:!1,children:[],meshes:[],position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0,w:0},scale:{x:0,y:0,z:0},transform:!1}},mapGroupID:function(e){this.data.hierarchyNodesByID[e.id]=e},setRoot:function(e){this.data.hierarchy=e},createMaterialTexture:function(){return{path:!1,scale:{u:1,v:1,w:1}}},createMaterial:function(){return{name:"",color:{ambient:!1,diffuse:!1,specular:!1,emissive:!1},twosided:!1,shininess:0,shininess_strength:0,shader:!1,textures:{ambient:[],diffuse:[],specular:[],emissive:[],normal:[],height:[],shininess:[],opacity:[],displacement:[],lightmap:[],reflection:[]}}},addMaterial:function(e){this.data.materials.push(e)},getMaterial:function(e){return e>=0&&e<this.data.materials.length?this.data.materials[e]:!1},createMesh:function(e){for(var t={index:-1,material:-1,indices:[],vertices:[]},i=0;e>i;i++)t.vertices.push(this.createVertex());return t},createVertex:function(){return{position:{x:0,y:0,z:0},normal:{x:0,y:0,z:0},texCoord:[],tangent:{x:0,y:0,z:0},bitangent:{x:0,y:0,z:0}}},addMesh:function(e){this.data.meshes.push(e),e.index=this.data.meshes.length-1},createCollisionTreeNode:function(){return{parent:!1,children:[],center:{x:0,y:0,z:0},extents:{x:0,y:0,z:0},faces:!1}},addFaceList:function(e,t,i,n){return 0>t||0>i||0==n.length?!1:(e.faces===!1&&(e.faces={}),t in e.faces||(e.faces[t]={}),i in e.faces[t]||(e.faces[t][i]=[]),e.faces[t][i]=e.faces[t][i].concat(n),!0)},setCollisionTreeRoot:function(e){this.data.collision=e}}),DataParser=Class.extend({init:function(e,t,i,n,r){this.VERSION=1,this.view=new jDataView(e),this.onComplete=t,this.onProgress=n,this.onError=i,this.userdata=r,this.result=new DataParserResult,this.errors=[],this.stack=[],this.linkReferences=!0,this.flipX=!1,this.warnOnUnknownChunks=!0},parse:function(){for(this.push(!1,this.parseHeader);!this.completed();)if(!this.step())return $.isFunction(this.onError)&&this.onError(this.errors,this.userdata),!1;return this.linkReferences&&this.result.linkReferences(),$.isFunction(this.onComplete)&&this.onComplete(this.result.getData(),this.userdata),!0},error:function(e){return this.errors.push(e),!1},errorExpect:function(e,t){return this.error("Expected at least "+e+" byte"+(e>1?"s":"")+' for "'+t+'"')},completed:function(){return this.view.tell()==this.view.byteLength?!0:!1},step:function(){var e=this.getCurrentCall();if(e){var t=e(this.getCurrentNode());return $.isFunction(this.onProgress)&&this.onProgress(this.view.tell()/this.view.byteLength*100,this.userdata),t}return!1},push:function(e,t){this.stack.push({node:e,call:ClassCallback(this,t)})},pop:function(){this.stack.pop()},getCurrentNode:function(){return this.stack.length>0?this.stack[this.stack.length-1].node:!1},getCurrentCall:function(){return this.stack.length>0?this.stack[this.stack.length-1].call:!1},hasDataFor:function(e){return this.view.byteLength<this.view.tell()+e?!1:!0},hasDataForNode:function(e){return this.view.byteLength<e.position+e.length+8?!1:!0},getUint32:function(){return this.view.getUint32(this.view.tell(),!0)},getFloat32:function(){return this.view.getFloat32(this.view.tell(),!0)},getMatrix4x4:function(){for(var e=[],t=0;4>t;t++)e.push([this.getFloat32(),this.getFloat32(),this.getFloat32(),this.getFloat32()]);return e},getColor:function(){return{r:this.view.getFloat32(this.view.tell(),!0),g:this.view.getFloat32(this.view.tell(),!0),b:this.view.getFloat32(this.view.tell(),!0),a:this.view.getFloat32(this.view.tell(),!0)}},parseHeader:function(){if(!this.view)return this.error("No data to parse");if(!this.parseSignature())return!1;var e=this.parseNodeHeader();return e===!1?!1:e.id!==DataParserTypes.NODE_ROOT?this.error("Root node type is incorrect"):(this.push(e,this.parseRoot),!0)},parseSignature:function(){if(!this.hasDataFor(12))return this.error("Not enough data for 3DTech DATA format header");var e=this.view.getString(10);if("3DTECHDATA"!=e)return this.error("The data is not in 3DTech DATA format");var t=this.view.getInt16(this.view.tell(),!0);return t!=this.VERSION?this.error("Incompatible version"):this.hasDataFor(8)?!0:this.error("Could not find root node")},parseNodeHeader:function(){if(!this.hasDataFor(8))return this.error("Not enough data for parsing node header");var e=this.view.tell(),t=this.getUint32(),i=this.getUint32();return new DataParserNode(t,i,e)},skipNode:function(e){this.warnOnUnknownChunks&&console.warn("DataParser: skipping node ",DataParserTypes.getName(e.id)),this.view.seek(this.view.tell()+e.length)},parseMaterial:function(e){for(var t=this.result.createMaterial();this.view.tell()<e.end();){var i=this.parseNodeHeader();switch(i.id){case DataParserTypes.NODE_STRING:t.name=this.view.getString(i.length);break;case DataParserTypes.NODE_SHADER_NAME:t.shader=this.view.getString(i.length);break;case DataParserTypes.NODE_COLOR_AMBIENT:if(16!=i.length)return this.error("Ambient color corrupted");t.color.ambient=this.getColor();break;case DataParserTypes.NODE_COLOR_DIFFUSE:if(16!=i.length)return this.error("Diffuse color corrupted");t.color.diffuse=this.getColor();break;case DataParserTypes.NODE_COLOR_SPECULAR:if(16!=i.length)return this.error("Specular color corrupted");t.color.specular=this.getColor();break;case DataParserTypes.NODE_COLOR_EMISSIVE:if(16!=i.length)return this.error("Emissive color corrupted");t.color.emissive=this.getColor();break;case DataParserTypes.NODE_TWOSIDED:if(i.length<1)return this.errorExpect(1,"material.twosided");var n=this.view.getChar();t.twosided=255==n?!0:!1;break;case DataParserTypes.NODE_SHININESS:if(i.length<4)return this.errorExpect(4,"material.shininess");t.shininess=this.getFloat32();break;case DataParserTypes.NODE_SHININESS_STRENGTH:if(i.length<4)return this.errorExpect(4,"material.shininess_strength");t.shininess_strength=this.getFloat32();break;case DataParserTypes.NODE_TEXTURES_AMBIENT:this.parseMaterialTextures(i,t.textures.ambient);break;case DataParserTypes.NODE_TEXTURES_DIFFUSE:this.parseMaterialTextures(i,t.textures.diffuse);break;case DataParserTypes.NODE_TEXTURES_SPECULAR:this.parseMaterialTextures(i,t.textures.specular);break;case DataParserTypes.NODE_TEXTURES_EMISSIVE:this.parseMaterialTextures(i,t.textures.emissive);break;case DataParserTypes.NODE_TEXTURES_NORMALS:this.parseMaterialTextures(i,t.textures.normal);break;case DataParserTypes.NODE_TEXTURES_HEIGHT:this.parseMaterialTextures(i,t.textures.height);break;case DataParserTypes.NODE_TEXTURES_SHININESS:this.parseMaterialTextures(i,t.textures.shininess);break;case DataParserTypes.NODE_TEXTURES_OPACITY:this.parseMaterialTextures(i,t.textures.opacity);break;case DataParserTypes.NODE_TEXTURES_DISPLACEMENT:this.parseMaterialTextures(i,t.textures.displacement);break;case DataParserTypes.NODE_TEXTURES_LIGHTMAP:this.parseMaterialTextures(i,t.textures.lightmap);break;case DataParserTypes.NODE_TEXTURES_REFLECTION:this.parseMaterialTextures(i,t.textures.reflection);break;default:this.skipNode(i)}}return this.result.addMaterial(t),!0},parseMaterialTextures:function(e,t){for(;this.view.tell()<e.end();){var i=this.parseNodeHeader();if(i.id==DataParserTypes.NODE_TEXTURE){for(var n=this.result.createMaterialTexture();this.view.tell()<i.end();){var r=this.parseNodeHeader();switch(r.id){case DataParserTypes.NODE_STRING:n.path=this.view.getString(r.length);break;case DataParserTypes.NODE_TEXTURE_SCALE:if(12!=r.length)return this.error("Texture scale is corrupted");n.scale.u=this.getFloat32(),n.scale.v=this.getFloat32(),n.scale.w=this.getFloat32();break;default:this.skipNode(r)}}n.path!==!1&&t.push(n)}else this.skipNode(i)}return!0},parseMaterials:function(e){if(!this.hasDataForNode(e))return this.error("Not enough data for node '"+DataParserTypes.getName(e.id)+"'");for(;this.view.tell()<e.end();){var t=this.parseNodeHeader();t.id==DataParserTypes.NODE_MATERIAL?this.parseMaterial(t):this.skipNode(t)}return this.pop(),!0},parseGeometry:function(e){if(!this.hasDataForNode(e))return this.error("Not enough data for node '"+DataParserTypes.getName(e.id)+"'");if(this.view.tell()>=e.end())return this.pop(),!0;var t=this.parseNodeHeader();if(t.id==DataParserTypes.NODE_MESH){if(!this.hasDataForNode(t))return this.error("Not enough data for node '"+DataParserTypes.getName(t.id)+"'");this.push(t,this.parseMesh)}else this.skipNode(t);return!0},parseMesh:function(e){var t=this.getUint32(),i=this.result.createMesh(t),n=0,r=[1,1,1],s=[1,1,1];for(this.flipX&&(s[0]=-1);this.view.tell()<e.end();){var a=this.parseNodeHeader();if(!this.hasDataForNode(a))return this.error("Not enough data for node '"+DataParserTypes.getName(a.id)+"'");switch(a.id){case DataParserTypes.NODE_MATERIAL_REFERENCE:if(a.length<4)return this.errorExpect(4,"mesh.material_reference");i.material=this.getUint32();break;case DataParserTypes.NODE_VERTICES:if(!this.parseVertices(a,t,i.vertices,"position",s))return!1;break;case DataParserTypes.NODE_NORMALS:if(!this.parseVertices(a,t,i.vertices,"normal",r))return!1;break;case DataParserTypes.NODE_TANGENTS:if(!this.parseVertices(a,t,i.vertices,"tangent",r))return!1;break;case DataParserTypes.NODE_BITANGENTS:if(!this.parseVertices(a,t,i.vertices,"bitangent",r))return!1;break;case DataParserTypes.NODE_TEXTURE_COORDINATES:if(a.length<4)return this.errorExpect(4,"mesh texture coordinates component count");var o=this.getUint32();if(0==o||o>3)return this.error("Unsupported number of texture coordinate components: "+o);if(a.length-4!=o*t*4)return this.error("Texture coordinate set "+n+" is corrupted");for(var h=["x","y","z"],c=0;t>c;c++){for(var u={},l=0;o>l;l++)u[h[l]]=this.getFloat32();i.vertices[c].texCoord.push(u)}n++;break;case DataParserTypes.NODE_FACES:if(!this.parseFaces(a,i.indices))return!1;break;default:this.skipNode(a)}}return this.result.addMesh(i),this.pop(),!0},parseVertices:function(e,t,i,n,r){if(e.length!=12*t)return this.error("Node "+DataParserTypes.getName(e.id)+" is corrupted");for(var s=0;t>s;s++)i[s][n].x=r[0]*this.getFloat32(),i[s][n].y=r[1]*this.getFloat32(),i[s][n].z=r[2]*this.getFloat32();return!0},parseFaces:function(e,t){if(e.length<4)return this.errorExpect(4,"faces.num_triangles");var i=this.getUint32();if(e.length-4!=12*i)return this.error("Faces list is corrupted");for(var n=0;i>n;n++)t.push(this.getUint32()),t.push(this.getUint32()),t.push(this.getUint32());return!0},parseScene:function(e){if(!this.hasDataForNode(e))return this.error("Not enough data for node '"+DataParserTypes.getName(e.id)+"'");for(;this.view.tell()<e.end();){var t=this.parseNodeHeader();if(t.id==DataParserTypes.NODE_GROUP){if(!this.parseGroup(t,!1))return!1}else this.skipNode(t)}return this.pop(),!0},parseGroup:function(e,t){if(!this.hasDataForNode(e))return this.error("Not enough data for node '"+DataParserTypes.getName(e.id)+"'");var i=this.result.createGroup();for(t===!1?this.result.setRoot(i):(t.children.push(i),i.parent=t);this.view.tell()<e.end();){var n=this.parseNodeHeader();if(!this.hasDataForNode(n))return this.error("Not enough data for node '"+DataParserTypes.getName(n.id)+"'");switch(n.id){case DataParserTypes.NODE_GROUP_ID:if(n.length<4)return this.error("Group ID is corrupted");i.id=this.getUint32(),this.result.mapGroupID(i);break;case DataParserTypes.NODE_STRING:i.name=this.view.getString(n.length);break;case DataParserTypes.NODE_TRANSFORM_POSITION:if(12!=n.length)return this.error("Group position is corrupted");i.position.x=this.getFloat32(),i.position.y=this.getFloat32(),i.position.z=this.getFloat32();break;case DataParserTypes.NODE_TRANSFORM_ROTATION:if(16!=n.length)return this.error("Group rotation is corrupted");i.rotation.x=this.getFloat32(),i.rotation.y=this.getFloat32(),i.rotation.z=this.getFloat32(),i.rotation.w=this.getFloat32();break;case DataParserTypes.NODE_TRANSFORM_SCALE:if(12!=n.length)return this.error("Group scale is corrupted");i.scale.x=this.getFloat32(),i.scale.y=this.getFloat32(),i.scale.z=this.getFloat32();break;case DataParserTypes.NODE_MATRIX4X4:if(64!=n.length)return this.error("Group transformation matrix is corrupted");i.transform=this.getMatrix4x4();break;case DataParserTypes.NODE_MESH_REFERENCE:if(n.length<4)return this.error("Group mesh reference is corrupted");i.meshes.push(this.getUint32());break;case DataParserTypes.NODE_GROUP:this.parseGroup(n,i);break;default:this.skipNode(n)}}return!0},parseCollision:function(e){if(!this.hasDataForNode(e))return this.error("Not enough data for node '"+DataParserTypes.getName(e.id)+"'");for(;this.view.tell()<e.end();){var t=this.parseNodeHeader();if(t.id==DataParserTypes.NODE_COLLISION_NODE){if(!this.parseCollisionNode(t,!1))return!1}else this.skipNode(t)}return this.pop(),!0},parseCollisionNode:function(e,t){if(!this.hasDataForNode(e))return this.error("Not enough data for node '"+DataParserTypes.getName(e.id)+"'");var i=this.result.createCollisionTreeNode();for(t===!1?this.result.setCollisionTreeRoot(i):(t.children.push(i),i.parent=t);this.view.tell()<e.end();){var n=this.parseNodeHeader();if(!this.hasDataForNode(n))return this.error("Not enough data for node '"+DataParserTypes.getName(n.id)+"'");switch(n.id){case DataParserTypes.NODE_COLLISION_AABB_CENTER:if(12!=n.length)return this.error("Collision node center is corrupted");i.center.x=this.getFloat32(),i.center.y=this.getFloat32(),i.center.z=this.getFloat32();break;case DataParserTypes.NODE_COLLISION_AABB_EXTENTS:if(12!=n.length)return this.error("Collision node extents are corrupted");i.extents.x=this.getFloat32(),i.extents.y=this.getFloat32(),i.extents.z=this.getFloat32();break;case DataParserTypes.NODE_COLLISION_NODE:this.parseCollisionNode(n,i);break;case DataParserTypes.NODE_COLLISION_FACE_LIST:this.parseCollisionFaceList(n,i);break;default:this.skipNode(n)}}return!0},parseCollisionFaceList:function(e,t){if(!this.hasDataForNode(e))return this.error("Not enough data for node '"+DataParserTypes.getName(e.id)+"'");for(var i=-1,n=-1,r=[];this.view.tell()<e.end();){var s=this.parseNodeHeader();if(!this.hasDataForNode(s))return this.error("Not enough data for node '"+DataParserTypes.getName(s.id)+"'");switch(s.id){case DataParserTypes.NODE_FACE_LIST_NODE_ID:if(4!=s.length)return this.error("Face list node ID is corrupted");i=this.getUint32();break;case DataParserTypes.NODE_FACE_LIST_MESH_REFERENCE:if(4!=s.length)return this.error("Face list mesh ID is corrupted");n=this.getUint32();break;case DataParserTypes.NODE_FACE_LIST_INDICES:for(;this.view.tell()<s.end();)r.push(this.getUint32());break;default:this.skipNode(s)}}return this.result.addFaceList(t,i,n,r)},parseRoot:function(e){if(!this.hasDataForNode(e))return this.error("Not enough data for node '"+DataParserTypes.getName(e.id)+"'");if(this.view.tell()>=e.end())return!0;var t=this.parseNodeHeader();switch(t.id){case DataParserTypes.NODE_MATERIALS:this.push(t,this.parseMaterials);break;case DataParserTypes.NODE_GEOMETRY:this.push(t,this.parseGeometry);break;case DataParserTypes.NODE_SCENE:this.push(t,this.parseScene);break;case DataParserTypes.NODE_COLLISION:this.push(t,this.parseCollision);break;default:this.skipNode(t)}return!0}}),ThreadedDataParser=DataParser.extend({init:function(e,t,i,n,r){this._super(e,t,i,n,r),this.timer=!1,this.inverval=10},parse:function(){return this.push(!1,this.parseHeader),this.timer=setTimeout(ClassCallback(this,this.threadStep),this.inverval),!0},threadStep:function(){return this.completed()?(this.linkReferences&&this.result.linkReferences(),void($.isFunction(this.onComplete)&&this.onComplete(this.result.getData(),this.userdata))):this.step()?void(this.timer=setTimeout(ClassCallback(this,this.threadStep),this.inverval)):void(this.onError&&"function"==typeof this.onError&&this.onError(this.errors,this.userdata))}}),ModelLoader=Class.extend({init:function(e,t,i,n){this.descriptor=t,this.shadersManager=i,this.texturesManager=n,this.defaultTexture=!1,this.defaultSampler=!1,this.nodesByID={},this.submeshesByID={},this.submeshes=[]},createDefaultTextureSampler:function(e){this.defaultTexture||(this.defaultTexture=new Texture(e),this.defaultTexture.clearImage(e,[255,255,255,255]),this.defaultSampler=new Sampler("diffuse0",this.defaultTexture))},load:function(e,t){e.name=t.hierarchy.name,this.loadMaterials(t.materials),this.loadSubmeshes(t.meshes),this.loadNode(e,t.hierarchy),this.loadCollision(e,t)},loadMaterials:function(e){for(var t=0;t<e.length;t++){var i=e[t];i.instance=new Material,this.loadMaterial(i.instance,i)}},loadSubmeshes:function(e){for(var t=0;t<e.length;t++){var i=new Submesh;this.loadSubmesh(i,e[t]),this.submeshesByID[e[t].index]={submesh:i,material:e[t].material.instance}}},loadNode:function(e,t){e.localCollisionID=t.id,this.nodesByID[e.localCollisionID]=e,this.loadTransform(e.transform,t.transform),this.loadMesh(e,t.meshes);for(var i in t.children){var n=new Node(t.children[i].name);this.loadNode(n,t.children[i]),e.addNode(n)}},loadMesh:function(e,t){if(t&&0!=t.length){var i=new Mesh;for(var n in t)if(t[n].index in this.submeshesByID){var r=this.submeshesByID[t[n].index];i.addSubmesh(r.submesh,r.material)}e.addComponent(new MeshComponent(i)),e.addComponent(new MeshRendererComponent)}},loadSubmesh:function(e,t){if(e.faces=t.indices,0!=t.vertices.length){var i=t.vertices[0];if(e.positions=this.loadSubmeshBuffer("position",t.vertices,["x","y","z"]),i.normal&&(e.normals=this.loadSubmeshBuffer("normal",t.vertices,["x","y","z"])),i.tangent&&(e.tangents=this.loadSubmeshBuffer("tangent",t.vertices,["x","y","z"])),i.bitangent&&(e.bitangents=this.loadSubmeshBuffer("bitangent",t.vertices,["x","y","z"])),i.texCoord)for(var n in i.texCoord)e.texCoords2D.push(this.loadSubmeshIndexedBuffer("texCoord",t.vertices,["x","y"],n));e.recalculateBounds()}},loadSubmeshBuffer:function(e,t,i){buffer=[];for(var n in t){vertex=t[n];for(var n in i){var r=i[n];buffer.push(vertex[e][r])}}return buffer},loadSubmeshIndexedBuffer:function(e,t,i,n){buffer=[];for(var r in t){vertex=t[r];for(var r in i){var s=i[r];buffer.push(vertex[e][n][s])}}return buffer},loadMaterial:function(e,t){e.name=t.name,e.shader=this.shadersManager.addSource(t.shader),e.uniforms={},this.loadUniforms(e.uniforms,t);for(var i in t.textures)for(var n=t.textures[i],r=0;r<n.length;r++){var s=new TextureDescriptor(n[r].path);s.parentDescriptor=this.descriptor;var a=this.texturesManager.addDescriptor(s);e.samplers||(e.samplers=[]),e.samplers.push(new Sampler(i+r,a)),"normal"==i&&(e.shader=this.shadersManager.addSource("normalmapped"))}e.samplers||"diffuse"!=t.shader.toLowerCase()||(e.samplers=[],this.createDefaultTextureSampler(this.texturesManager.context),e.samplers.push(this.defaultSampler))},getModelDirectory:function(){var e=this.descriptor.source,t=e.lastIndexOf("/"),i=e.substr(0,t);return i},getRelativePath:function(e){var t=e.lastIndexOf("/");return e.substr(t+1,e.length-t-1)},loadUniforms:function(e,t){e.ambient=new UniformColor(t.color.ambient?t.color.ambient:new Color(.2,.2,.2,1)),e.diffuse=new UniformColor(t.color.diffuse?t.color.diffuse:new Color(1,1,1,1)),t.color.emissive&&(e.emissive=new UniformColor(t.color.emissive)),t.color.specular&&(e.specular=new UniformColor(t.color.specular)),e.twosided=new UniformInt(t.twosided+0)},loadTransform:function(e,t){e.relative[0]=t[0][0],e.relative[4]=t[0][1],e.relative[8]=t[0][2],e.relative[12]=t[0][3],e.relative[1]=t[1][0],e.relative[5]=t[1][1],e.relative[9]=t[1][2],e.relative[13]=t[1][3],e.relative[2]=t[2][0],e.relative[6]=t[2][1],e.relative[10]=t[2][2],e.relative[14]=t[2][3],e.relative[3]=t[3][0],e.relative[7]=t[3][1],e.relative[11]=t[3][2],e.relative[15]=t[3][3]},loadCollisionNodeParameters:function(e,t){var i=new CollisionOctreeNode([e.center.x,e.center.y,e.center.z],2*e.extents.x,t);return e.faces&&(i.faces=e.faces),i},loadCollisionNodeSubnodes:function(e,t,i){if(0!=t.children.length){e.subnodes=[];for(var n=0;8>n;n++){var r=this.loadCollisionNodeParameters(t.children[n],e);e.subnodes.push(r),this.loadCollisionNodeSubnodes(r,t.children[n],i)}}},loadCollision:function(e,t){if(t.collision!==!1){var i=e.addComponent(new LargeMeshCollider);i.tree=this.loadCollisionNodeParameters(t.collision,!1),i.tree.nodes=this.nodesByID,i.tree.submeshes={};for(var n in this.submeshesByID)i.tree.submeshes[n]=this.submeshesByID[n].submesh;this.loadCollisionNodeSubnodes(i.tree,t.collision,t)}}}),Manager=Class.extend({init:function(e){var t=this;this.path="",e&&(this.path=e),this.path.length>0&&"/"!=this.path.slice(-1)&&(this.path+="/"),this.queue=[],this.loading=[],this.cache={},this.cacheSize=0,this.callbacks=[],this.progressCallbacks=[],this.sourceCallback=function(e){return t.path+e},this.descriptorCallback=function(e){return e},this.onAddToQueue=function(){},this.onLoaded=function(){}},getTotalItems:function(){return this.queue.length+this.loading.length+this.cacheSize},getWaitingItems:function(){return this.queue.length+this.loading.length},getProgress:function(){return 0==this.getTotalItems()?1:1-this.getWaitingItems()/this.getTotalItems()},addDescriptor:function(e){var t=this.cache[e.serialize(["id"])];return t?t:(t=this.getLoadingResource(e))?t:(this.onAddToQueue(e),t=this.createResource(e),this.queue.push([e,e.serialize(["id"]),t]),t)},getLoadingResource:function(e){var t=e.serialize(["id"]);for(var i in this.loading)if(this.loading[i][1]==t)return this.loading[i][2];for(var n in this.queue)if(this.queue[n][1]==t)return this.queue[n][2];return null},removeFromCache:function(e){delete this.cache[e],this.cacheSize--},cleanCache:function(){this.cache={},this.cacheSize=0},load:function(e,t){return t&&this.progressCallbacks.push(t),e&&(this.callbacks.push(e),this.callbacks.length>1)?void(0==this.queue.length&&this.callDoneCallbacks()):void this.keepLoading()},keepLoading:function(){for(var e in this.progressCallbacks)this.progressCallbacks[e](this.getProgress());if(0==this.queue.length)return void this.callDoneCallbacks();var t=this,i=this.queue.shift();this.loading.push(i),this.loadResource(i[0],i[2],function(e,i){t.cache[e.serialize(["id"])]=i,t.cacheSize++,t.removeLoadedResource(e),t.onLoaded(e),t.keepLoading()},function(e){console.warn("Failed to load resource with descriptor: ",e.serialize(["id"])),t.removeLoadedResource(e),t.onLoaded(e),e.getFullPath&&console.warn("Full path: ",e.getFullPath()),t.keepLoading()})},removeLoadedResource:function(e){for(var t in this.loading)if(this.loading[t][0]===e){this.loading.splice(t,1);break}},callDoneCallbacks:function(){var e=this.callbacks;this.callbacks=[];for(var t in e)e[t]()},createResource:function(){throw"createResource not implemented by this instance of Manager"},loadResource:function(){throw"loadResource not implemented by this instance of Manager"}}),TextManager=Manager.extend({init:function(e){this._super(e)},add:function(e){return e=this.sourceCallback(e),this.addDescriptor(new TextDescriptor(e))},createResource:function(e){return{data:!1,descriptor:e}},loadResource:function(e,t,i,n){var r=this.descriptorCallback(e);Logistics.getText(r.getFullPath(),function(e){t.data=e,i(r,t)}).error(function(){n(r)})}}),ShadersManager=Manager.extend({init:function(e,t){this._super(t),this.context=e,this.aliases={diffuse:"shaders/default/diffuse",normalmapped:"shaders/default/normalmapped",transparent:"shaders/default/transparent",test:"shaders/default/test",fallback:"shaders/default/fallback",depthrgba:"shaders/default/DepthRGBA",gaussianblur:"shaders/default/GaussianBlur"},this.textManager=new TextManager},add:function(e,t){return this.addDescriptor(new ShaderDescriptor(e,t))},addSource:function(e){var t=e.toLowerCase();return t in this.aliases&&(e=this.aliases[t]),e=this.sourceCallback(e),this.addDescriptor(new ShaderDescriptor(e+".vert",e+".frag"))},createResource:function(e){return new Shader(this.context,e)},loadResource:function(e,t,i,n){var r=this.descriptorCallback(e),s=this.textManager.add(r.getVertexShaderPath()),a=this.textManager.add(r.getFragmentShaderPath());this.textManager.load(function(){return s.data&&a.data?(t.addVertexShader(s.data),t.addFragmentShader(a.data),void i(r,t)):void n(r)})}}),TexturesManager=Manager.extend({init:function(e,t){this._super(t),this.context=e},add:function(e){e=this.sourceCallback(e);var t=new TextureDescriptor(e);return this.addDescriptor(t)},createResource:function(e){return texture=new Texture(this.context),texture.name=e.source,texture},loadResource:function(e,t,i,n){var r=this.descriptorCallback(e),s=this;Logistics.getImage(r.getFullPath(),function(e){t.setImage(s.context,e),delete e,i(r,t)}).error(function(){n(r)})}}),MaterialsManager=Manager.extend({init:function(e,t,i,n){if(this._super(t),i&&!(i instanceof ShadersManager))throw"shadersManager is not instance of ShadersManager";if(n&&!(n instanceof TexturesManager))throw"texturesManager is not instance of TexturesManager";i||(i=new ShadersManager(e)),this.shadersManager=i,n||(n=new TexturesManager(e)),this.texturesManager=n,this.context=e},add:function(e){return e=this.sourceCallback(e),this.addDescriptor(new MaterialDescriptor(e))},createResource:function(e){var t=new Material;return t.descriptor=e,t},loadResource:function(e,t,i){var n,r=this.descriptorCallback(e),s=this;r.shaderDescriptor&&(n=this.shadersManager.addDescriptor(r.shaderDescriptor)),this.shadersManager.load(function(){var e={};for(var a in r.textureDescriptors)e[a]=s.texturesManager.addDescriptor(r.textureDescriptors[a]);s.texturesManager.load(function(){t.samplers||(t.samplers=[]);for(var s in e)t.samplers.push(new Sampler(s,e[s]));t.shader=n,t.uniforms=r.uniforms,r.requirements&&t.shader&&(t.shader.requirements.transparent=r.requirements.transparent),i(r,t)})})}}),MaterialSourcesManager=Manager.extend({init:function(e,t,i,n){if(this._super(t),i&&!(i instanceof MaterialsManager))throw"materialsManager is not instance of MaterialsManager";if(n&&!(n instanceof TextManager))throw"textManager is not instance of TextManager";i||(i=new MaterialsManager(e)),this.materialsManager=i,n||(n=new TextManager),this.textManager=n,this.context=e},add:function(e){return e=this.sourceCallback(e),this.addDescriptor(new MaterialSourceDescriptor(e))},createResource:function(e){return new MaterialSource(e)},loadResource:function(e,t,i){var n=this.descriptorCallback(e),r=this.textManager.add(n.getFullPath()),s=this;this.textManager.load(function(){var e=$.parseJSON(r.data),a=new MaterialDescriptor;if(a.parentDescriptor=n,e.uniforms)for(var o in e.uniforms){var h=e.uniforms[o];h instanceof Array?(1==h.length&&(a.uniforms[o]=new UniformFloat(h)),2==h.length&&(a.uniforms[o]=h[0]instanceof Array?new UniformMat2(h[0].concat(h[1])):new UniformVec2(h)),3==h.length&&(a.uniforms[o]=h[0]instanceof Array?new UniformMat3(h[0].concat(h[1]).concat(h[2])):new UniformVec3(h)),4==h.length&&(a.uniforms[o]=h[0]instanceof Array?new UniformMat4(h[0].concat(h[1]).concat(h[2]).concat(h[3])):new UniformVec4(h))):h instanceof Object?(!1 in h&&(h.a=0),a.uniforms[o]=new UniformColor(h)):a.uniforms[o]="number"==typeof h&&parseFloat(h)==parseInt(h)?new UniformInt(h):new UniformFloat(h)}if(e.textures)for(var c in e.textures){var u=new TextureDescriptor(e.textures[c]);a.textureDescriptors[c]=u,u.parentDescriptor=a}e.shader&&(a.shaderDescriptor=e.shader instanceof Array?new ShaderDescriptor(e.shader[0],e.shader[1]):new ShaderDescriptor(e.shader),a.shaderDescriptor.parentDescriptor=a),e.requirements&&(a.requirements=e.requirements),t.material=s.materialsManager.addDescriptor(a),s.materialsManager.load(function(){i(n,t)
  })})}}),ModelsManager=Manager.extend({init:function(e,t,i,n){this._super(t),i||(i=new ShadersManager(e)),this.shadersManager=i,n||(n=new TexturesManager(e)),this.texturesManager=n},getProgress:function(){var e=this._super();return 1==e?e:e+(this.texturesManager.getProgress()+this.shadersManager.getProgress())/2/this.getTotalItems()},add:function(e){return e=this.sourceCallback(e),this.addDescriptor(new ModelDescriptor(e))},createResource:function(){return new Node},loadResource:function(e,t,i,n){var r=this.descriptorCallback(e),s=0,a=this;Logistics.getBinary(r.getFullPath(),function(e){if(!e||0==e.byteLength)return void n(r);var o=a.createParser(e,function(e){var n=(new Date).getTime(),o=n-fileStartTime;s+=o;var h=new ModelLoader(a.context,r,a.shadersManager,a.texturesManager);h.load(t,e),i(r,t),a.shadersManager.load(function(){}),a.texturesManager.load(function(){})},function(){n(r)},function(){});fileStartTime=(new Date).getTime(),o.parse()})},createParser:function(e,t,i,n,r){return new ThreadedDataParser(e,t,i,n,r)}}),FontsManager=Manager.extend({init:function(e,t,i,n,r){if(this._super(),t&&!(t instanceof MaterialSourcesManager))throw"materialSourcesManager is not instance of MaterialSourcesManager";if(i&&!(i instanceof MaterialsManager))throw"materialsManager is not instance of MaterialsManager";if(n&&!(n instanceof TexturesManager))throw"texturesManager is not instance of TexturesManager";if(r&&!(r instanceof TextManager))throw"textManager is not instance of TextManager";r||(r=new TextManager),this.textManager=new TextManager,i||(i=new MaterialsManager(e)),this.materialsManager=i,t||(t=new MaterialSourcesManager(e,this.materialsManager,this.textManager)),this.materialSourcesManager=t,n||(n=new TexturesManager(e)),this.texturesManager=n},add:function(e,t){return this.addDescriptor(new FontDescriptor(e,t))},createResource:function(e){return new Font(!1,!1,!1,e)},loadResource:function(e,t,i){var n=this,r=[],s=e.fontTexturePaths;for(var a in s){var o=new TextureDescriptor(s[a]);o.parentDescriptor=e,r.push(this.texturesManager.addDescriptor(o))}this.texturesManager.load(function(){t.textures=r,e.materialSourceDescriptor||(e.materialSourceDescriptor=new MaterialSourceDescriptor("materials/FontMaterial.json")),e.materialSourceDescriptor.parentDescriptor=e,t.materialSource=n.materialSourcesManager.addDescriptor(e.materialSourceDescriptor),n.materialSourcesManager.load(function(){t.materialSource.material.samplers=[];for(var r in t.textures)t.materialSource.material.samplers.push(new Sampler("page"+r,t.textures[r]));var s=n.textManager.add(e.getFullDataPath());n.textManager.load(function(){t.data=new FontData($.parseXML(s.data)),i(e,t)})})})}}),FontSourcesManager=Manager.extend({init:function(e,t,i){if(this._super(),t&&!(t instanceof FontsManager))throw"fontsManager is not instance of FontsManager";if(i&&!(i instanceof TextManager))throw"textManager is not instance of TextManager";i||(i=new TextManager),this.textManager=i,t||(t=new FontsManager(e)),this.fontsManager=t},add:function(e){return this.addDescriptor(new FontSourceDescriptor(e))},createResource:function(e){return new FontSource(e)},loadResource:function(e,t,i,n){var r=this;Logistics.getText(this.sourceCallback(e.getFullPath(),e),function(s){var a=JSON&&JSON.parse(s)||$.parseJSON(s);if(!(a&&a.textures&&a.data&&a.material))return void n(e);var o=new FontDescriptor(a.textures,a.data,new MaterialSourceDescriptor(a.material));o.parentDescriptor=e,t.font=r.fontsManager.addDescriptor(o),r.fontsManager.load(function(){i(o,t)})}).error(function(){n(e)})}}),AssetsManager=Class.extend({init:function(e,t){this.managers=[],this.assetsPath=t;var n=this;this.loadingCount=0,this.loadedCallbacks=[];var r=function(e){e.onAddToQueue=function(){n.loadingCount++},e.onLoaded=function(){if(n.loadingCount--,n.loadingCount<=0){var e=n.loadedCallbacks.slice(0);n.loadedCallbacks=[];for(i in e){var t=e[i];t()}}},n.managers.push(e)};r(this.shadersManager=new ShadersManager(e,this.assetsPath)),r(this.texturesManager=new TexturesManager(e,this.assetsPath)),r(this.modelsManager=new ModelsManager(e,this.assetsPath,this.shadersManager,this.texturesManager)),r(this.textManager=new TextManager(this.assetsPath)),r(this.materialsManager=new MaterialsManager(e,this.assetsPath,this.shadersManager,this.texturesManager)),r(this.materialSourcesManager=new MaterialSourcesManager(e,this.assetsPath,this.materialsManager,this.textManager))},addTexture:function(e){return this.texturesManager.add(e)},addModel:function(e){return this.modelsManager.add(e)},addShaderSource:function(e){return this.shadersManager.addSource(e)},addShader:function(e,t){return this.shadersManager.add(e,t)},addText:function(e){return this.textManager.add(e)},addMaterial:function(e){return this.materialSourcesManager.add(e)},addFont:function(e){return this.fontSourcesManager.add(e)},hasItemsInQueue:function(){for(var e in this.managers)if(this.managers[e].getWaitingItems()>0)return!0;return!1},load:function(e,t){function n(){if(t){var e=0;for(var i in r.managers)e+=r.managers[i].getProgress();t(e/r.managers.length)}}var r=this;if(e&&this.loadedCallbacks.push(e),this.hasItemsInQueue())for(var s in this.managers)this.managers[s].load(function(){},n);else{var a=this.loadedCallbacks.slice(0);this.loadedCallbacks=[];for(i in a){var o=a[i];o()}}}}),BoundingVolume=Serializable.extend({init:function(e){this.center=!1,e&&(this.center=vec3.clone(e))},type:function(){return"BoundingVolume"},isPoint:function(){return!0},toString:function(){return"BoundingVolume[center=("+this.center[0]+","+this.center[1]+","+this.center[2]+")]"}}),BoundingVolumeVectorCache=[vec3.create(),vec3.create(),vec3.create()],BoundingBox=BoundingVolume.extend({init:function(e,t){this._super(e),this.size=vec3.create(),t&&vec3.copy(this.size,t),this.extents=vec3.scale(vec3.create(),this.size,.5),this.min=vec3.create(),this.max=vec3.create(),this.recalculate()},type:function(){return"BoundingBox"},recalculate:function(){vec3.scale(this.size,this.extents,2),this.center&&(vec3.subtract(this.min,this.center,this.extents),vec3.add(this.max,this.center,this.extents))},transform:function(e){var t=new BoundingBox;if(!this.center)return t;var i=0,n=0;mat4.translation(t.min,e),mat4.translation(t.max,e);for(var r=0;3>r;r++)for(var s=0;3>s;s++)i=e[4*s+r]*this.min[s],n=e[4*s+r]*this.max[s],n>i?(t.min[r]+=i,t.max[r]+=n):(t.min[r]+=n,t.max[r]+=i);return vec3.subtract(t.size,t.max,t.min),vec3.scale(t.extents,t.size,.5),t.center=vec3.add(vec3.create(),t.min,t.extents),t},isPoint:function(){return 0==this.size[0]&&0==this.size[1]&&0==this.size[2]},getOuterSphereRadius:function(){return vec3.len(this.extents)},containsPoint:function(e){return this.center&&e[0]>=this.min[0]&&e[1]>=this.min[1]&&e[2]>=this.min[2]&&e[0]<=this.max[0]&&e[1]<=this.max[1]&&e[2]<=this.max[2]?!0:!1},containsBox:function(e){return this.center?this.containsPoint(e.min)&&this.containsPoint(e.max):!1},intersectsBox:function(e){return this.center?this.max[0]>e.min[0]&&this.min[0]<e.max[0]&&this.max[1]>e.min[1]&&this.min[1]<e.max[1]&&this.max[2]>e.min[2]&&this.min[2]<e.max[2]:!1},intersectsPlane:function(e){if(!this.center)return!1;var t=BoundingVolumeVectorCache[0],i=BoundingVolumeVectorCache[1],n=BoundingVolumeVectorCache[2];vec3.copy(t,this.max),vec3.copy(i,this.min);var r=1/0,s=-1/0,a=e.getDistanceToPoint(this.min);return r>a&&(vec3.copy(t,this.min),r=a),a>s&&(vec3.copy(i,this.min),s=a),a=e.getDistanceToPoint(this.max),r>a&&(vec3.copy(t,this.max),r=a),a>s&&(vec3.copy(i,this.max),s=a),vec3.set(n,this.min[0],this.min[1],this.max[2]),a=e.getDistanceToPoint(n),r>a&&(vec3.copy(t,n),r=a),a>s&&(vec3.copy(i,n),s=a),vec3.set(n,this.min[0],this.max[1],this.min[2]),a=e.getDistanceToPoint(n),r>a&&(vec3.copy(t,n),r=a),a>s&&(vec3.copy(i,n),s=a),vec3.set(n,this.min[0],this.max[1],this.max[2]),a=e.getDistanceToPoint(n),r>a&&(vec3.copy(t,n),r=a),a>s&&(vec3.copy(i,n),s=a),vec3.set(n,this.max[0],this.min[1],this.min[2]),a=e.getDistanceToPoint(n),r>a&&(vec3.copy(t,n),r=a),a>s&&(vec3.copy(i,n),s=a),vec3.set(n,this.max[0],this.min[1],this.max[2]),a=e.getDistanceToPoint(n),r>a&&(vec3.copy(t,n),r=a),a>s&&(vec3.copy(i,n),s=a),vec3.set(n,this.max[0],this.max[1],this.min[2]),a=e.getDistanceToPoint(n),r>a&&(vec3.copy(t,n),r=a),a>s&&(vec3.copy(i,n),s=a),e.sameSide(t,i)?e.pointOnPlane(t)||e.pointOnPlane(i)?!0:!1:!0},intersectsTriangle:function(e,t,i){if(!this.center)return!1;if(AABBPlaneCache.setByPoints(e,t,i),!this.intersectsPlane(AABBPlaneCache))return!1;if(this.containsPoint(e)||this.containsPoint(t)||this.containsPoint(i))return!0;var n=BoundingVolumeVectorCache[0],r=BoundingVolumeVectorCache[1];vec3.copy(n,e),vec3.copy(r,e);for(var s=0;3>s;s++)t[s]<n[s]&&(n[s]=t[s]),i[s]<n[s]&&(n[s]=i[s]),t[s]>r[s]&&(r[s]=t[s]),i[s]>r[s]&&(r[s]=i[s]);if(!(this.max[0]>=n[0]&&this.min[0]<=r[0]&&this.max[1]>=n[1]&&this.min[0]<=r[1]&&this.max[2]>=n[2]&&this.min[2]<=r[2]))return!1;var a=vec2.fromValues(e[0],e[1]),o=vec2.fromValues(t[0],t[1]),h=vec2.fromValues(i[0],i[1]),c=vec2.fromValues(this.min[0],this.min[1]),u=vec2.fromValues(this.max[0],this.max[1]);return LineRectIntersection2D(a,o,c,u)||LineRectIntersection2D(o,h,c,u)||LineRectIntersection2D(h,a,c,u)||PointInTriangle2D(a,o,h,c)?(vec2.set(a,e[2],e[1]),vec2.set(o,t[2],t[1]),vec2.set(h,i[2],i[1]),vec2.set(c,this.min[2],this.min[1]),vec2.set(u,this.max[2],this.max[1]),LineRectIntersection2D(a,o,c,u)||LineRectIntersection2D(o,h,c,u)||LineRectIntersection2D(h,a,c,u)||PointInTriangle2D(a,o,h,c)?(vec2.set(a,e[0],e[2]),vec2.set(o,t[0],t[2]),vec2.set(h,i[0],i[2]),vec2.set(c,this.min[0],this.min[2]),vec2.set(u,this.max[0],this.max[2]),LineRectIntersection2D(a,o,c,u)||LineRectIntersection2D(o,h,c,u)||LineRectIntersection2D(h,a,c,u)||PointInTriangle2D(a,o,h,c)?!0:!1):!1):!1},encapsulatePoint:function(e){if(!this.center)return this.center=vec3.clone(e),this.extents[0]=0,this.extents[1]=0,this.extents[2]=0,void this.recalculate();if(!this.containsPoint(e)){for(var t=vec3.subtract(BoundingVolumeVectorCache[0],e,this.center),i=0;3>i;i++)Math.abs(t[i])>this.extents[i]&&(this.extents[i]+=(Math.abs(t[i])-this.extents[i])/2,this.center[i]=e[i]+(e[i]>this.center[i]?-1:1)*this.extents[i]);this.recalculate()}},encapsulateBox:function(e){return e.center?this.center?void(this.containsBox(e)||(this.encapsulatePoint(e.min),this.encapsulatePoint(e.max))):(this.center=vec3.clone(e.center),this.extents=vec3.clone(e.extents),void this.recalculate()):void 0},getVertices:function(){var e=[];return e.push(vec3.create(),vec3.create(),vec3.create(),vec3.create(),vec3.create(),vec3.create(),vec3.create(),vec3.create()),vec3.add(e[0],this.center,[this.extents[0],this.extents[1],this.extents[2]]),vec3.add(e[1],this.center,[-this.extents[0],this.extents[1],this.extents[2]]),vec3.add(e[2],this.center,[this.extents[0],-this.extents[1],this.extents[2]]),vec3.add(e[3],this.center,[-this.extents[0],-this.extents[1],this.extents[2]]),vec3.add(e[4],this.center,[this.extents[0],this.extents[1],-this.extents[2]]),vec3.add(e[5],this.center,[-this.extents[0],this.extents[1],-this.extents[2]]),vec3.add(e[6],this.center,[this.extents[0],-this.extents[1],-this.extents[2]]),vec3.add(e[7],this.center,[-this.extents[0],-this.extents[1],-this.extents[2]]),e},toString:function(){return"BoundingBox[\n	center=("+this.center[0]+", "+this.center[1]+", "+this.center[2]+")\n	min=("+this.min[0]+", "+this.min[1]+", "+this.min[2]+")\n	max=("+this.max[0]+", "+this.max[1]+", "+this.max[2]+")\n	extents=("+this.extents[0]+", "+this.extents[1]+", "+this.extents[2]+")\n	size=("+this.size[0]+", "+this.size[1]+", "+this.size[2]+")\n]\n"}}),BoundingSphere=BoundingVolume.extend({init:function(e,t){this._super(e),this.radius=0,t&&(this.radius=t)},type:function(){return"BoundingSphere"},isPoint:function(){return 0==this.radius},containsPoint:function(e){return this.center?vec3.distance(e,this.center)<=this.radius:!1},containsSphere:function(e){return this.center?vec3.distance(e.center,this.center)<=this.radius-e.radius:!1},intersectsSphere:function(e){if(!this.center)return!1;var t=vec3.squaredLength(vec3.subtract(BoundingVolumeVectorCache[0],this.center,e.center)),i=this.radius+e.radius;return i*i>=t},encapsulatePoint:function(e){if(!this.center)return this.center=vec3.clone(e),void(this.radius=0);if(!this.containsPoint(e)){var t=vec3.subtract(BoundingVolumeVectorCache[0],this.center,e),i=vec3.length(t)+this.radius;vec3.normalize(t,t),this.radius=i/2;var n=vec3.scale(BoundingVolumeVectorCache[1],t,this.radius);vec3.add(this.center,e,n)}},encapsulateSphere:function(e){if(e.center){if(!this.center)return this.center=vec3.clone(e.center),void(this.radius=e.radius);if(!this.containsSphere(e)){var t=vec3.subtract(BoundingVolumeVectorCache[0],e.center,this.center),i=vec3.length(t)+e.radius;vec3.normalize(t,t),vec3.scale(t,t,i);var n=vec3.add(BoundingVolumeVectorCache[2],this.center,t);this.encapsulatePoint(n)}}},transform:function(e){if(!this.center)return new BoundingSphere;var t=mat4.getScale(BoundingVolumeVectorCache[0],e),i=vec3.transformMat4(BoundingVolumeVectorCache[1],this.center,e);return new BoundingSphere(i,this.radius*Math.max(t[0],t[1],t[2]))},toString:function(){return"BoundingSphere[center=("+this.center[0]+", "+this.center[1]+", "+this.center[2]+") radius="+this.radius+"]"}}),Plane=Class.extend({init:function(){this.normal=vec3.create(),this.distance=0},setByPoints:function(e,t,i){return this.normal=vec3.cross(vec3.create(),vec3.subtract(vec3.create(),t,e),vec3.subtract(vec3.create(),i,e)),vec3.normalize(this.normal,this.normal),this.distance=-vec3.dot(this.normal,t),this},setByNormalAndPoint:function(e,t){return this.normal=vec3.clone(e),vec3.normalize(this.normal,this.normal),this.distance=-vec3.dot(this.normal,t),this},getDistanceToPoint:function(e){return vec3.dot(this.normal,e)+this.distance},getDistanceOnLine:function(e,t){var i=vec3.scale(vec3.create(),this.normal,-this.distance),n=vec3.dot(t,this.normal);return Math.abs(n)<EPSILON?1/0:vec3.dot(vec3.sub(i,i,e),this.normal)/n},getLineIntersection:function(e,t,i){i||(i=vec3.create());var n=this.getDistanceOnLine(e,t);return vec3.scaleAndAdd(i,e,t,n),i},projectToPlane:function(e,t){return t||(t=vec3.create()),vec3.scale(t,this.normal,this.getDistanceToPoint(e)),vec3.sub(t,e,t),t},pointInFront:function(e){return vec3.dot(this.normal,e)+this.distance>0},pointInBack:function(e){return vec3.dot(this.normal,e)+this.distance<0},pointOnPlane:function(e){return Math.abs(vec3.dot(this.normal,e)+this.distance)<EPSILON},sameSide:function(e,t){var i=vec3.dot(this.normal,e)+this.distance,n=vec3.dot(this.normal,t)+this.distance;return!(0>i*n)},toString:function(){return"Plane["+this.normal[0]+", "+this.normal[1]+", "+this.normal[2]+", "+this.distance+"]"}}),AABBPlaneCache=new Plane,Ray=Class.extend({init:function(e,t){this.infinite=!1,this.origin=vec3.create(),this.destination=vec3.create(),e&&vec3.copy(this.origin,e),t&&vec3.copy(this.destination,t)},clone:function(){var e=new Ray(this.origin,this.destination);return e.infinite=this.infinite,e},getLength:function(){return vec3.distance(this.origin,this.destination)},getDirection:function(e){return e||(e=vec3.create()),this.getVector(e),vec3.normalize(e,e),e},getVector:function(e){return e||(e=vec3.create()),vec3.subtract(e,this.destination,this.origin),e},transform:function(e){vec3.transformMat4(this.origin,this.origin,e),vec3.transformMat4(this.destination,this.destination,e)},transformWithLength:function(e,t){var i=mat4.clone(e);i[12]=0,i[13]=0,i[14]=0;var n=this.getDirection();vec3.transformMat4(this.origin,this.origin,e),vec3.transformMat4(n,n,i),vec3.scale(n,n,t),vec3.add(this.destination,this.origin,n)},getPointOnRay:function(e){var t=vec3.create(),i=this.getVector();return vec3.add(t,this.origin,vec3.scale(i,i,e)),t},getClosestPointOnRay:function(e){var t=this.getDirection(),i=vec3.dot(t,vec3.subtract(vec3.create(),e,this.origin));return vec3.add(vec3.create(),this.origin,vec3.scale(t,t,i))},distanceOfPoint:function(e){return vec3.dot(this.getDirection(),vec3.subtract(vec3.create(),e,this.origin))<=0?vec3.distance(e,this.origin):vec3.distance(vec3.cross(vec3.create(),this.getDirection(),vec3.subtract(vec3.create(),e,this.origin)))},intersectBoundingVolume:function(e,t){return e instanceof BoundingVolume&&e.center?e instanceof BoundingSphere?this.intersectSphere(e.center,e.radius,t):e instanceof BoundingBox?this.intersectAABB(e.min,e.max,t):!1:!1},intersectPlane:function(e,t){if(e.sameSide(this.origin,this.destination))return!1;var i=this.getDirection(),n=-e.getDistanceToPoint(this.origin)/vec3.dot(i,e.normal);return t&&t.add(vec3.add(vec3.create(),this.origin,vec3.scale(i,i,n))),!0},intersectTriangle:function(e,t,i,n){var r=vec3.subtract(RayTestLocalCache[0],i,e),s=vec3.subtract(RayTestLocalCache[1],t,e),a=vec3.cross(RayTestLocalCache[2],s,r);vec3.normalize(a,a);var o=vec3.dot(vec3.subtract(RayTestLocalCache[3],this.origin,e),a),h=vec3.dot(vec3.subtract(RayTestLocalCache[3],this.destination,e),a);if(o*h>=0)return!1;var c=this.getVector();c=vec3.add(c,this.origin,vec3.scale(c,c,-o/(h-o)));var u=vec3.subtract(RayTestLocalCache[2],c,e),l=vec3.dot(r,r),d=vec3.dot(r,s),f=vec3.dot(r,u),m=vec3.dot(s,s),p=vec3.dot(s,u),g=1/(l*m-d*d),v=(m*f-d*p)*g,b=(l*p-d*f)*g;return v>=0&&b>=0&&1>=v+b?(n&&n.add(c),!0):!1},intersectTriangleDistanceOnly:function(e,t,i){var n=vec3.subtract(RayTestLocalCache[0],i,e),r=vec3.subtract(RayTestLocalCache[1],t,e),s=vec3.cross(RayTestLocalCache[2],r,n);vec3.normalize(s,s);var a=vec3.dot(vec3.subtract(RayTestLocalCache[3],this.origin,e),s),o=vec3.dot(vec3.subtract(RayTestLocalCache[3],this.destination,e),s);if(a*o>=0)return!1;var h=this.getVector(),c=-a/(o-a);h=vec3.add(h,this.origin,vec3.scale(h,h,c));var u=vec3.subtract(RayTestLocalCache[2],h,e),l=vec3.dot(n,n),d=vec3.dot(n,r),f=vec3.dot(n,u),m=vec3.dot(r,r),p=vec3.dot(r,u),g=1/(l*m-d*d),v=(m*f-d*p)*g,b=(l*p-d*f)*g;return v>=0&&b>=0&&1>=v+b?c:!1},intersectSphere:function(e,t,i){var n=vec3.sub(RayTestLocalCache[0],this.origin,e),r=this.getDirection(),s=vec3.dot(r,n),a=s*s-vec3.dot(n,n)+t*t;return Math.abs(a)<EPSILON?(i&&i.add(vec3.add(vec3.create(),this.origin,vec3.scale(r,r,-s))),!0):a>0?(i&&(i.add(vec3.add(vec3.create(),this.origin,vec3.scale(RayTestLocalCache[0],r,-s-Math.sqrt(a)))),i.add(vec3.add(vec3.create(),this.origin,vec3.scale(RayTestLocalCache[0],r,-s+Math.sqrt(a))))),!0):!1},intersectAABB:function(e,t,i){var n=this.getDirection(RayTestLocalCache[0]),r=RayTestLocalCache[1],s=RayTestLocalCache[2];n[0]=1/n[0],n[1]=1/n[1],n[2]=1/n[2],r[0]=(e[0]-this.origin[0])*n[0],s[0]=(t[0]-this.origin[0])*n[0],r[1]=(e[1]-this.origin[1])*n[1],s[1]=(t[1]-this.origin[1])*n[1],r[2]=(e[2]-this.origin[2])*n[2],s[2]=(t[2]-this.origin[2])*n[2];var a=Math.max(Math.min(r[0],s[0]),Math.min(r[1],s[1]),Math.min(r[2],s[2])),o=Math.min(Math.max(r[0],s[0]),Math.max(r[1],s[1]),Math.max(r[2],s[2]));return 0>o||a>o?!1:this.infinite?(i&&(this.getDirection(n),i.add(vec3.add(vec3.create(),this.origin,vec3.scale(RayTestLocalCache[1],n,a))),i.add(vec3.add(vec3.create(),this.origin,vec3.scale(RayTestLocalCache[1],n,o)))),!0):a*a>vec3.sqrDist(this.origin,this.destination)&&(this.origin[0]<e[0]||this.origin[1]<e[1]||this.origin[2]<e[2]||this.origin[0]>t[0]||this.origin[1]>t[1]||this.origin[2]>t[2])&&(this.destination[0]<e[0]||this.destination[1]<e[1]||this.destination[2]<e[2]||this.destination[0]>t[0]||this.destination[1]>t[1]||this.destination[2]>t[2])?!1:(i&&(this.getDirection(n),i.add(vec3.add(vec3.create(),this.origin,vec3.scale(RayTestLocalCache[1],n,a))),i.add(vec3.add(vec3.create(),this.origin,vec3.scale(RayTestLocalCache[1],n,o)))),!0)},toString:function(){return"Ray("+vec3.str(this.origin)+", "+vec3.str(this.destination)+", infinite = "+this.infinite+")"}}),RayTestResult=Class.extend({init:function(e){this.ray=e.clone(),this.hits=[],this.addCallback=!1},add:function(e){var t={point:e,collider:!1,submesh:!1,node:!1};$.isFunction(this.addCallback)&&this.addCallback(t),this.hits.push(t)},empty:function(){return 0==this.hits.length},sort:function(){var e=this;this.hits.sort(function(t,i){var n=vec3.sqrDist(e.ray.origin,t.point),r=vec3.sqrDist(e.ray.origin,i.point);return n-r})},nearest:function(){if(this.empty())return!1;var e=1/0,t=0;for(var i in this.hits){var n=vec3.sqrDist(this.ray.origin,this.hits[i].point);e>n&&(e=n,t=i)}return this.hits[t]}}),RayTestLocalCache=[vec3.create(),vec3.create(),vec3.create(),vec3.create()],Submesh=Class.extend({init:function(){this.materialIndex=-1,this.faces=[],this.positions=[],this.texCoords1D=[],this.texCoords2D=[],this.texCoords3D=[],this.tangents=!1,this.normals=!1,this.bitangents=!1,this.barycentric=!1,this.boundingBox=new BoundingBox,this.boundingSphere=new BoundingSphere},calculateTangents:function(){for(var e=new Float32Array(this.positions.length),t=new Float32Array(this.positions.length),i=this.texCoords2D[0],n=vec3.create(),r=vec3.create(),s=vec3.create(),a=vec2.create(),o=vec2.create(),h=vec2.create(),c=vec3.create(),u=vec3.create(),l=0;l<this.faces.length;l+=3){var d=this.faces[l],f=this.faces[l+1],m=this.faces[l+2];vec3.set(n,this.positions[3*d],this.positions[3*d+1],this.positions[3*d+2]),vec3.set(r,this.positions[3*f],this.positions[3*f+1],this.positions[3*f+2]),vec3.set(s,this.positions[3*m],this.positions[3*m+1],this.positions[3*m+2]),vec2.set(a,i[2*d],i[2*d+1]),vec2.set(o,i[2*f],i[2*f+1]),vec2.set(h,i[2*m],i[2*m+1]);var p=r[0]-n[0],g=s[0]-n[0],v=r[1]-n[1],b=s[1]-n[1],T=r[2]-n[2],x=s[2]-n[2],E=o[0]-a[0],w=h[0]-a[0],S=o[1]-a[1],y=h[1]-a[1],M=1/(E*y-w*S);vec3.set(c,(y*p-S*g)*M,(y*v-S*b)*M,(y*T-S*x)*M),vec3.set(u,(E*g-w*p)*M,(E*b-w*v)*M,(E*x-w*T)*M),e[3*d+0]+=c[0],e[3*d+1]+=c[1],e[3*d+2]+=c[2],e[3*f+0]+=c[0],e[3*f+1]+=c[1],e[3*f+2]+=c[2],e[3*m+0]+=c[0],e[3*m+1]+=c[1],e[3*m+2]+=c[2],t[3*d+0]+=u[0],t[3*d+1]+=u[1],t[3*d+2]+=u[2],t[3*f+0]+=u[0],t[3*f+1]+=u[1],t[3*f+2]+=u[2],t[3*m+0]+=u[0],t[3*m+1]+=u[1],t[3*m+2]+=u[2]}this.tangents=new Float32Array(this.positions.length),this.bitangents=new Float32Array(this.positions.length);for(var R=vec3.create(),_=vec3.create(),D=vec3.create(),C=vec3.create(),l=0;l<this.normals.length;l+=3){vec3.set(R,this.normals[l],this.normals[l+1],this.normals[l+2]),vec3.set(_,e[l],e[l+1],e[l+2]),vec3.scale(D,R,vec3.dot(R,_)),vec3.sub(D,_,D),vec3.normalize(D,D),this.tangents[l]=D[0],this.tangents[l+1]=D[1],this.tangents[l+2]=D[2],vec3.set(D,t[l],t[l+1],t[l+2]),vec3.cross(C,R,_);var P=vec3.dot(C,D)<0?-1:1;vec3.set(_,this.tangents[l],this.tangents[l+1],this.tangents[l+2]),vec3.cross(D,R,_),vec3.scale(D,D,P),vec3.normalize(D,D),this.bitangents[l]=D[0],this.bitangents[l+1]=D[1],this.bitangents[l+2]=D[2]}delete e,delete t},recalculateBounds:function(){this.boundingBox=new BoundingBox,this.boundingSphere=new BoundingSphere;for(var e=0,t=this.positions.length;t>e;e+=3)this.boundingBox.encapsulatePoint(vec3.fromValues(this.positions[e+0],this.positions[e+1],this.positions[e+2])),this.boundingSphere.encapsulatePoint(vec3.fromValues(this.positions[e+0],this.positions[e+1],this.positions[e+2]))},generateEdges:function(){function e(e,i){t.edges[t.faces[e]]||(t.edges[e]={}),t.edges[t.faces[e]][t.faces[i]]=!0}var t=this;this.edges={};for(var i=0,n=this.faces.length;n>i;i+=3)e(i,i+1),e(i+1,i),e(i+1,i+2),e(i+2,i+1),e(i+2,i),e(i,i+2)}}),Mesh=Class.extend({init:function(){this.submeshes=[],this.materials=[],this.boundingBox=new BoundingBox,this.boundingSphere=new BoundingSphere},addSubmesh:function(e,t){this.boundingBox.encapsulateBox(e.boundingBox),this.boundingSphere.encapsulateSphere(e.boundingSphere),this.submeshes.push(e),t&&(this.materials.push(t),e.materialIndex=this.materials.length-1)},getMaterial:function(e){return e>=0&&e<this.materials.length?this.materials[e]:!1},setMaterial:function(e,t){if(0>e||e>=this.materials.length)throw"Material.setMaterial: index out of bounds.";this.materials[e]=t},addMaterial:function(e){return this.materials.push(e),this.materials.length-1},getPolycount:function(){var e=0;for(var t in this.submeshes)e+=this.submeshes[t].faces.length/3;return e},empty:function(){return 0===this.submeshes.length}}),Primitives={plane:function(e,t,i){var n=new Mesh,r=new Submesh;r.positions=[-.5*e,-.5*t,0,-.5*e,.5*t,0,.5*e,.5*t,0,.5*e,-.5*t,0],r.normals=[0,0,1,0,0,1,0,0,1,0,0,1],r.texCoords2D=[[0,0,0,1,1,1,1,0]],r.faces=[0,1,2,0,2,3],r.recalculateBounds(),n.addSubmesh(r,i);var s=new Node("Plane");return s.addComponent(new MeshComponent(n)),s.addComponent(new MeshRendererComponent),s},box:function(e,t,i){function n(e,t,i,n){vec3.sub(o,t,e),vec3.sub(h,n,e),vec3.cross(a,o,h),vec3.negate(a,a),vec3.normalize(a,a);var r=s.positions.length/3;s.positions.push(e[0],e[1],e[2]),s.normals.push(a[0],a[1],a[2]),s.texCoords2D[0].push(0,1),s.positions.push(t[0],t[1],t[2]),s.normals.push(a[0],a[1],a[2]),s.texCoords2D[0].push(1,1),s.positions.push(i[0],i[1],i[2]),s.normals.push(a[0],a[1],a[2]),s.texCoords2D[0].push(1,0),s.positions.push(n[0],n[1],n[2]),s.normals.push(a[0],a[1],a[2]),s.texCoords2D[0].push(0,0),s.faces.push(r+0,r+3,r+2),s.faces.push(r+2,r+1,r+0)}var r=new Mesh,s=new Submesh;s.positions=[],s.normals=[],s.texCoords2D=[[]];var a=vec3.create(),o=vec3.create(),h=vec3.create(),c=[vec3.fromValues(e[0]-t[0],e[1]-t[1],e[2]-t[2]),vec3.fromValues(e[0]+t[0],e[1]-t[1],e[2]-t[2]),vec3.fromValues(e[0]+t[0],e[1]+t[1],e[2]-t[2]),vec3.fromValues(e[0]-t[0],e[1]+t[1],e[2]-t[2]),vec3.fromValues(e[0]-t[0],e[1]-t[1],e[2]+t[2]),vec3.fromValues(e[0]+t[0],e[1]-t[1],e[2]+t[2]),vec3.fromValues(e[0]+t[0],e[1]+t[1],e[2]+t[2]),vec3.fromValues(e[0]-t[0],e[1]+t[1],e[2]+t[2])];n(c[0],c[1],c[2],c[3]),n(c[5],c[4],c[7],c[6]),n(c[4],c[0],c[3],c[7]),n(c[1],c[5],c[6],c[2]),n(c[4],c[5],c[1],c[0]),n(c[3],c[2],c[6],c[7]),s.calculateTangents(),s.recalculateBounds(),r.addSubmesh(s,i);var u=new Node("Box");return u.addComponent(new MeshComponent(r)),u.addComponent(new MeshRendererComponent),u},text:function(e){var t=new Node("Text");return t.addComponent(new TextComponent(e)),t.addComponent(new TextRendererComponent),t}},CollisionOctreeNode=Class.extend({init:function(e,t,i){this.parent=!1,this.depth=0,this.subnodes=!1,this.bounds=!1,i?(this.parent=i,this.root=i.root,this.depth=i.depth+1):(this.maxDepth=3,this.root=this,this.nodes={},this.submeshes={},this.cache=[vec3.create(),vec3.create(),vec3.create(),vec3.create(),vec3.create()]),this.faces=!1,this.setSize(e,t)},clone:function(e){var t=new CollisionOctreeNode(this.bounds.center,this.bounds.size[0],e?e:!1);if(t.depth=this.depth,this.nodes){t.nodes={};for(var i in this.nodes)t.nodes[i]=this.nodes[i]}if(this.submeshes){t.submeshes={};for(var n in this.submeshes)t.submeshes[n]=this.submeshes[n]}if(t.faces=this.faces,this.subnodes){t.subnodes=[];for(var r=0;r<this.subnodes.length;r++)t.subnodes.push(this.subnodes[r].clone(t))}return t},getNodeID:function(){var e="/",t="root";if(this.parent){e=this.parent.getNodeID();for(var i in this.parent.subnodes)if(this.parent.subnodes[i]===this){t=i;break}}return"{0}{1}/".format(e,t)},setSize:function(e,t){this.bounds=new BoundingBox(e,[t,t,t])},isLeaf:function(){return this.subnodes===!1},hasGeometry:function(){return this.faces!==!1},subdivide:function(){this.subnodes=[];var e=.5*this.bounds.size[0],t=.5*e,i=vec3.create();this.subnodes.push(new CollisionOctreeNode(vec3.add(i,this.bounds.center,[t,t,t]),e,this)),this.subnodes.push(new CollisionOctreeNode(vec3.add(i,this.bounds.center,[-t,t,t]),e,this)),this.subnodes.push(new CollisionOctreeNode(vec3.add(i,this.bounds.center,[t,-t,t]),e,this)),this.subnodes.push(new CollisionOctreeNode(vec3.add(i,this.bounds.center,[-t,-t,t]),e,this)),this.subnodes.push(new CollisionOctreeNode(vec3.add(i,this.bounds.center,[t,t,-t]),e,this)),this.subnodes.push(new CollisionOctreeNode(vec3.add(i,this.bounds.center,[-t,t,-t]),e,this)),this.subnodes.push(new CollisionOctreeNode(vec3.add(i,this.bounds.center,[t,-t,-t]),e,this)),this.subnodes.push(new CollisionOctreeNode(vec3.add(i,this.bounds.center,[-t,-t,-t]),e,this))},optimize:function(){if(!this.isLeaf()){for(var e in this.subnodes)this.subnodes[e].optimize();var t=0;for(var e in this.subnodes)!this.subnodes[e].hasGeometry()&&this.subnodes[e].isLeaf()&&t++;8==t&&(delete this.subnodes,this.subnodes=!1)}},rayIntersectBounds:function(e){var t=e.getDirection(this.root.cache[0]),i=this.root.cache[1],n=this.root.cache[2];t[0]=1/t[0],t[1]=1/t[1],t[2]=1/t[2],i[0]=(this.bounds.min[0]-e.origin[0])*t[0],n[0]=(this.bounds.max[0]-e.origin[0])*t[0],i[1]=(this.bounds.min[1]-e.origin[1])*t[1],n[1]=(this.bounds.max[1]-e.origin[1])*t[1],i[2]=(this.bounds.min[2]-e.origin[2])*t[2],n[2]=(this.bounds.max[2]-e.origin[2])*t[2];var r=Math.max(Math.min(i[0],n[0]),Math.min(i[1],n[1]),Math.min(i[2],n[2])),s=Math.min(Math.max(i[0],n[0]),Math.max(i[1],n[1]),Math.max(i[2],n[2]));return 0>s||r>s?!1:e.infinite?r:r*r>vec3.sqrDist(e.origin,e.destination)&&(e.origin[0]<this.bounds.min[0]||e.origin[1]<this.bounds.min[1]||e.origin[2]<this.bounds.min[2]||e.origin[0]>this.bounds.max[0]||e.origin[1]>this.bounds.max[1]||e.origin[2]>this.bounds.max[2])&&(e.destination[0]<this.bounds.min[0]||e.destination[1]<this.bounds.min[1]||e.destination[2]<this.bounds.min[2]||e.destination[0]>this.bounds.max[0]||e.destination[1]>this.bounds.max[1]||e.destination[2]>this.bounds.max[2])?!1:r},rayIntersectGeometry:function(e){if(!this.hasGeometry())return!1;var t={submesh:!1,node:!1,t:1/0,normal:vec3.create()},i=this.root.cache[0],n=this.root.cache[1],r=this.root.cache[2],s=mat4.create();for(var a in this.faces){var o=e.clone();mat4.isIdentity(this.root.nodes[a].transform.absolute)||(mat4.invert(s,this.root.nodes[a].transform.absolute),o.transform(s));for(var h in this.faces[a])for(var c=this.faces[a][h],u=this.root.submeshes[h].positions,l=0;l<c.length;l+=3){i[0]=u[3*c[l]],i[1]=u[3*c[l]+1],i[2]=u[3*c[l]+2],n[0]=u[3*c[l+1]],n[1]=u[3*c[l+1]+1],n[2]=u[3*c[l+1]+2],r[0]=u[3*c[l+2]],r[1]=u[3*c[l+2]+1],r[2]=u[3*c[l+2]+2];var d=o.intersectTriangleDistanceOnly(i,n,r);d!==!1&&d<t.t&&(t.t=d,t.submesh=this.root.submeshes[h],t.node=this.root.nodes[a],vec3.cross(t.normal,vec3.subtract(this.root.cache[3],n,i),vec3.subtract(this.root.cache[4],r,i)),vec3.normalize(t.normal,t.normal))}}return t},getNodesWithGeometry:function(e,t){var i=this.rayIntersectBounds(e);if(i!==!1){if(this.hasGeometry()){for(var n=0;n<t.length&&!(t[n].t>i);n++);t.splice(n,0,{t:i,octreeNode:this})}if(!this.isLeaf())for(var n in this.subnodes)this.subnodes[n].getNodesWithGeometry(e,t)}},getNearestRayCollision:function(e,t){var i=[];this.getNodesWithGeometry(e,i);for(var n={t:1/0,octreeNode:!1,submesh:!1,node:!1,normal:!1},r=0;r<i.length;r++)if(!(n.octreeNode!==!1&&i[r].depth==n.octreeNode.depth&&i[r].t>n.t)){var s=i[r].octreeNode.rayIntersectGeometry(t);s.t<n.t&&(n.t=s.t,n.submesh=s.submesh,n.octreeNode=i[r].octreeNode,n.node=s.node,n.normal=s.normal)}return n}}),Component=Serializable.extend({init:function(){this._super(),this.updatePasses=1,this.started=!1,this.node=!1,this.enable()},excluded:function(){return["started","node"]},getScene:function(){return this.node.scene},enable:function(){this.enabled||this.onEnable(),this.enabled=!0},disable:function(){this.enabled&&this.onDisable(),this.enabled=!1},instantiate:function(){var e=this.clone();return e},onAdd:function(){},onRemove:function(){},onAddScene:function(){},onRemoveScene:function(){},onEnable:function(){},onDisable:function(){},onStart:function(){},start:function(e,t){this.onStart(e,t)},onLoad:function(){},onEnd:function(){},onPreRender:function(){},onPostRender:function(){},onUpdateTransform:function(){},onUpdate:function(){}}),CameraComponent=Component.extend({init:function(e,t){if(!e||!t)throw"CameraComponent can be initialized only with given viewMatrix and projectionMatrix. Normally one should create OrthoCamera or PerspectiveCamera instead";this._super(),this.camera=new Camera(e,t,new PostProcessRenderStage)},excluded:function(){return this._super().concat(["camera"])},type:function(){return"CameraComponent"},onAddScene:function(e){e.scene.cameras.push(this.camera),e.scene.cameras.sort(function(e,t){return e.order-t.order}),this.useCameraViewMatrix()
  },onRemoveScene:function(e){for(var t=e.scene.cameras,i=0;i<t.length;i++)t[i]==this.camera&&(t.splice(i,1),i--)},onStart:function(e,t){if(this.camera.target instanceof TargetScreen){var i=e.canvas.parent().position();this.camera.target.setPosition(i.left,i.top),this.camera.target.setSize(e.canvas.width(),e.canvas.height())}("blended"==t.options.transparencyMode||"stochastic"==t.options.transparencyMode)&&this.camera.renderStage.addStage(new OITPostProcess),t.options.ssao===!0&&this.camera.renderStage.addStage(new SSAOPostProcess),t.options.antialias===!0&&this.camera.renderStage.addStage(new AntiAliasPostProcess),this.camera.renderStage.start(e,t,this.camera)},onUpdateTransform:function(){this.node.transform&&mat4.invert(this.camera.viewMatrix,this.node.transform.absolute)},lookAt:function(e,t){t||(t=[0,1,0]),mat4.lookAt(this.camera.viewMatrix,this.camera.getPosition(),e,t),this.useCameraViewMatrix()},setPosition:function(e){this.camera.setPosition(e),this.useCameraViewMatrix()},center:function(e){this.camera.center(e),this.useCameraViewMatrix()},fitToView:function(e){this.camera.fitToView(e),this.useCameraViewMatrix()},fitNodeToView:function(e){var t=new BoundingBox;e.onEachChild(function(e){if(e.getComponent(MeshComponent)){var i=e.getComponent(MeshComponent);t.encapsulateBox(i.mesh.boundingBox.transform(e.transform.absolute))}}),this.fitToView(t)},screenPointToViewportPoint:function(e){var t=vec2.create(),i=vec2.create();this.camera.target instanceof TargetScreen&&(i=this.camera.target.getPosition());var n=this.camera.target.getSize();return Math.abs(n[0])<EPSILON||Math.abs(n[1])<EPSILON?t:(t[0]=(e[0]-i[0])/n[0],t[1]=(e[1]-i[1])/n[1],t)},unprojectScreenPoint:function(e){var t=this.node.scene.camera.target.getSize(),i=vec2.create(),n=vec2.fromValues(e[0]-i[0],t[1]-e[1]+i[1]);if(Math.abs(t[0])<EPSILON||Math.abs(t[1])<EPSILON)return!1;var r=vec4.fromValues(2*(n[0]/t[0])-1,2*(n[1]/t[1])-1,2*e[2]-1,1),s=mat4.mul(mat4.create(),this.camera.projectionMatrix,this.camera.viewMatrix);return mat4.invert(s,s)?(vec4.transformMat4(r,r,s),Math.abs(r[3])<EPSILON?!1:(r[3]=1/r[3],vec3.fromValues(r[0]*r[3],r[1]*r[3],r[2]*r[3]))):!1},screenPointToRay:function(e){var t=this.unprojectScreenPoint([e[0],e[1],0]),i=this.unprojectScreenPoint([e[0],e[1],1]);return t&&i?new Ray(t,i):!1},useCameraViewMatrix:function(){this.node.transform&&(this.node.transform.absolute=mat4.invert(mat4.create(),this.camera.viewMatrix),this.node.calculateRelativeFromAbsolute())}}),PerspectiveCamera=CameraComponent.extend({init:function(e,t,i,n){e||(e=45),i||(i=.3),n||(n=1e3),t||(t=4/3),this.fov=e,this.aspect=t,this.near=i,this.far=n;var r=mat4.create();mat4.lookAt(r,[0,0,-100],[0,0,0],[0,1,0]),this._super(r,this.calculatePerspective()),this.camera.near=this.near,this.camera.far=this.far},type:function(){return"PerspectiveCamera"},onStart:function(e,t){this.aspect||this.setAspectRatio(e.canvas.width()/e.canvas.height()),this._super(e,t)},setClipPlanes:function(e,t){this.near=e,this.far=t,this.camera.near=this.near,this.camera.far=this.far,this.camera.projectionMatrix=this.calculatePerspective()},setAspectRatio:function(e){this.aspect=e,this.camera.projectionMatrix=this.calculatePerspective()},setVerticalFieldOfView:function(e){this.fov=e,this.camera.projectionMatrix=this.calculatePerspective()},setHorizontalFieldOfView:function(e){e=2*e*Math.PI/360;var t=Math.tan(e/2),i=t/this.aspect;this.fov=2*Math.atan(i)*180/Math.PI,this.camera.projectionMatrix=this.calculatePerspective()},getVerticalFieldOfView:function(){return 180*this.camera.getFieldOfView()/Math.PI},getHorizontalFieldOfView:function(){var e=Math.tan(.5*this.camera.getFieldOfView()),t=this.aspect*e,i=2*Math.atan(t);return 180*i/Math.PI},calculatePerspective:function(){var e=mat4.create(),t=this.aspect;return t||(t=1),mat4.perspective(e,2*this.fov*Math.PI/360,t,this.near,this.far),e}}),OrthoCamera=CameraComponent.extend({init:function(e,t,i,n,r,s){e||(e=0),t||(t=512),i||(i=512),n||(n=0),r||(r=-100),s||(s=100);var a=mat4.ortho(mat4.create(),e,t,i,n,r,s);this._super(mat4.identity(mat4.create()),a)},type:function(){return"OrthoCamera"}}),MeshComponent=Component.extend({init:function(e){this.mesh=e,this._super()},type:function(){return"MeshComponent"},instantiate:function(){var e=this._super();return e.mesh=this.mesh,e}}),RendererComponent=Component.extend({init:function(){this._super(),this.castShadows=!0,this.receiveShadows=!0},type:function(){return"RendererComponent"},instantiate:function(){var e=this._super();return e.castShadows=this.castShadows,e.receiveShadows=this.receiveShadows,e}}),MeshRendererComponent=RendererComponent.extend({init:function(){this.meshRenderers=[],this._super()},type:function(){return"MeshRendererComponent"},excluded:function(){return this._super().concat(["meshRenderers"])},createRenderer:function(e,t,i,n){return new SubmeshRenderer(e,t,i,n)},onStart:function(e,t){this.updateRenderers(e,t)},addRenderers:function(e){var t=this;this.node.onEachComponent(function(i){if(i instanceof MeshComponent)for(var n in i.mesh.submeshes){var r=i.mesh.submeshes[n],s=i.mesh.getMaterial(r.materialIndex);if(s){var a=t.createRenderer(e,t.node.transform.absolute,r,s);t.getScene().dynamicSpace.addRenderer(a),t.meshRenderers.push(a),t.enabled||(a.visible=!1)}else console.warn(" *** Failed to to find submesh material in node: ",i.node.name,i.node)}})},removeRenderers:function(){for(var e=0;e<this.meshRenderers.length;e++)this.getScene().dynamicSpace.removeRenderer(this.meshRenderers[e])},updateRenderers:function(e,t){this.removeRenderers(),this.addRenderers(e,t)},onEnd:function(){this.removeRenderers()},onUpdateTransform:function(e){for(var t=0;t<this.meshRenderers.length;t++)this.meshRenderers[t].layer=this.node.layer,this.meshRenderers[t].castShadows=this.castShadows,this.meshRenderers[t].receiveShadows=this.receiveShadows,this.meshRenderers[t].setMatrix(e)},onEnable:function(){for(var e=0;e<this.meshRenderers.length;e++)this.meshRenderers[e].visible=!0},onDisable:function(){for(var e=0;e<this.meshRenderers.length;e++)this.meshRenderers[e].visible=!1},getBoundingBox:function(e){for(var t=new BoundingBox,i=0;i<this.meshRenderers.length;i++)(!e||this.meshRenderers[i].visible)&&t.encapsulateBox(this.meshRenderers[i].globalBoundingBox);return t},getBoundingSphere:function(e){for(var t=new BoundingSphere,i=0;i<this.meshRenderers.length;i++)(!e||this.meshRenderers[i].visible)&&t.encapsulateSphere(this.meshRenderers[i].globalBoundingSphere);return t},setTransparency:function(e){e=!!e;for(var t=0;t<this.meshRenderers.length;t++)this.meshRenderers[t].transparent=e},getSubmeshRenderer:function(e){for(var t=0;t<this.meshRenderers.length;t++)if(this.meshRenderers[t].submesh===e)return this.meshRenderers[t];return!1}}),SkyboxComponent=Component.extend({init:function(){this._super()},setup:function(e,t,i){function n(e,t,i,n,r){var s=new Submesh;s.positions=[],s.normals=[],s.texCoords2D=[[]],vec3.sub(c,t,e),vec3.sub(u,n,e),vec3.cross(h,c,u),vec3.negate(h,h),vec3.normalize(h,h);var a=s.positions.length/3;s.positions.push(e[0],e[1],e[2]),s.normals.push(h[0],h[1],h[2]),s.texCoords2D[0].push(0,1),s.positions.push(t[0],t[1],t[2]),s.normals.push(h[0],h[1],h[2]),s.texCoords2D[0].push(1,1),s.positions.push(i[0],i[1],i[2]),s.normals.push(h[0],h[1],h[2]),s.texCoords2D[0].push(1,0),s.positions.push(n[0],n[1],n[2]),s.normals.push(h[0],h[1],h[2]),s.texCoords2D[0].push(0,0),s.faces.push(a+0,a+3,a+2),s.faces.push(a+2,a+1,a+0),s.recalculateBounds(),o.addSubmesh(s,r)}this.meshNode=new Node("Skybox");var r=[0,0,0],s=1;t.scene&&t.scene.camera&&t.scene.camera.far&&(s=Math.sqrt(t.scene.camera.far*t.scene.camera.far/3));var a=[s,s,s],o=new Mesh,h=vec3.create(),c=vec3.create(),u=vec3.create(),l=[vec3.fromValues(r[0]-a[0],r[1]-a[1],r[2]-a[2]),vec3.fromValues(r[0]+a[0],r[1]-a[1],r[2]-a[2]),vec3.fromValues(r[0]+a[0],r[1]+a[1],r[2]-a[2]),vec3.fromValues(r[0]-a[0],r[1]+a[1],r[2]-a[2]),vec3.fromValues(r[0]-a[0],r[1]-a[1],r[2]+a[2]),vec3.fromValues(r[0]+a[0],r[1]-a[1],r[2]+a[2]),vec3.fromValues(r[0]+a[0],r[1]+a[1],r[2]+a[2]),vec3.fromValues(r[0]-a[0],r[1]+a[1],r[2]+a[2])],d={ambient:new UniformColor(new Color),diffuse:new UniformColor(new Color)};n(l[3],l[2],l[1],l[0],new Material(e.addShaderSource("diffuse"),d,[new Sampler("diffuse0",e.texturesManager.addDescriptor(i[0]))])),n(l[6],l[7],l[4],l[5],new Material(e.addShaderSource("diffuse"),d,[new Sampler("diffuse0",e.texturesManager.addDescriptor(i[1]))])),n(l[7],l[3],l[0],l[4],new Material(e.addShaderSource("diffuse"),d,[new Sampler("diffuse0",e.texturesManager.addDescriptor(i[2]))])),n(l[2],l[6],l[5],l[1],new Material(e.addShaderSource("diffuse"),d,[new Sampler("diffuse0",e.texturesManager.addDescriptor(i[3]))])),n(l[0],l[1],l[5],l[4],new Material(e.addShaderSource("diffuse"),d,[new Sampler("diffuse0",e.texturesManager.addDescriptor(i[4]))])),n(l[7],l[6],l[2],l[3],new Material(e.addShaderSource("diffuse"),d,[new Sampler("diffuse0",e.texturesManager.addDescriptor(i[5]))])),this.meshNode.addComponent(new MeshComponent(o));var f=this.meshNode.addComponent(new MeshRendererComponent);this.node.addNode(this.meshNode),f.castShadows=!1,f.disable(),f.addRenderers(t.context,t)},type:function(){return"SkyboxComponent"}}),TextRendererComponent=MeshRendererComponent.extend({type:function(){return"TextRendererComponent"}}),TextComponent=MeshComponent.extend({init:function(e){this._super(new Mesh),this.context=!1,this.material=!1,this.texture=!1,this.sampler=new Sampler("diffuse0",null),this.color=new Color(0,0,0,1),this.fontSize=56,this.style="normal",this.variant="normal",this.weight="normal",this.family="monospace",this.backgroundColor=new Color(0,0,0,0),this.outline=!0,this.outlineColor=new Color(1,1,1,1),this.outlineWidth=5,this.setText(e)},excluded:function(){return this._super().concat(["material","texture","sampler","context"])},type:function(){return"TextComponent"},applyTextStyles:function(e){this.outline&&(e.strokeStyle=this.outlineColor.toString(),e.lineWidth=this.outlineWidth),e.fillStyle=this.color.toString(),e.textBaseline="middle",e.textAlign="center",e.font=this.font},updateFont:function(){this.font="","normal"!=this.style&&(this.font+=this.style+" "),"normal"!=this.variant&&(this.font+=this.variant+" "),"normal"!=this.weight&&(this.font+=this.weight+" "),this.font+=this.fontSize+"px "+this.family},updateText:function(){if(this.context&&0!=this.text.length){var e=this.node.getComponent(TextRendererComponent);if(e){this.updateFont();var t=document.createElement("canvas"),i=t.getContext("2d");this.applyTextStyles(i),t.width=nextHighestPowerOfTwo(i.measureText(this.text).width),t.height=nextHighestPowerOfTwo(2*this.fontSize),i.fillStyle=this.backgroundColor.toString(),i.fillRect(0,0,t.width,t.height),this.applyTextStyles(i),this.outline&&i.strokeText(this.text,t.width/2,t.height/2),i.fillText(this.text,t.width/2,t.height/2),this.texture.setImage(this.context,t);var n=1,r=t.width/t.height,s=this.mesh.submeshes[0];if(s.positions[0]=-.5*r,s.positions[1]=-.5*n,s.positions[3]=-.5*r,s.positions[4]=.5*n,s.positions[6]=.5*r,s.positions[7]=.5*n,s.positions[9]=.5*r,s.positions[10]=-.5*n,s.recalculateBounds(),e.meshRenderers.length>0){var a=e.meshRenderers[0];a.buffer.update("position",s.positions)}}}},onStart:function(e,t){this.context=e,this.material=new Material(t.assetsManager.addShaderSource("transparent"),{diffuse:new UniformColor({r:1,g:1,b:1,a:1})},[this.sampler]),this.material.shader.requirements.transparent=!0,this.material.name="TextComponentMaterial",this.texture=new Texture(e),this.texture.mipmapped=!0,this.texture.clampToEdge=!0,this.sampler.texture=this.texture;var i=new Submesh;i.positions=new Float32Array(12),i.normals=[0,0,1,0,0,1,0,0,1,0,0,1],i.texCoords2D=[[0,0,0,1,1,1,1,0]],i.faces=[0,1,2,0,2,3],i.recalculateBounds(),this.mesh.addSubmesh(i,this.material),this.updateText()},setText:function(e){this.text=String(e),this.updateText()}}),Controller=Component.extend({init:function(){this._super(),this.delta=vec2.create(),this.dragDelta=vec2.create(),this.position=!1,this.oldPosition=!1,this.startDragPosition=!1,this.buttons=[!1,!1,!1]},excluded:function(){return this._super().concat(["delta","dragDelta","position","oldPosition","startDragPosition","buttons","keyStates"])},type:function(){return"Controller"},onAddScene:function(e){e.scene.engine.input.registerController(this)},onRemoveScene:function(e){e.scene.engine.input.unregisterController(this)},bind:function(e,t,i){this.node&&e&&t&&i&&this.node.scene.engine.input.bind(e,t,i)},getPriority:function(){return 0},onStart:function(e){this.canvas=e.canvas,this.buttons=[!1,!1,!1]},onUpdate:function(){},onKeyStateChange:function(){},onKeyDown:function(){},onKeyUp:function(){},onButtonDown:function(){},onButtonUp:function(){},onClick:function(){},onMouseMove:function(){},onMouseDown:function(e,t){this.buttons[t]=!0},onMouseUp:function(e,t){this.buttons[t]=!1}}),FlightController=Controller.extend({init:function(){this._super(),this.rotation=vec3.create(),this.velocity=vec3.fromValues(0,0,0),this.angularVelocity=vec3.fromValues(0,0,0),this.acceleration=.2,this.deceleration=.2,this.friction=.01,this.rotationAcceleration=.001,this.rotationFriction=.1},type:function(){return"FlightController"},onAdd:function(){this._super(),this.bind("W","accelerate",this),this.bind("S","decelerate",this),this.bind("A","strafeLeft",this),this.bind("D","strafeRight",this),this.bind("up_arrow","accelerate",this),this.bind("down_arrow","decelerate",this),this.bind("left_arrow","strafeLeft",this),this.bind("right_arrow","strafeRight",this)},accelerate:function(e){this.addLocalImpulse([0,0,-this.acceleration*e])},decelerate:function(e){this.addLocalImpulse([0,0,this.deceleration*e])},strafeLeft:function(e){this.addLocalImpulse([-this.deceleration*e,0,0])},strafeRight:function(e){this.addLocalImpulse([this.deceleration*e,0,0])},addLocalImpulse:function(e){var t=vec3.create(),i=quat.create();quat.fromMat4(i,this.node.transform.absolute),vec3.transformQuat(t,e,i),vec3.add(this.velocity,this.velocity,t)},onStep:function(){return!0},onUpdate:function(e,t){this._super(e,t);var i=e.fps.getDelta(),n=1+this.friction*i;vec3.scale(this.velocity,this.velocity,1/n);var r=1+this.rotationFriction*i;vec3.scale(this.angularVelocity,this.angularVelocity,1/r);var s=vec3.scale(vec3.create(),this.velocity,i),a=vec3.scale(vec3.create(),this.angularVelocity,i);vec3.add(this.rotation,this.rotation,a);var o=quat.create();quat.rotateY(o,o,this.rotation[1]),quat.rotateX(o,o,this.rotation[0]);var h=mat4.translation(vec3.create(),this.node.transform.relative),c=vec3.add(vec3.create(),s,h);this.onStep(h,c,o)&&mat4.fromRotationTranslation(this.node.transform.relative,o,c)},onMouseMove:function(e,t,i){if(0===t){var n=vec3.create(),r=this.rotationAcceleration;vec3.scale(n,[-i[1],-i[0],0],r),vec3.add(this.angularVelocity,this.angularVelocity,n)}}}),OrbitController=FlightController.extend({init:function(){this._super(),this.target=new TypeReference("Transform"),this.panButton=2,this.rotateButton=0,this.position=vec3.create(),this.velocity=vec3.create(),this.pan=vec3.create(),this.minimumPan=[-100,-100,-100],this.maximumPan=[100,100,100],this.panXAxis=[1,0,0],this.panYAxis=[0,0,1],this.panSpeed=.05,this.rotation=vec3.create(),this.angularVelocity=vec3.create(),this.minimumPitch=-Math.PI/2.2,this.maximumPitch=0,this.rotationAcceleration=.012,this.rotationFriction=.1,this.lastPinch=0,this.zoomSpeed=1,this.doZoomIn=!1,this.doZoomOut=!1,this.distance=5,this.minimumDistance=2.5,this.maximumDistance=7.5,this.distanceSteps=4,this.direction=vec3.create(),this.cameraPosition=vec3.create(),this.targetPosition=vec3.create(),this.lookat=mat4.create()},excluded:function(){return this._super().concat(["velocity","angularVelocity","doZoomIn","doZoomOut","direction","cameraPosition","targetPosition","lookat"])},type:function(){return"OrbitController"},onAdd:function(){this._super(),this.bind("W","zoomIn",this),this.bind("S","zoomOut",this),this.bind("A","rotateLeft",this),this.bind("D","rotateRight",this),this.bind("E","rotateUp",this),this.bind("Q","rotateDown",this)},getZoom:function(){var e=this.distance-this.minimumDistance,t=this.maximumDistance-this.minimumDistance;return e/t},setZoom:function(e){e=Math.max(0,e);var t=this.maximumDistance-this.minimumDistance;this.distance=Math.min(this.minimumDistance+t*e,this.maximumDistance)},setDistance:function(e){this.distance=Math.min(Math.max(e,this.minimumDistance),this.maximumDistance)},zoomIn:function(e){this.enabled&&(e||(e=1),this.distance-=e*this.zoomSpeed*(this.maximumDistance-this.minimumDistance)/this.distanceSteps,this.distance<this.minimumDistance&&(this.distance=this.minimumDistance))},zoomOut:function(e){this.enabled&&(e||(e=1),this.distance+=e*this.zoomSpeed*(this.maximumDistance-this.minimumDistance)/this.distanceSteps,this.distance>this.maximumDistance&&(this.distance=this.maximumDistance))},rotateLeft:function(e){this.accelerate([0,-this.rotationAcceleration,0],e)},rotateRight:function(e){this.accelerate([0,this.rotationAcceleration,0],e)},rotateUp:function(e){this.accelerate([this.rotationAcceleration,0,0],e)},rotateDown:function(e){this.accelerate([-this.rotationAcceleration,0,0],e)},accelerate:function(e,t){this.enabled&&(vec3.scale(e,e,t),vec3.add(this.angularVelocity,this.angularVelocity,e))},onUpdate:function(e,t){if(this._super(e,t),!this.target.isNull()){vec3.add(this.rotation,this.rotation,this.angularVelocity);var i=quat.create();quat.rotateY(i,i,this.rotation[1]),quat.rotateX(i,i,this.rotation[0]),vec3.set(this.direction,0,0,1),vec3.transformQuat(this.direction,this.direction,i),vec3.scale(this.direction,this.direction,this.distance),mat4.translation(this.targetPosition,this.target.value.absolute),vec3.add(this.cameraPosition,this.targetPosition,this.direction),vec3.add(this.targetPosition,this.targetPosition,this.pan),vec3.add(this.cameraPosition,this.cameraPosition,this.pan),mat4.lookAt(this.lookat,this.cameraPosition,this.targetPosition,[0,1,0]),mat4.invert(this.node.transform.absolute,this.lookat),this.node.calculateRelativeFromAbsolute(),this.doZoomIn&&this.zoomIn(),this.doZoomOut&&this.zoomOut()}},onMouseMove:function(e,t,i){this.rotateButton!==!1&&t==this.rotateButton&&this.rotate(i[1],i[0]),this.panButton!==!1&&t==this.panButton&&this.move(i[0],i[1])},onPan:function(e,t){this.move(t[0],t[1])},rotate:function(e,t){var i=vec3.create();vec3.scale(i,[-e,-t,0],this.rotationAcceleration),vec3.add(this.rotation,this.rotation,i),this.rotation[0]=Math.max(this.minimumPitch,this.rotation[0]),this.rotation[0]=Math.min(this.maximumPitch,this.rotation[0])},move:function(e,t){var i=vec3.create();vec3.scale(i,this.panXAxis,-e),vec3.add(i,i,vec3.scale(vec3.create(),this.panYAxis,-t)),i=vec3.scale(i,i,this.distance/900);var n=quat.fromMat4(quat.create(),this.node.transform.absolute),r=vec3.fromValues(0,0,1);vec3.transformQuat(r,r,n);var s=Math.atan2(r[2],r[0]);s-=Math.PI/2,quat.identity(n),quat.rotateY(n,n,s),quat.conjugate(n,n),quat.normalize(n,n),vec3.transformQuat(i,i,n),vec3.add(this.pan,this.pan,i),this.pan[0]=Math.max(this.pan[0],this.minimumPan[0]),this.pan[1]=Math.max(this.pan[1],this.minimumPan[1]),this.pan[2]=Math.max(this.pan[2],this.minimumPan[2]),this.pan[0]=Math.min(this.pan[0],this.maximumPan[0]),this.pan[1]=Math.min(this.pan[1],this.maximumPan[1]),this.pan[2]=Math.min(this.pan[2],this.maximumPan[2])},onPinch:function(e,t){t=this.getZoom()+(1-t),this.setZoom(t)},onRotate:function(e,t){var i=t*(Math.PI/180);this.rotation[1]=this.rotation[1]+i},onMouseWheel:function(e,t,i){0>i?this.zoomIn():this.zoomOut()}}),SmoothOrbitController=OrbitController.extend({init:function(){this._super(),this.speed=5,this.currentRotation=vec2.create(),this.currentDistance=this.distance,this.tmpRotation=quat.create()},excluded:function(){return this._super().concat(["currentRotation","currentDistance","tmpRotation"])},type:function(){return"SmoothOrbitController"},onUpdate:function(e){if(!this.target.isNull()){var t=e.fps.getDelta()/1e3*this.speed;this.currentRotation[0]=lerp(this.currentRotation[0],this.rotation[0],t),this.currentRotation[1]=lerp(this.currentRotation[1],this.rotation[1],t),this.currentDistance=lerp(this.currentDistance,this.distance,t),quat.identity(this.tmpRotation),quat.rotateY(this.tmpRotation,this.tmpRotation,this.currentRotation[1]),quat.rotateX(this.tmpRotation,this.tmpRotation,this.currentRotation[0]),vec3.set(this.direction,0,0,1),vec3.transformQuat(this.direction,this.direction,this.tmpRotation),vec3.scale(this.direction,this.direction,this.currentDistance),mat4.translation(this.targetPosition,this.target.value.absolute),vec3.add(this.cameraPosition,this.targetPosition,this.direction),vec3.add(this.targetPosition,this.targetPosition,this.pan),vec3.add(this.cameraPosition,this.cameraPosition,this.pan),mat4.lookAt(this.lookat,this.cameraPosition,this.targetPosition,[0,1,0]),mat4.invert(this.node.transform.absolute,this.lookat),this.node.calculateRelativeFromAbsolute(),this.doZoomIn&&this.zoomIn(),this.doZoomOut&&this.zoomOut()}}}),LineRendererComponent=Component.extend({init:function(e){this._super(),this.shader=!1,this.color=new UniformColor(e instanceof Color?e:new Color(.5,.5,.5,1)),this.faces=[],this.vertices=[],this.buffer=!1,this.updateBuffer=!1,this.depthTest=!1},type:function(){return"LineRendererComponent"},excluded:function(){return this._super().concat(["buffer","updateBuffer"])},initialize:function(e){this.shader=this.node.scene.engine.assetsManager.addShaderSource("Transparent"),this.node.scene.engine.assetsManager.load();var t=new Texture(e);t.clearImage(e,[255,255,255,255]),this.samplers=[new Sampler("diffuse0",t)]},build:function(e){return 0==this.vertices.length||0==this.faces.length?!1:(this.buffer=new RenderBuffer(e,this.faces,e.gl.DYNAMIC_DRAW),void this.buffer.add("position",this.vertices,3))},clear:function(e){this.faces=[],this.vertices=[];for(var t in this.buffer.buffers)e.gl.deleteBuffer(this.buffer.buffers[t]);this.buffer=!1},addLine:function(e,t){var i=this.vertices.length/3,n={vertexOffset:i};return this.vertices.push(e[0],e[1],e[2],t[0],t[1],t[2]),this.faces.push(i,i+1),n},updateLine:function(e,t,i){if(this.buffer&&this.buffer.buffers.position){var n=function(e,t,i){e[3*t+0]=i[0],e[3*t+1]=i[1],e[3*t+2]=i[2]};n(this.vertices,e.vertexOffset+0,t),n(this.vertices,e.vertexOffset+1,i),this.updateBuffer=!0}},addTriangle:function(e,t,i){this.addLine(e,t),this.addLine(t,i),this.addLine(i,e)},addBox:function(e){if(!(e instanceof BoundingBox))throw"LineRendererComponent.addBox expects box to be of type BoundingBox";this.addLine(e.min,[e.min[0],e.min[1],e.max[2]]),this.addLine(e.min,[e.min[0],e.max[1],e.min[2]]),this.addLine(e.min,[e.max[0],e.min[1],e.min[2]]),this.addLine(e.max,[e.max[0],e.min[1],e.max[2]]),this.addLine(e.max,[e.max[0],e.max[1],e.min[2]]),this.addLine(e.max,[e.min[0],e.max[1],e.max[2]]),this.addLine([e.min[0],e.max[1],e.min[2]],[e.min[0],e.max[1],e.max[2]]),this.addLine([e.min[0],e.max[1],e.max[2]],[e.min[0],e.min[1],e.max[2]]),this.addLine([e.min[0],e.min[1],e.max[2]],[e.max[0],e.min[1],e.max[2]]),this.addLine([e.max[0],e.min[1],e.max[2]],[e.max[0],e.min[1],e.min[2]]),this.addLine([e.max[0],e.min[1],e.min[2]],[e.max[0],e.max[1],e.min[2]]),this.addLine([e.max[0],e.max[1],e.min[2]],[e.min[0],e.max[1],e.min[2]])},addGrid:function(e,t,i){var n=[t[0]/2,t[1]/2];i||(i=[1,1]);for(var r=-n[0];r<=n[0];r++)this.addLine([r*i[0]+e[0],e[1],-n[1]*i[1]+e[2]],[r*i[0]+e[0],e[1],n[1]*i[1]+e[2]]);for(r=-n[1];r<=n[1];r++)this.addLine([-n[0]*i[0]+e[0],e[1],r*i[1]+e[2]],[n[0]*i[0]+e[0],e[1],r*i[1]+e[2]])},onStart:function(e){this.initialize(e),this.build(e)},onPostRender:function(e){if(this.enabled&&this.buffer!==!1){this.updateBuffer&&this.build(e);var t={modelview:new UniformMat4(e.modelview.top()),projection:new UniformMat4(e.projection.top()),diffuse:this.color};this.shader.use(t),this.shader.bindSamplers(this.samplers),this.shader.requirements.apply(this.buffer);var i=e.gl;this.depthTest&&(i.enable(i.DEPTH_TEST),i.depthFunc(i.LESS),i.depthMask(!0));var n=[];for(var r in this.buffer.buffers){i.bindBuffer(i.ARRAY_BUFFER,this.buffer.buffers[r]);var s=i.getAttribLocation(this.shader.program,r);-1!=s&&(i.enableVertexAttribArray(s),n.push(s),i.vertexAttribPointer(s,this.buffer.buffers[r].itemSize,i.FLOAT,!1,0,0))}i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,this.buffer.facesBuffer),i.drawElements(i.LINES,this.buffer.facesBuffer.numItems,i.UNSIGNED_SHORT,0);for(var a in n)i.disableVertexAttribArray(n[a]);this.depthTest&&i.disable(i.DEPTH_TEST)}}}),Billboard=Component.extend({init:function(e,t,i){this._super(),this.cameraToLookAt=e,this.smoothRotation=t===!0,this.rotationSpeed=4,i&&(this.rotationSpeed=i),this.cacheMat4=[mat4.create()],this.cacheQuat=[quat.create(),quat.create()],this.cacheVec3=[vec3.create(),vec3.create()]},type:function(){return"Billboard"},onUpdate:function(e){if(this.enabled){if(!(this.cameraToLookAt instanceof Camera))throw"Billboard.cameraToLookAt is not an instance of Camera";var t=e.fps.getDelta()/1e3,i=mat4.invert(this.cacheMat4[0],this.cameraToLookAt.viewMatrix),n=quat.fromMat4(this.cacheQuat[0],i);if(this.smoothRotation){var r=quat.fromMat4(this.cacheQuat[1],this.node.transform.relative);quat.slerp(n,r,n,this.rotationSpeed*t)}quat.normalize(n,n);var s=mat4.translation(this.cacheVec3[0],this.node.transform.relative),a=mat4.getScale(this.cacheVec3[1],this.node.transform.relative);mat4.fromRotationTranslationScale(this.node.transform.relative,n,s,a)}}}),VerticalBillboard=Billboard.extend({init:function(e,t,i){this._super(e,t,i)},type:function(){return"VerticalBillboard"},onUpdate:function(e){if(!(this.cameraToLookAt instanceof Camera))throw"VerticalBillboard.cameraToLookAt is not an instance of Camera";var t=e.fps.getDelta()/1e3,i=mat4.invert(this.cacheMat4[0],this.cameraToLookAt.viewMatrix),n=quat.fromMat4(this.cacheQuat[0],i);if(quat.multiply(n,n,quat.euler(this.cacheQuat[1],0,180,0)),this.smoothRotation){n[0]=0,n[2]=0,quat.normalize(n,n);var r=quat.fromMat4(this.cacheQuat[1],this.node.transform.relative);quat.slerp(n,r,n,this.rotationSpeed*t)}quat.normalize(n,n);var s=mat4.translation(this.cacheVec3[0],this.node.transform.relative),a=mat4.getScale(this.cacheVec3[1],this.node.transform.relative);mat4.fromRotationTranslationScale(this.node.transform.relative,n,s,a)}}),Collider=Component.extend({init:function(){this._super()},type:function(){return"Collider"},onStart:function(){this.getScene().dynamicSpace.addCollider(this)},onEnd:function(){this.getScene().dynamicSpace.removeCollider(this)},rayTest:function(){return!1}}),MeshCollider=Collider.extend({init:function(){this._super()},type:function(){return"MeshCollider"},rayTest:function(e,t,i){if(!this.enabled)return!1;var n=this.node.getComponent(MeshRendererComponent);if(!n)return!1;var r=n.meshRenderers,s=vec3.create(),a=vec3.create(),o=vec3.create(),h=!1;for(var c in r)if((i||r[c].visible)&&e.intersectBoundingVolume(r[c].globalBoundingBox)){var u=e.clone(),l=mat4.invert(mat4.create(),r[c].matrix);u.transform(l);var d=r[c].submesh.faces,f=r[c].submesh.positions;if(t){var m=this;t.addCallback=function(e){vec3.transformMat4(e.point,e.point,r[c].matrix),e.submesh=r[c].submesh,e.collider=m,e.node=m.node}}for(var p=0;p<d.length;p+=3)if(s[0]=f[3*d[p]],s[1]=f[3*d[p]+1],s[2]=f[3*d[p]+2],a[0]=f[3*d[p+1]],a[1]=f[3*d[p+1]+1],a[2]=f[3*d[p+1]+2],o[0]=f[3*d[p+2]],o[1]=f[3*d[p+2]+1],o[2]=f[3*d[p+2]+2],u.intersectTriangle(s,a,o,t)){if(!t)return!0;h=!0;break}if(t)t.addCallback=!1;else if(h)return!0}return h}}),LargeMeshCollider=Collider.extend({init:function(){this._super(),this.tree=!1,this.meshes=[],this.damaged=!1,this.invMat=mat4.create()},type:function(){return"LargeMeshCollider"},excluded:function(){return this._super().concat(["tree","meshes"])},isComplete:function(){return this.tree!==!1&&0==this.meshes.length},onAdd:function(){function e(e){var i=null;return t.onEachChild(function(t){return t.localCollisionID===e?(i=t,!0):void 0}),i}if(this._super(),this.damaged){var t=this.node;for(var i in this.tree.nodes){var n=this.tree.nodes[i].localCollisionID;0>n||(this.tree.nodes[i]=e(n))}this.damaged=!1}},clone:function(){var e=new LargeMeshCollider;return this.tree&&(e.tree=this.tree.clone(),e.damaged=!0),e},rayTest:function(e,t){if(!this.enabled||!this.isComplete())return!1;var i=e.clone();mat4.invert(this.invMat,this.node.transform.absolute),i.transform(this.invMat);var n=this.tree.getNearestRayCollision(i,e);if(1/0==n.t||n.t==-1/0)return!1;if(t&&n){var r=i.getPointOnRay(n.t);vec3.transformMat4(r,r,this.node.transform.absolute),t.hits.push({point:r,collider:this,submesh:n.submesh,node:n.node,normal:n.normal})}return n!==!1}}),Light=Component.extend({init:function(){this._super(),this.direction=vec3.fromValues(0,-1,0),this.color=new Color,this.intensity=1,this.shadowIntensity=.4,this.shadowBlurKernelSize=5,this.shadowCasting=!1,this.shadowMask=4294967295},type:function(){return"Light"},setLightDirection:function(e){vec3.copy(this.direction,e),vec3.normalize(this.direction,this.direction)},onAddScene:function(e){e.scene.lights.push(this)},onRemoveScene:function(e){for(var t=e.scene.lights,i=0;i<t.length;i++)t[i]==this&&(t.splice(i,1),i--)}}),Transform=Component.extend({init:function(e){this._super(),this.relative=e?e:mat4.identity(mat4.create()),this.absolute=mat4.copy(mat4.create(),this.relative)},onAdd:function(e){e.transform=this},type:function(){return"Transform"},excluded:function(){return this._super().concat(["absolute"])},calculateRelativeFromAbsolute:function(e){if(!e)return void mat4.copy(this.relative,this.absolute);var t=mat4.invert(mat4.create(),e);mat4.multiply(this.relative,this.absolute,t)},getPosition:function(e){return e||(e=vec3.create()),mat4.translation(e,this.absolute)},setPosition:function(e){mat4.fromRotationTranslation(this.relative,quat.fromMat4(quat.create(),this.relative),e)},getRotation:function(e){return e||(e=quat.create()),quat.fromMat4(e,this.absolute)},translate:function(e){this.relative=mat4.translate(this.relative,this.relative,e)},rotate:function(e,t){this.relative=mat4.rotate(this.relative,this.relative,e,t)},scale:function(e){this.relative=mat4.scale(this.relative,this.relative,e)},clone:function(){var e=new Transform;return e.relative=mat4.clone(this.relative),e.absolute=mat4.clone(this.absolute),e}}),Resource=Component.extend({init:function(){this._super(),this.descriptor=!1},excluded:function(){return this._super().concat(["resource"])},type:function(){return"ResourceComponent"}}),TextureResource=Resource.extend({init:function(){this._super(),this.descriptor=new TextureDescriptor,this.texture=!1,this.engine=!1},excluded:function(){return this._super().concat(["texture","engine"])},type:function(){return"TextureResource"},load:function(e){var t=this;this.texture=this.engine.assetsManager.texturesManager.addDescriptor(this.descriptor),this.engine.assetsManager.load(function(){t.onLoaded(),e&&e(t.engine.context,t.engine)})},onStart:function(e,t){this.engine=t,this.load()},onLoaded:function(){}}),ModelResource=Resource.extend({init:function(){this._super(),this.descriptor=new ModelDescriptor,this.model=!1},type:function(){return"ModelResource"},excluded:function(){return this._super().concat(["model","engine"])},load:function(e){if(this.descriptor.source){var t=this;this.model=this.engine.assetsManager.modelsManager.addDescriptor(this.descriptor),this.engine.assetsManager.load(function(){t.node.addNode(t.model),t.onLoaded(),e&&e(t.engine.context,t.engine)})}},onStart:function(e,t){this.engine=t,this.load()},onLoaded:function(){}}),MaterialResource=Resource.extend({init:function(){this._super(),this.descriptor=new MaterialSourceDescriptor,this.material=!1,this.engine=!1},excluded:function(){return this._super().concat(["material","engine"])},type:function(){return"MaterialResource"},load:function(e){var t=this;this.texture=this.engine.assetsManager.materialSourcesManager.addDescriptor(this.descriptor),this.engine.assetsManager.load(function(){t.onLoaded(),e&&e(t.engine.context,t.engine)})},onStart:function(e,t){this.engine=t,this.load()
  },onLoaded:function(){}}),Descriptor=Serializable.extend({init:function(){this._super(),this.source="",this.parentDescriptor=!1},included:function(){return!0},excluded:function(){return this._super().concat(["parentDescriptor"])},type:function(){return"Descriptor"},equals:function(e){if(this.type()!=e.type())return!1;if(this.getFullPath()!=e.getFullPath())return!1;if(this.parentDescriptor&&e.parentDescriptor){if(!this.parentDescriptor.equals(e.parentDescriptor))return!1}else if(this.parentDescriptor!=e.parentDescriptor)return!1;return!0},getCurrentRelativeDirectory:function(){return 0==this.source.length?"":this.source.substring(0,this.source.lastIndexOf("/")+1)},getCurrentDirectory:function(){var e="";return this.parentDescriptor&&(e=this.parentDescriptor.getCurrentDirectory()),e+this.getCurrentRelativeDirectory()},getParentDirectory:function(){return this.parentDescriptor?this.parentDescriptor.getCurrentDirectory():""},getFullPath:function(){var e=this.getParentDirectory()+this.source;return e}}),TextDescriptor=Descriptor.extend({init:function(e){this._super(),this.source=e},type:function(){return"TextDescriptor"},equals:function(e){return this._super(e)?this.source==e.source:!1}}),FontDescriptor=Descriptor.extend({init:function(e,t,i){this._super(),this.fontTexturePaths=e,this.fontDataPath=t,this.materialSourceDescriptor=i},type:function(){return"FontDescriptor"},equals:function(e){if(!this._super(e))return!1;if(this.fontTexturePaths.length!=e.fontTexturePaths)return!1;for(var t in this.fontTexturePaths)if(this.fontTexturePaths[t]!=e.fontTexturePaths[t])return!1;if(this.fontDataPath!=e.fontDataPath)return!1;if(this.materialSourceDescriptor&&e.materialSourceDescriptor){if(!this.materialSourceDescriptor.equals(e.materialSourceDescriptor))return!1}else if(this.materialSourceDescriptor!=e.materialSourceDescriptor)return!1;return!0},getFullTexturePaths:function(){var e=this.getParentDirectory(),t=[];for(var i in this.fontTexturePaths)t.push(e+this.fontTexturePaths[i]);return t},getFullDataPath:function(){return this.getParentDirectory()+this.fontDataPath}}),FontSourceDescriptor=Descriptor.extend({init:function(e){this._super(),this.source=e},type:function(){return"FontSourceDescriptor"},equals:function(e){return this._super(e)?this.source==e.source:!1}}),FontSource=Descriptor.extend({init:function(e){this._super(),this.sourceDescriptor=e,this.font=!1},type:function(){return"FontSource"},equals:function(e){if(!this._super(e))return!1;if(this.sourceDescriptor&&e.sourceDescriptor){if(!this.ourceDescriptor.equals(e.sourceDescriptor))return!1}else if(this.sourceDescriptor!=e.sourceDescriptor)return!1;return!0}}),ModelDescriptor=Descriptor.extend({init:function(e){this._super(),this.source=e},type:function(){return"ModelDescriptor"}}),ShaderDescriptor=Descriptor.extend({init:function(e,t){this._super(),t?(this.vertexSource=e,this.fragmentSource=t):(this.vertexSource=e+".vert",this.fragmentSource=e+".frag")},type:function(){return"ShaderDescriptor"},equals:function(e){return this._super(e)?this.vertexSource==e.vertexSource&&this.fragmentSource==e.fragmentSource:!1},getVertexShaderPath:function(){var e=this.getParentDirectory()+this.vertexSource;return e},getFragmentShaderPath:function(){var e=this.getParentDirectory()+this.fragmentSource;return e}}),MaterialDescriptor=Descriptor.extend({init:function(e,t,i){this._super(),i||(i=[]),t||(t={}),this.shaderDescriptor=e,this.uniforms=t,this.textureDescriptors=i,this.materialResourceDescriptor=!1,this.requirements={}},type:function(){return"MaterialDescriptor"},equals:function(){return!1}}),MaterialSource=Descriptor.extend({init:function(e){this._super(),this.material=!1,this.sourceDescriptor=e},type:function(){return"MaterialSource"},equals:function(){return!1}}),MaterialSourceDescriptor=Descriptor.extend({init:function(e){this._super(),this.source=e},type:function(){return"MaterialSourceDescriptor"},equals:function(e){return this.source==e.source}}),TextureDescriptor=Descriptor.extend({init:function(e,t,i){this._super(),this.source=e,this.width=t,this.height=i},type:function(){return"TextureDescriptor"},equals:function(e){return this._super(e)?this.source==e.source&&this.width==e.width&&height==e.height:!1}}),EmptyNode=Serializable.extend({init:function(e){this._super(),this.name=e?e:"Empty Node",this.subnodes=[],this.components=[],this.scene=!1,this.parent=!1,this.layer=1,this.tags=[]},excluded:function(){return["parent","scene"]},type:function(){return"EmptyNode"},addNode:function(e){if(!(e instanceof EmptyNode))throw"addNode: The given node is not a subclass of EmptyNode";this.subnodes.push(e);var t=this;return e.parent=this,e.onEachChild(function(e){e.scene=t.scene}),e.scene&&e.onEachChildComponent(function(e){e.onAddScene(t),e.node.onAddComponent(e)}),e.onAdd(this),t.scene.engine&&e.onEachChildComponent(function(e){e.started||(t.scene.starting||t.scene.started===!1?t.scene.startingQueue.push(e):(e.onLoad(t.scene.engine.assetsManager,t.scene.engine),e.start(t.scene.engine.context,t.scene.engine),e.started=!0))}),e},removeNode:function(e){var t=this;t.scene.engine&&e.onEachChildComponent(function(e){e.started&&e.onEnd(t.scene.engine.context,t.scene.engine),e.started=!1}),e.onRemove(this),e.scene&&e.onEachChildComponent(function(e){e.onRemoveScene(t),e.node.onRemoveComponent(e)}),e.onEachChild(function(e){e.scene=!1}),e.parent=!1;for(var i in this.subnodes)if(this.subnodes[i]==e){this.subnodes.splice(i,1);break}return e},removeSubnodes:function(){var e=this.subnodes.slice(0);for(var t in e)this.removeNode(e[t])},addComponent:function(e){if(!e.type())throw"Unable to add a component that doesn't define it's type by returning it from type() method";return this.components.push(e),e.node=this,e.onAdd(this),this.scene&&(e.onAddScene(this),this.onAddComponent(e)),this.scene.engine&&!e.started&&(e.start(this.scene.engine.context,this.scene.engine),e.started=!0),e},removeComponent:function(e){for(var t in this.components)if(this.components[t]===e){this.components.splice(t,1);break}return this.scene.engine&&e.started&&(e.onEnd(this.scene.engine.context,this.scene.engine),e.started=!1),this.scene&&(e.onRemoveScene(this),this.onRemoveComponent(e)),e.onRemove(this),e.node=!1,e},removeComponentsByType:function(e){for(var t=[],i=0;i<this.components.length;i++)this.components[i]instanceof e&&(t.push(this.components[i]),this.components.splice(i,1),i--);for(var i in t)this.scene.engine&&t[i].started&&(t[i].onEnd(this.scene.engine.context,this.scene.engine),t[i].started=!1),this.scene&&(t[i].onRemoveScene(this),this.onRemoveComponent(t[i])),t[i].onRemove(this),t[i].node=!1;return t},getComponent:function(e){for(var t in this.components)if(this.components[t]instanceof e)return this.components[t];return!1},getComponents:function(e){var t=[];for(var i in this.components)this.components[i]instanceof e&&t.push(this.components[i]);return 0==t.length?!1:t},calculateRelativeFromAbsolute:function(){this.parent.transform&&this.transform.calculateRelativeFromAbsolute(this.parent.transform.absolute)},instantiate:function(){var e=new EmptyNode(this.name);e.isInstanced=!0,e.layer=this.layer,e.tags=this.tags.slice(0);for(var t in this.subnodes)e.addNode(this.subnodes[t].instantiate());for(var i in this.components)e.addComponent(this.components[i].instantiate());return e},enable:function(e){e?this.onEachComponent(function(e){e.enable()}):this.onEachChildComponent(function(e){e.enable()})},disable:function(e){e?this.onEachComponent(function(e){e.disable()}):this.onEachChildComponent(function(e){e.disable()})},onAdd:function(){},onRemove:function(){},onAddComponent:function(e){this.scene.components.push(e),e.onUpdate!=Component.prototype.onUpdate&&this.scene.updatedComponents.push(e),e.onPreRender!=Component.prototype.onPreRender&&this.scene.preRenderedComponents.push(e),e.onPostRender!=Component.prototype.onPostRender&&this.scene.postRenderedComponents.push(e)},onRemoveComponent:function(e){function t(e,t){var i=e.indexOf(t);return-1!=i?void e.splice(i,1):void 0}t(this.scene.components,e),e.onUpdate!=Component.prototype.onUpdate&&t(this.scene.updatedComponents,e),e.onPreRender!=Component.prototype.onPreRender&&t(this.scene.preRenderedComponents,e),e.onPostRender!=Component.prototype.onPostRender&&t(this.scene.postRenderedComponents,e)},onEachChild:function(e){if(e(this)===!0)return!0;for(var t in this.subnodes)if(this.subnodes[t].onEachChild(e)===!0)return!0},onEachChildExclusive:function(e){for(var t in this.subnodes)if(this.subnodes[t].onEachChild(e)===!0)return!0},onEachDirectChild:function(e){for(var t in this.subnodes)if(e(this.subnodes[t])===!0)return!0},onEachComponent:function(e){for(var t in this.components)if(e(this.components[t])===!0)return!0},onEachChildComponent:function(e){this.onEachChild(function(t){return t.onEachComponent(e)===!0?!0:void 0})},onEachChildComponentExclusive:function(e){this.onEachChildExclusive(function(t){return t.onEachComponent(e)===!0?!0:void 0})},getChildComponentsOfType:function(e){var t=[];return this.onEachChildComponent(function(i){i instanceof e&&t.push(i)}),t},find:function(e){var t=e.split("/");if(0==t.length)return!1;var i=this;if(""===t[0]){if(!this.scene)return!1;i=this.scene.root,t.shift()}for(var n in t)if(i=i.findChildWithName(t[n]),i===!1)return!1;return i},findChildWithName:function(e){for(var t in this.subnodes)if(this.subnodes[t].name===e)return this.subnodes[t];return!1},path:function(){for(var e=[],t=this;t;)e.push(t.name),t=t.parent;return"/"+e.reverse().join("/")}}),Node=EmptyNode.extend({init:function(e){this._super(e),this.name=e?e:"Node",this.transform=this.addComponent(new Transform),this.localCollisionID=-1},excluded:function(){return this._super().concat(["transform"])},type:function(){return"Node"},getBoundingBox:function(e){var t=new BoundingBox;return this.onEachChildComponent(function(i){i instanceof MeshRendererComponent&&t.encapsulateBox(i.getBoundingBox(e))}),t},getBoundingSphere:function(e){var t=new BoundingSphere;return this.onEachChildComponent(function(i){i instanceof MeshRendererComponent&&t.encapsulateSphere(i.getBoundingSphere(e))}),t},instantiate:function(){var e=new Node(this.name);e.isInstanced=!0,e.localCollisionID=this.localCollisionID,e.removeComponentsByType(Transform),e.layer=this.layer,e.tags=this.tags.slice(0);for(var t in this.subnodes)e.addNode(this.subnodes[t].instantiate());for(var i in this.components)e.addComponent(this.components[i].instantiate());return e.transform=e.getComponent(Transform),e},updateChildTransforms:function(){var e,t,i=this.transform.absolute,n=this.subnodes;for(e=0;e<n.length;e++){var r=n[e];r.transform&&(mat4.multiply(r.transform.absolute,i,r.transform.relative),r.updateChildTransforms())}for(t=0;t<this.components.length;t++)this.components[t].onUpdateTransform(i)},setAbsolutePosition:function(e){return this.parent&&this.parent.transform?(mat4.fromRotationTranslationScale(this.transform.absolute,quat.fromMat4(quat.create(),this.transform.absolute),e,mat4.getScale(vec3.create(),this.transform.absolute)),void this.transform.calculateRelativeFromAbsolute(this.parent.transform.absolute)):void this.transform.calculateRelativeFromAbsolute()}}),Scene=Serializable.extend({init:function(){this.root=new Node,this.root.scene=this,this.dynamicSpace=new DynamicSpace,this.cameras=[],this.lights=[],this.engine=!1,this.starting=!1,this.started=!1,this.startingQueue=[],this.components=[],this.preRenderedComponents=[],this.postRenderedComponents=[],this.updatedComponents=[]},fields:function(){return["root"]},start:function(e){if(!this.started&&!this.starting){this.starting=!0;var t=this;this.root.onEachChildComponent(function(e){e.enabled&&(e.started||e.onLoad(t.engine.assetsManager,t.engine))});var i=function(){t.root.updateChildTransforms(),t.root.onEachChildComponent(function(e){e.enabled&&(e.started||t.startingQueue.push(e))});var i=null;(i=function(){for(var n=50,r=(new Date).getTime()+n;(new Date).getTime()<r;){if(0===t.startingQueue.length)return t.started=!0,t.starting=!1,void("function"==typeof t.engine.sceneStarted&&t.engine.sceneStarted());var s=t.startingQueue.shift();s.started||(s.start(e,t.engine),s.started=!0)}setTimeout(i,10)})()};i()}},end:function(e,t){this.started&&(this.root.updateChildTransforms(),this.root.onEachChildComponent(function(i){i.enabled&&i.started&&(i.onEnd(e,t),i.started=!1)}),this.started=!1)},render:function(e){if(this.started){var t=!1;for(var i in this.cameras){t=this.cameras[i],t.startRender(e);for(var n=0;n<this.preRenderedComponents.length;n++){var r=this.preRenderedComponents[n];r.node.layer&t.layerMask&&(e.modelview.push(),e.modelview.multiply(r.node.transform.absolute),r.onPostRender(e,t),e.modelview.pop())}for(t.render(e,this),n=0;n<this.postRenderedComponents.length;n++){var r=this.postRenderedComponents[n];r.node.layer&t.layerMask&&(e.modelview.push(),e.modelview.multiply(r.node.transform.absolute),r.onPostRender(e,t),e.modelview.pop())}t.endRender(e)}}},update:function(e){if(this.started){for(var t=1,i=0;t>i;i++)for(var n=0;n<this.updatedComponents.length;++n){var r=this.updatedComponents[n];r.enabled&&(i<r.updatePasses&&r.started&&r.onUpdate(e,i),t<r.updatePasses&&(t=r.updatePasses))}this.root.updateChildTransforms()}},getMaterials:function(){var e=[];return this.root.onEachChildComponent(function(t){if(t instanceof MeshComponent)for(var i in t.mesh.materials)e.push(t.mesh.materials[i])}),e}}),DefaultScene=Scene.extend({init:function(){this._super(),this.root.name="Root",this.cameraNode=new Node("Camera"),this.cameraComponent=this.cameraNode.addComponent(new PerspectiveCamera),this.cameraComponent.aspect=!1,this.camera=this.cameraComponent.camera,this.root.addNode(this.cameraNode),this.lightNode=new Node("Light"),this.light=new Light,this.light.color=new Color(1,1,1,1),this.light.intensity=1,this.light.setLightDirection(vec3.fromValues(.9,1,.9)),this.lightNode.addComponent(this.light),this.root.addNode(this.lightNode)}}),FPS=Class.extend({init:function(){this.frametime=0,this.lastMeasurement=(new Date).getTime(),this.averageMultiplier=.95,this.delta=0},measure:function(){var e=(new Date).getTime();e-this.lastMeasurement>0&&(this.frametime=this.frametime*this.averageMultiplier+this.delta*(1-this.averageMultiplier),this.delta=e-this.lastMeasurement),this.lastMeasurement=e},getAverage:function(){return this.frametime<=0?0:1e3/this.frametime},getDelta:function(){return this.delta}}),Engine=Class.extend({init:function(e,t,i){function n(){for(var e=1;e<arguments.length;e++)for(var t in arguments[e])arguments[e].hasOwnProperty(t)&&(arguments[0][t]=arguments[e][t]);return arguments[0]}t||(t={}),this.options=n({assetsPath:"",requestedFPS:30,debug:!1,antialias:!1,ssao:!1,transparencyMode:"default",renderer:"default",context:!1},t),this.validateOptions(e),this.context=this.options.context,i||(i=new DefaultScene),this.scene=i,this.scene.engine=this,this.fps=new FPS,this.running=!1,this.input=!1,this.assetsManager=new AssetsManager(this.context,this.options.assetsPath),this.WhiteTexture=new Texture(this.context),this.WhiteTexture.name="WhiteTexture",this.WhiteTexture.mipmapped=!1,this.WhiteTexture.clearImage(this.context,[255,255,255,255]),this.WhiteTextureSampler=new Sampler("tex0",this.WhiteTexture),this.setupInput()},setupInput:function(){this.input=new Input(this,this.context.canvas[0])},run:function(){function e(){s.running&&a(e),t=Date.now(),i=t-n,i>r&&(n=t-i%r,s.frame())}if(this.running===!1){this.running=!0;var t,i,n=Date.now(),r=1e3/this.options.requestedFPS,s=this,a=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame||function(e){window.setTimeout(e,1e3/60)}}();this.scene.start(this.context,this),a(e)}},sceneStarted:function(){},stop:function(){this.pause(),this.scene.started&&this.scene.end(this.context)},pause:function(){this.running=!1},togglePause:function(){this.running===!1?this.run():this.pause()},frame:function(){this.context.engine=this,this.input.update(this),this.scene.update(this),this.scene.render(this.context),this.fps.measure()},validateOptions:function(e){switch(this.options.context=new RenderingContext(e),this.options.transparencyMode){case"sorted":case"blended":case"stochastic":break;default:this.options.transparencyMode="blended"}switch(this.options.renderer){case"deferred":case"forward":break;default:this.options.renderer="forward"}}}),Input=Class.extend({init:function(e,t){this.controllers=[],this.engine=e,this.canvas=t,this.lastPinch=0,this.lastRotation=0,this.buttons=[!1,!1,!1],this.button=-1,this.position=vec2.create(),this.delta=vec2.create(),this.lastDelta=vec2.create(),this.deltaChange=vec2.create(),this.scrollDelta=0,this.hammertime=HammerWF(this.canvas),this.hammertime.get("pinch").set({enable:!0}),this.hammertime.get("rotate").set({enable:!0}),this.hammertime.get("pan").set({threshold:0,pointers:0}),this.bindings={},this.keyStates={},this.keymap={enter:13,escape:27,backspace:8,tab:9,shift:16,ctrl:17,alt:18,pause:19,caps_lock:20,page_up:33,page_down:34,end:35,home:36,left_arrow:37,up_arrow:38,right_arrow:39,down_arrow:40,insert:45,"delete":46,left_window_key:91,right_window_key:92,select_key:93,numpad_0:96,numpad_1:97,numpad_2:98,numpad_3:99,numpad_4:100,numpad_5:101,numpad_6:102,numpad_7:103,numpad_8:104,numpad_9:105,multiply:106,add:107,subtract:109,decimal_point:110,divide:111,f1:112,f2:113,f3:114,f4:115,f5:116,f6:117,f7:118,f8:119,f9:120,f10:121,f11:122,f12:123,num_lock:144,scroll_lock:145,semi_colon:186,equal_sign:187,comma:188,dash:189,period:190,forward_slash:191,grave_accent:192,open_bracket:219,back_slash:220,close_braket:221,single_quote:222,0:48,1:49,2:50,3:51,4:52,5:53,6:54,7:55,8:56,9:57,a:65,b:66,c:67,d:68,e:69,f:70,g:71,h:72,i:73,j:74,k:75,l:76,m:77,n:78,o:79,p:80,q:81,r:82,s:83,t:84,u:85,v:86,w:87,x:88,y:89,z:90},this.setup()},setup:function(){this.registerKeyboardEvents(),this.registerPointerEvents()},registerController:function(e){return this.controllers.push(e),!0},registerPointerEvents:function(){this.hammertime&&(this.hammertime.on("pinch",ClassCallback(this,this.onPinch)),this.hammertime.on("pinchend",ClassCallback(this,this.onPinchEnd)),this.hammertime.on("tap",ClassCallback(this,this.onTap)),this.hammertime.on("transformstart",ClassCallback(this,this.onTransformStart)),this.hammertime.on("pan",ClassCallback(this,this.onPan)),this.hammertime.on("panstart",ClassCallback(this,this.onPanStart)),this.hammertime.on("panend",ClassCallback(this,this.onPanEnd)),this.hammertime.on("rotate",ClassCallback(this,this.onRotate)),this.hammertime.on("rotateend",ClassCallback(this,this.onRotateEnd)),this.hammertime.on("touch",ClassCallback(this,this.onTouch))),this.canvas.addEventListener("mousewheel",ClassCallback(this,this.onMouseWheel)),this.canvas.addEventListener("DOMMouseScroll",ClassCallback(this,this.onMouseWheelMOZ)),this.canvas.addEventListener("contextmenu",function(e){e.preventDefault()},!1)},registerKeyboardEvents:function(){this.canvas&&(this.canvas.addEventListener("keydown",ClassCallback(this,this.onKeyDown)),this.canvas.addEventListener("keyup",ClassCallback(this,this.onKeyUp)),this.canvas.focus&&this.canvas.focus())},unregisterController:function(e){var t=this.controllers.indexOf(e);return t>-1?(this.controllers.splice(t,1),!0):!1},bind:function(e,t,i){e&&t&&i&&(e in this.keymap?this.bindings[this.keymap[e]]=[i,t]:this.bindings[e.charCodeAt(0)]=[i,t])},sendEvent:function(e){var t=Array.prototype.slice.call(arguments,0);t=t.slice(1,t.length);for(var i=[],n=0;n<this.controllers.length;n++)this.controllers[n][e]&&i.push(this.controllers[n]);i.sort(function(t,i){return i.getPriority(e)-t.getPriority(e)});for(var n=0;n<i.length&&i[n][e].apply(i[n],t)!==!0;n++);},translateCoordinates:function(e,t,i){var n=this.canvas.getBoundingClientRect(),r=t-n.left,s=i-n.top;return vec2.set(e,r,s)},onTap:function(e){if(e){{this.translateCoordinates(this.position,e.center.x,e.center.y)}this.sendEvent("onClick",this.position,0,e.pointerType,e)}},onPan:function(e){e&&(e.preventDefault(),vec2.set(this.deltaChange,e.deltaX,e.deltaY),vec2.sub(this.deltaChange,this.deltaChange,this.lastDelta),vec2.set(this.lastDelta,e.deltaX,e.deltaY),this.setMouseButtons(e.frakButtons),this.translateCoordinates(this.position,e.center.x,e.center.y),Math.max(vec2.len(this.deltaChange))<100&&("touch"==e.pointerType?this.sendEvent("onPan",this.position,this.deltaChange,e.pointerType,e):this.sendEvent("onMouseMove",this.position,this.button,this.deltaChange,e.pointerType,e)))},onPanStart:function(e){e&&(this.setMouseButtons(e.frakButtons),this.translateCoordinates(this.position,e.center.x,e.center.y),this.sendEvent("onButtonDown",this.position,this.button,0,e.pointerType,e))},onPanEnd:function(e){vec2.set(this.lastDelta,0,0),e&&(this.setMouseButtons(e.frakButtons),this.translateCoordinates(this.position,e.center.x,e.center.y),this.sendEvent("onButtonUp",this.position,this.button,0,e.pointerType,e),this.resetMouseButtons())},onTouch:function(){},onTransformStart:function(e){e.gesture.preventDefault(),e.gesture&&(this.lastRotation=e.gesture.rotation)},onPinch:function(e){if(e.preventDefault(),e){this.translateCoordinates(this.position,e.clientX,e.clientY);var t=e.scale-this.lastPinch;this.lastPinch=e.scale-1,this.sendEvent("onPinch",this.position,t,"touch",e)}},onPinchEnd:function(){this.lastPinch=0},onRotate:function(e){if(e){this.translateCoordinates(this.position,e.clientX,e.clientY);var t=e.rotation-this.lastRotation;this.lastRotation=e.rotation,Math.max(t)<10&&this.sendEvent("onRotate",this.position,t,"touch",e)}},onRotateEnd:function(){this.lastRotation=0},onMultiDrag:function(){},onMouseWheel:function(e){if(e){e.preventDefault();var t=0;t="wheelDelta"in e?e.wheelDelta<0?1:e.wheelDelta>0?-1:0:e.deltaY>0?1:e.deltaY<0?-1:0,this.scrollDelta+=e.deltaY,this.translateCoordinates(this.position,e.clientX,e.clientY),this.sendEvent("onMouseWheel",this.position,this.scrollDelta,t,"mouse",e)}},onMouseWheelMOZ:function(e){if(e){e.preventDefault();var t=e.detail>0?1:e.detail<0?-1:0;this.scrollDelta+=e.detail,this.translateCoordinates(this.position,e.clientX,e.clientY),this.sendEvent("onMouseWheel",this.position,this.scrollDelta,t,"mouse",e)}},onKeyDown:function(e){e&&(this.sendEvent("onKeyDown",e.which,"keyboard",e),this.sendEvent("onKeyStateChange",e.which,!0,"keyboard",e),this.keyStates[e.which]=!0)},onKeyUp:function(e){e&&(this.sendEvent("onKeyUp",e.which,"keyboard",e),this.sendEvent("onKeyStateChange",e.which,!1,"keyboard",e),delete this.keyStates[e.which])},update:function(){this.processKeyEvents()},processKeyEvents:function(){for(var e in this.keyStates)if(this.bindings[e]){var t=this.bindings[e];t&&"object"==typeof t[0]&&"string"==typeof t[1]&&t[0][t[1]](this.engine.fps.getDelta()/1e3,e)}},setMouseButtons:function(e){if(e&&!(e.length<3)){this.button=-1;for(var t=0;3>t;t++)this.buttons[t]=e[t],e[t]===!0&&(this.button=t)}},resetMouseButtons:function(){this.button=-1,this.buttons[0]=!1,this.buttons[1]=!1,this.buttons[2]=!1}});HammerWF.MouseInput.prototype.handler=function(e){if("mousedown"==e.type&&(this.pressed=!0),this.pressed&&this.allow){"mouseup"==e.type&&(this.pressed=!1);var t=[!1,!1,!1];"buttons"in e?(t[0]=!!(1&e.buttons),t[1]=!!(4&e.buttons),t[2]=!!(2&e.buttons)):"button"in e&&(t[e.button]=!0);var i={mousedown:1,mousemove:2,mouseup:4};this.callback(this.manager,i[e.type],{pointers:[e],changedPointers:[e],pointerType:"mouse",srcEvent:e,frakButtons:t})}},HammerWF.PointerEventInput.prototype.handler=function(e){function t(e,t,i){if(e.indexOf&&!i)return e.indexOf(t);for(var n=0;n<e.length;){if(i&&e[n][i]==t||!i&&e[n]===t)return n;n++}return-1}var i=this.store,n=!1,r="touch",s="pen",a="mouse",o="kinect",h=1,c=2,u=4,l=8,d={pointerdown:h,pointermove:c,pointerup:u,pointercancel:l,pointerout:l},f={2:r,3:s,4:a,5:o},m=e.type.toLowerCase().replace("ms",""),p=d[m],g=f[e.pointerType]||e.pointerType,v=t(i,e.pointerId,"pointerId");if(p&h?0>v&&(i.push(e),v=i.length-1):p&(u|l)&&(n=!0),!(0>v)){i[v]=e;var b=[!!(1&e.buttons),!!(4&e.buttons),!!(2&e.buttons)];this.callback(this.manager,p,{pointers:i,changedPointers:[e],pointerType:g,srcEvent:e,frakButtons:b}),n&&i.splice(v,1)}};