(function(){var root=this;var PIXI=PIXI||{};PIXI.WEBGL_RENDERER=0;PIXI.CANVAS_RENDERER=1;PIXI.VERSION="v1.5.2";PIXI.blendModes={NORMAL:0,ADD:1,MULTIPLY:2,SCREEN:3,OVERLAY:4,DARKEN:5,LIGHTEN:6,COLOR_DODGE:7,COLOR_BURN:8,HARD_LIGHT:9,SOFT_LIGHT:10,DIFFERENCE:11,EXCLUSION:12,HUE:13,SATURATION:14,COLOR:15,LUMINOSITY:16};PIXI.scaleModes={DEFAULT:0,LINEAR:0,NEAREST:1};PIXI.INTERACTION_FREQUENCY=30;PIXI.AUTO_PREVENT_DEFAULT=true;PIXI.RAD_TO_DEG=180/Math.PI;PIXI.DEG_TO_RAD=Math.PI/180;PIXI.Point=function(x,y){this.x=x||0;this.y=y||0};PIXI.Point.prototype.clone=function(){return new PIXI.Point(this.x,this.y)};PIXI.Point.prototype.constructor=PIXI.Point;PIXI.Point.prototype.set=function(x,y){this.x=x||0;this.y=y||(y!==0?this.x:0)};PIXI.Rectangle=function(x,y,width,height){this.x=x||0;this.y=y||0;this.width=width||0;this.height=height||0};PIXI.Rectangle.prototype.clone=function(){return new PIXI.Rectangle(this.x,this.y,this.width,this.height)};PIXI.Rectangle.prototype.contains=function(x,y){if(this.width<=0||this.height<=0)return false;var x1=this.x;if(x>=x1&&x<=x1+this.width){var y1=this.y;if(y>=y1&&y<=y1+this.height){return true}}return false};PIXI.Rectangle.prototype.constructor=PIXI.Rectangle;PIXI.EmptyRectangle=new PIXI.Rectangle(0,0,0,0);PIXI.Polygon=function(points){if(!(points instanceof Array))points=Array.prototype.slice.call(arguments);if(typeof points[0]==="number"){var p=[];for(var i=0,il=points.length;iy!==yj>y&&x<(xj-xi)*(y-yi)/(yj-yi)+xi;if(intersect)inside=!inside}return inside};PIXI.Polygon.prototype.constructor=PIXI.Polygon;PIXI.Circle=function(x,y,radius){this.x=x||0;this.y=y||0;this.radius=radius||0};PIXI.Circle.prototype.clone=function(){return new PIXI.Circle(this.x,this.y,this.radius)};PIXI.Circle.prototype.contains=function(x,y){if(this.radius<=0)return false;var dx=this.x-x,dy=this.y-y,r2=this.radius*this.radius;dx*=dx;dy*=dy;return dx+dy<=r2};PIXI.Circle.prototype.constructor=PIXI.Circle;PIXI.Ellipse=function(x,y,width,height){this.x=x||0;this.y=y||0;this.width=width||0;this.height=height||0};PIXI.Ellipse.prototype.clone=function(){return new PIXI.Ellipse(this.x,this.y,this.width,this.height)};PIXI.Ellipse.prototype.contains=function(x,y){if(this.width<=0||this.height<=0)return false;var normx=(x-this.x)/this.width,normy=(y-this.y)/this.height;normx*=normx;normy*=normy;return normx+normy<=1};PIXI.Ellipse.prototype.getBounds=function(){return new PIXI.Rectangle(this.x,this.y,this.width,this.height)};PIXI.Ellipse.prototype.constructor=PIXI.Ellipse;PIXI.determineMatrixArrayType=function(){return typeof Float32Array!=="undefined"?Float32Array:Array};PIXI.Matrix2=PIXI.determineMatrixArrayType();PIXI.Matrix=function(){this.a=1;this.b=0;this.c=0;this.d=1;this.tx=0;this.ty=0};PIXI.Matrix.prototype.fromArray=function(array){this.a=array[0];this.b=array[1];this.c=array[3];this.d=array[4];this.tx=array[2];this.ty=array[5]};PIXI.Matrix.prototype.toArray=function(transpose){if(!this.array)this.array=new Float32Array(9);var array=this.array;if(transpose){this.array[0]=this.a;this.array[1]=this.c;this.array[2]=0;this.array[3]=this.b;this.array[4]=this.d;this.array[5]=0;this.array[6]=this.tx;this.array[7]=this.ty;this.array[8]=1}else{this.array[0]=this.a;this.array[1]=this.b;this.array[2]=this.tx;this.array[3]=this.c;this.array[4]=this.d;this.array[5]=this.ty;this.array[6]=0;this.array[7]=0;this.array[8]=1}return array};PIXI.identityMatrix=new PIXI.Matrix;PIXI.DisplayObject=function(){this.position=new PIXI.Point;this.scale=new PIXI.Point(1,1);this.pivot=new PIXI.Point(0,0);this.rotation=0;this.alpha=1;this.visible=true;this.hitArea=null;this.buttonMode=false;this.renderable=false;this.parent=null;this.stage=null;this.worldAlpha=1;this._interactive=false;this.defaultCursor="pointer";this.worldTransform=new PIXI.Matrix;this.color=[];this.dynamic=true;this._sr=0;this._cr=1;this.filterArea=null;this._bounds=new PIXI.Rectangle(0,0,1,1);this._currentBounds=null;this._mask=null;this._cacheAsBitmap=false;this._cacheIsDirty=false};PIXI.DisplayObject.prototype.constructor=PIXI.DisplayObject;PIXI.DisplayObject.prototype.setInteractive=function(interactive){this.interactive=interactive};Object.defineProperty(PIXI.DisplayObject.prototype,"interactive",{get:function(){return this._interactive},set:function(value){this._interactive=value;if(this.stage)this.stage.dirty=true}});Object.defineProperty(PIXI.DisplayObject.prototype,"worldVisible",{get:function(){var item=this;do{if(!item.visible)return false;item=item.parent}while(item);return true}});Object.defineProperty(PIXI.DisplayObject.prototype,"mask",{get:function(){return this._mask},set:function(value){if(this._mask)this._mask.isMask=false;this._mask=value;if(this._mask)this._mask.isMask=true}});Object.defineProperty(PIXI.DisplayObject.prototype,"filters",{get:function(){return this._filters},set:function(value){if(value){var passes=[];for(var i=0;i=0&&index<=this.children.length){if(child.parent){child.parent.removeChild(child)}child.parent=this;this.children.splice(index,0,child);if(this.stage)child.setStageReference(this.stage)}else{throw new Error(child+" The index "+index+" supplied is out of bounds "+this.children.length)}};PIXI.DisplayObjectContainer.prototype.swapChildren=function(child,child2){if(child===child2){return}var index1=this.children.indexOf(child);var index2=this.children.indexOf(child2);if(index1<0||index2<0){throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.")}this.children[index1]=child2;this.children[index2]=child};PIXI.DisplayObjectContainer.prototype.getChildAt=function(index){if(index>=0&&index0&&range<=end){var removed=this.children.splice(begin,range);for(var i=0;ichildMaxX?maxX:childMaxX;maxY=maxY>childMaxY?maxY:childMaxY}if(!childVisible)return PIXI.EmptyRectangle;var bounds=this._bounds;bounds.x=minX;bounds.y=minY;bounds.width=maxX-minX;bounds.height=maxY-minY;return bounds};PIXI.DisplayObjectContainer.prototype.getLocalBounds=function(){var matrixCache=this.worldTransform;this.worldTransform=PIXI.identityMatrix;for(var i=0,j=this.children.length;imaxX?x1:maxX;maxX=x2>maxX?x2:maxX;maxX=x3>maxX?x3:maxX;maxX=x4>maxX?x4:maxX;maxY=y1>maxY?y1:maxY;maxY=y2>maxY?y2:maxY;maxY=y3>maxY?y3:maxY;maxY=y4>maxY?y4:maxY;var bounds=this._bounds;bounds.x=minX;bounds.width=maxX-minX;bounds.y=minY;bounds.height=maxY-minY;this._currentBounds=bounds;return bounds};PIXI.Sprite.prototype._renderWebGL=function(renderSession){if(!this.visible||this.alpha<=0)return;var i,j;if(this._mask||this._filters){var spriteBatch=renderSession.spriteBatch;if(this._mask){spriteBatch.stop();renderSession.maskManager.pushMask(this.mask,renderSession);spriteBatch.start()}if(this._filters){spriteBatch.flush();renderSession.filterManager.pushFilter(this._filterBlock)}spriteBatch.render(this);for(i=0,j=this.children.length;ispaceLeft){if(j>0){result+="\n"}result+=words[j];spaceLeft=this.style.wordWrapWidth-wordWidth}else{spaceLeft-=wordWidthWithSpace;result+=" "+words[j]}}if(i=2?parseInt(font[font.length-2],10):PIXI.BitmapText.fonts[this.fontName].size;this.dirty=true;this.tint=style.tint};PIXI.BitmapText.prototype.updateText=function(){var data=PIXI.BitmapText.fonts[this.fontName];var pos=new PIXI.Point;var prevCharCode=null;var chars=[];var maxLineWidth=0;var lineWidths=[];var line=0;var scale=this.fontSize/data.size;for(var i=0;ilenChars){var child=this.getChildAt(this.children.length-1);this._pool.push(child);this.removeChild(child)}this.textWidth=maxLineWidth*scale;this.textHeight=(pos.y+data.lineHeight)*scale};PIXI.BitmapText.prototype.updateTransform=function(){if(this.dirty){this.updateText();this.dirty=false}PIXI.DisplayObjectContainer.prototype.updateTransform.call(this)};PIXI.BitmapText.fonts={};PIXI.Stage=function(backgroundColor){PIXI.DisplayObjectContainer.call(this);this.worldTransform=new PIXI.Matrix;this.interactive=true;this.interactionManager=new PIXI.InteractionManager(this);this.dirty=true;this.stage=this;this.stage.hitArea=new PIXI.Rectangle(0,0,1e5,1e5);this.setBackgroundColor(backgroundColor)};PIXI.Stage.prototype=Object.create(PIXI.DisplayObjectContainer.prototype);PIXI.Stage.prototype.constructor=PIXI.Stage;PIXI.Stage.prototype.setInteractionDelegate=function(domElement){this.interactionManager.setTargetDomElement(domElement)};PIXI.Stage.prototype.updateTransform=function(){this.worldAlpha=1;for(var i=0,j=this.children.length;i>16&255)/255,(hex>>8&255)/255,(hex&255)/255]};PIXI.rgb2hex=function(rgb){return(rgb[0]*255<<16)+(rgb[1]*255<<8)+rgb[2]*255};if(typeof Function.prototype.bind!=="function"){Function.prototype.bind=function(){var slice=Array.prototype.slice;return function(thisArg){var target=this,boundArgs=slice.call(arguments,1);if(typeof target!=="function")throw new TypeError;function bound(){var args=boundArgs.concat(slice.call(arguments));target.apply(this instanceof bound?this:thisArg,args)}bound.prototype=function F(proto){if(proto)F.prototype=proto;if(!(this instanceof F))return new F}(target.prototype);return bound}}()}PIXI.AjaxRequest=function(){var activexmodes=["Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.3.0","Microsoft.XMLHTTP"];if(window.ActiveXObject){for(var i=0;i0&&(number&number-1)===0)return number;else{var result=1;while(result>1;if(n<3)return[];var tgs=[];var avl=[];for(var i=0;i3){var i0=avl[(i+0)%al];var i1=avl[(i+1)%al];var i2=avl[(i+2)%al];var ax=p[2*i0],ay=p[2*i0+1];var bx=p[2*i1],by=p[2*i1+1];var cx=p[2*i2],cy=p[2*i2+1];var earFound=false;if(PIXI.PolyK._convex(ax,ay,bx,by,cx,cy,sign)){earFound=true;for(var j=0;j3*al){if(sign){tgs=[];avl=[];for(i=0;i=0&&v>=0&&u+v<1};PIXI.PolyK._convex=function(ax,ay,bx,by,cx,cy,sign){return(ay-by)*(cx-bx)+(bx-ax)*(cy-by)>=0===sign};PIXI.initDefaultShaders=function(){};PIXI.CompileVertexShader=function(gl,shaderSrc){return PIXI._CompileShader(gl,shaderSrc,gl.VERTEX_SHADER)};PIXI.CompileFragmentShader=function(gl,shaderSrc){return PIXI._CompileShader(gl,shaderSrc,gl.FRAGMENT_SHADER)};PIXI._CompileShader=function(gl,shaderSrc,shaderType){var src=shaderSrc.join("\n");var shader=gl.createShader(shaderType);gl.shaderSource(shader,src);gl.compileShader(shader);if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS)){window.console.log(gl.getShaderInfoLog(shader));return null}return shader};PIXI.compileProgram=function(gl,vertexSrc,fragmentSrc){var fragmentShader=PIXI.CompileFragmentShader(gl,fragmentSrc);var vertexShader=PIXI.CompileVertexShader(gl,vertexSrc);var shaderProgram=gl.createProgram();gl.attachShader(shaderProgram,vertexShader);gl.attachShader(shaderProgram,fragmentShader);gl.linkProgram(shaderProgram);if(!gl.getProgramParameter(shaderProgram,gl.LINK_STATUS)){window.console.log("Could not initialise shaders")}return shaderProgram};PIXI.PixiShader=function(gl){this.gl=gl;this.program=null;this.fragmentSrc=["precision lowp float;","varying vec2 vTextureCoord;","varying vec4 vColor;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"];this.textureCount=0;this.attributes=[];this.init()};PIXI.PixiShader.prototype.init=function(){var gl=this.gl;var program=PIXI.compileProgram(gl,this.vertexSrc||PIXI.PixiShader.defaultVertexSrc,this.fragmentSrc);gl.useProgram(program);this.uSampler=gl.getUniformLocation(program,"uSampler");this.projectionVector=gl.getUniformLocation(program,"projectionVector");this.offsetVector=gl.getUniformLocation(program,"offsetVector");this.dimensions=gl.getUniformLocation(program,"dimensions");this.aVertexPosition=gl.getAttribLocation(program,"aVertexPosition");this.aTextureCoord=gl.getAttribLocation(program,"aTextureCoord");this.colorAttribute=gl.getAttribLocation(program,"aColor");if(this.colorAttribute===-1){this.colorAttribute=2}this.attributes=[this.aVertexPosition,this.aTextureCoord,this.colorAttribute];for(var key in this.uniforms){this.uniforms[key].uniformLocation=gl.getUniformLocation(program,key)}this.initUniforms();this.program=program};PIXI.PixiShader.prototype.initUniforms=function(){this.textureCount=1;var gl=this.gl;var uniform;for(var key in this.uniforms){uniform=this.uniforms[key];var type=uniform.type;if(type==="sampler2D"){uniform._init=false;if(uniform.value!==null){this.initSampler2D(uniform)}}else if(type==="mat2"||type==="mat3"||type==="mat4"){uniform.glMatrix=true;uniform.glValueLength=1;if(type==="mat2"){uniform.glFunc=gl.uniformMatrix2fv}else if(type==="mat3"){uniform.glFunc=gl.uniformMatrix3fv}else if(type==="mat4"){uniform.glFunc=gl.uniformMatrix4fv}}else{uniform.glFunc=gl["uniform"+type];if(type==="2f"||type==="2i"){uniform.glValueLength=2}else if(type==="3f"||type==="3i"){uniform.glValueLength=3}else if(type==="4f"||type==="4i"){uniform.glValueLength=4}else{uniform.glValueLength=1}}}};PIXI.PixiShader.prototype.initSampler2D=function(uniform){if(!uniform.value||!uniform.value.baseTexture||!uniform.value.baseTexture.hasLoaded){return}var gl=this.gl;gl.activeTexture(gl["TEXTURE"+this.textureCount]);gl.bindTexture(gl.TEXTURE_2D,uniform.value.baseTexture._glTextures[gl.id]);if(uniform.textureData){var data=uniform.textureData;var magFilter=data.magFilter?data.magFilter:gl.LINEAR;var minFilter=data.minFilter?data.minFilter:gl.LINEAR;var wrapS=data.wrapS?data.wrapS:gl.CLAMP_TO_EDGE;var wrapT=data.wrapT?data.wrapT:gl.CLAMP_TO_EDGE;var format=data.luminance?gl.LUMINANCE:gl.RGBA;if(data.repeat){wrapS=gl.REPEAT;wrapT=gl.REPEAT}gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,!!data.flipY);if(data.width){var width=data.width?data.width:512;var height=data.height?data.height:2;var border=data.border?data.border:0;gl.texImage2D(gl.TEXTURE_2D,0,format,width,height,border,format,gl.UNSIGNED_BYTE,null)}else{gl.texImage2D(gl.TEXTURE_2D,0,format,gl.RGBA,gl.UNSIGNED_BYTE,uniform.value.baseTexture.source)}gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,magFilter);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,minFilter);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,wrapS);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,wrapT)}gl.uniform1i(uniform.uniformLocation,this.textureCount);uniform._init=true;this.textureCount++};PIXI.PixiShader.prototype.syncUniforms=function(){this.textureCount=1;var uniform;var gl=this.gl;for(var key in this.uniforms){uniform=this.uniforms[key];if(uniform.glValueLength===1){if(uniform.glMatrix===true){uniform.glFunc.call(gl,uniform.uniformLocation,uniform.transpose,uniform.value)}else{uniform.glFunc.call(gl,uniform.uniformLocation,uniform.value)}}else if(uniform.glValueLength===2){uniform.glFunc.call(gl,uniform.uniformLocation,uniform.value.x,uniform.value.y)}else if(uniform.glValueLength===3){uniform.glFunc.call(gl,uniform.uniformLocation,uniform.value.x,uniform.value.y,uniform.value.z)}else if(uniform.glValueLength===4){uniform.glFunc.call(gl,uniform.uniformLocation,uniform.value.x,uniform.value.y,uniform.value.z,uniform.value.w)}else if(uniform.type==="sampler2D"){if(uniform._init){gl.activeTexture(gl["TEXTURE"+this.textureCount]);gl.bindTexture(gl.TEXTURE_2D,uniform.value.baseTexture._glTextures[gl.id]||PIXI.createWebGLTexture(uniform.value.baseTexture,gl));gl.uniform1i(uniform.uniformLocation,this.textureCount);this.textureCount++}else{this.initSampler2D(uniform)}}}};PIXI.PixiShader.prototype.destroy=function(){this.gl.deleteProgram(this.program);this.uniforms=null;this.gl=null;this.attributes=null};PIXI.PixiShader.defaultVertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute vec2 aColor;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying vec4 vColor;","const vec2 center = vec2(-1.0, 1.0);","void main(void) {"," gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;"," vColor = vec4(color * aColor.x, aColor.x);","}"];PIXI.PixiFastShader=function(gl){this.gl=gl;this.program=null;this.fragmentSrc=["precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"];this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","const vec2 center = vec2(-1.0, 1.0);","void main(void) {"," vec2 v;"," vec2 sv = aVertexPosition * aScale;"," v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);"," v.y = (sv.x) * sin(aRotation) + (sv.y) * cos(aRotation);"," v = ( uMatrix * vec3(v + aPositionCoord , 1.0) ).xy ;"," gl_Position = vec4( ( v / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = aColor;","}"];this.textureCount=0;this.init()};PIXI.PixiFastShader.prototype.init=function(){var gl=this.gl;var program=PIXI.compileProgram(gl,this.vertexSrc,this.fragmentSrc);gl.useProgram(program);this.uSampler=gl.getUniformLocation(program,"uSampler");this.projectionVector=gl.getUniformLocation(program,"projectionVector");this.offsetVector=gl.getUniformLocation(program,"offsetVector");this.dimensions=gl.getUniformLocation(program,"dimensions");this.uMatrix=gl.getUniformLocation(program,"uMatrix");this.aVertexPosition=gl.getAttribLocation(program,"aVertexPosition");this.aPositionCoord=gl.getAttribLocation(program,"aPositionCoord");this.aScale=gl.getAttribLocation(program,"aScale");this.aRotation=gl.getAttribLocation(program,"aRotation");this.aTextureCoord=gl.getAttribLocation(program,"aTextureCoord");this.colorAttribute=gl.getAttribLocation(program,"aColor");if(this.colorAttribute===-1){this.colorAttribute=2}this.attributes=[this.aVertexPosition,this.aPositionCoord,this.aScale,this.aRotation,this.aTextureCoord,this.colorAttribute];this.program=program};PIXI.PixiFastShader.prototype.destroy=function(){this.gl.deleteProgram(this.program);this.uniforms=null;this.gl=null;this.attributes=null};PIXI.StripShader=function(){this.program=null;this.fragmentSrc=["precision mediump float;","varying vec2 vTextureCoord;","varying float vColor;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y));"," gl_FragColor = gl_FragColor * alpha;","}"];this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute float aColor;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","varying vec2 vTextureCoord;","uniform vec2 offsetVector;","varying float vColor;","void main(void) {"," vec3 v = translationMatrix * vec3(aVertexPosition, 1.0);"," v -= offsetVector.xyx;"," gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / projectionVector.y + 1.0 , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = aColor;","}"]};PIXI.StripShader.prototype.init=function(){var gl=PIXI.gl;var program=PIXI.compileProgram(gl,this.vertexSrc,this.fragmentSrc);gl.useProgram(program);this.uSampler=gl.getUniformLocation(program,"uSampler");this.projectionVector=gl.getUniformLocation(program,"projectionVector");this.offsetVector=gl.getUniformLocation(program,"offsetVector");this.colorAttribute=gl.getAttribLocation(program,"aColor");this.aVertexPosition=gl.getAttribLocation(program,"aVertexPosition");this.aTextureCoord=gl.getAttribLocation(program,"aTextureCoord");this.translationMatrix=gl.getUniformLocation(program,"translationMatrix");this.alpha=gl.getUniformLocation(program,"alpha");this.program=program};PIXI.PrimitiveShader=function(gl){this.gl=gl;this.program=null;this.fragmentSrc=["precision mediump float;","varying vec4 vColor;","void main(void) {"," gl_FragColor = vColor;","}"];this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void) {"," vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);"," v -= offsetVector.xyx;"," gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"];this.init()};PIXI.PrimitiveShader.prototype.init=function(){var gl=this.gl;var program=PIXI.compileProgram(gl,this.vertexSrc,this.fragmentSrc);gl.useProgram(program);this.projectionVector=gl.getUniformLocation(program,"projectionVector");this.offsetVector=gl.getUniformLocation(program,"offsetVector");this.tintColor=gl.getUniformLocation(program,"tint");this.aVertexPosition=gl.getAttribLocation(program,"aVertexPosition");this.colorAttribute=gl.getAttribLocation(program,"aColor");this.attributes=[this.aVertexPosition,this.colorAttribute];this.translationMatrix=gl.getUniformLocation(program,"translationMatrix");this.alpha=gl.getUniformLocation(program,"alpha");this.program=program};PIXI.PrimitiveShader.prototype.destroy=function(){this.gl.deleteProgram(this.program);this.uniforms=null;this.gl=null;this.attribute=null};PIXI.WebGLGraphics=function(){};PIXI.WebGLGraphics.renderGraphics=function(graphics,renderSession){var gl=renderSession.gl;var projection=renderSession.projection,offset=renderSession.offset,shader=renderSession.shaderManager.primitiveShader;if(!graphics._webGL[gl.id])graphics._webGL[gl.id]={points:[],indices:[],lastIndex:0,buffer:gl.createBuffer(),indexBuffer:gl.createBuffer()};var webGL=graphics._webGL[gl.id];if(graphics.dirty){graphics.dirty=false;if(graphics.clearDirty){graphics.clearDirty=false;webGL.lastIndex=0;webGL.points=[];webGL.indices=[]}PIXI.WebGLGraphics.updateGraphics(graphics,gl)}renderSession.shaderManager.activatePrimitiveShader();gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.uniformMatrix3fv(shader.translationMatrix,false,graphics.worldTransform.toArray(true));gl.uniform2f(shader.projectionVector,projection.x,-projection.y);gl.uniform2f(shader.offsetVector,-offset.x,-offset.y);gl.uniform3fv(shader.tintColor,PIXI.hex2rgb(graphics.tint));gl.uniform1f(shader.alpha,graphics.worldAlpha);gl.bindBuffer(gl.ARRAY_BUFFER,webGL.buffer);gl.vertexAttribPointer(shader.aVertexPosition,2,gl.FLOAT,false,4*6,0);gl.vertexAttribPointer(shader.colorAttribute,4,gl.FLOAT,false,4*6,2*4);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,webGL.indexBuffer);gl.drawElements(gl.TRIANGLE_STRIP,webGL.indices.length,gl.UNSIGNED_SHORT,0);renderSession.shaderManager.deactivatePrimitiveShader()};PIXI.WebGLGraphics.updateGraphics=function(graphics,gl){var webGL=graphics._webGL[gl.id];for(var i=webGL.lastIndex;i3)PIXI.WebGLGraphics.buildPoly(data,webGL)}if(data.lineWidth>0){PIXI.WebGLGraphics.buildLine(data,webGL)}}else if(data.type===PIXI.Graphics.RECT){PIXI.WebGLGraphics.buildRectangle(data,webGL)}else if(data.type===PIXI.Graphics.CIRC||data.type===PIXI.Graphics.ELIP){PIXI.WebGLGraphics.buildCircle(data,webGL)}}webGL.lastIndex=graphics.graphicsData.length;webGL.glPoints=new Float32Array(webGL.points);gl.bindBuffer(gl.ARRAY_BUFFER,webGL.buffer);gl.bufferData(gl.ARRAY_BUFFER,webGL.glPoints,gl.STATIC_DRAW);webGL.glIndicies=new Uint16Array(webGL.indices);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,webGL.indexBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,webGL.glIndicies,gl.STATIC_DRAW)};PIXI.WebGLGraphics.buildRectangle=function(graphicsData,webGLData){var rectData=graphicsData.points;var x=rectData[0];var y=rectData[1];var width=rectData[2];var height=rectData[3];if(graphicsData.fill){var color=PIXI.hex2rgb(graphicsData.fillColor);var alpha=graphicsData.fillAlpha;var r=color[0]*alpha;var g=color[1]*alpha;var b=color[2]*alpha;var verts=webGLData.points;var indices=webGLData.indices;var vertPos=verts.length/6;verts.push(x,y);verts.push(r,g,b,alpha);verts.push(x+width,y);verts.push(r,g,b,alpha);verts.push(x,y+height);verts.push(r,g,b,alpha);verts.push(x+width,y+height);verts.push(r,g,b,alpha);indices.push(vertPos,vertPos,vertPos+1,vertPos+2,vertPos+3,vertPos+3)}if(graphicsData.lineWidth){var tempPoints=graphicsData.points;graphicsData.points=[x,y,x+width,y,x+width,y+height,x,y+height,x,y];PIXI.WebGLGraphics.buildLine(graphicsData,webGLData);graphicsData.points=tempPoints}};PIXI.WebGLGraphics.buildCircle=function(graphicsData,webGLData){var rectData=graphicsData.points;var x=rectData[0];var y=rectData[1];var width=rectData[2];var height=rectData[3];var totalSegs=40;var seg=Math.PI*2/totalSegs;var i=0;if(graphicsData.fill){var color=PIXI.hex2rgb(graphicsData.fillColor);var alpha=graphicsData.fillAlpha;var r=color[0]*alpha;var g=color[1]*alpha;var b=color[2]*alpha;var verts=webGLData.points;var indices=webGLData.indices;var vecPos=verts.length/6;indices.push(vecPos);for(i=0;i140*140){perp3x=perpx-perp2x;perp3y=perpy-perp2y;dist=Math.sqrt(perp3x*perp3x+perp3y*perp3y);perp3x/=dist;perp3y/=dist;perp3x*=width;perp3y*=width;verts.push(p2x-perp3x,p2y-perp3y);verts.push(r,g,b,alpha);verts.push(p2x+perp3x,p2y+perp3y);verts.push(r,g,b,alpha);verts.push(p2x-perp3x,p2y-perp3y);verts.push(r,g,b,alpha);indexCount++}else{verts.push(px,py);verts.push(r,g,b,alpha);verts.push(p2x-(px-p2x),p2y-(py-p2y));verts.push(r,g,b,alpha)}}p1x=points[(length-2)*2];p1y=points[(length-2)*2+1];p2x=points[(length-1)*2];p2y=points[(length-1)*2+1];perpx=-(p1y-p2y);perpy=p1x-p2x;dist=Math.sqrt(perpx*perpx+perpy*perpy);perpx/=dist;perpy/=dist;perpx*=width;perpy*=width;verts.push(p2x-perpx,p2y-perpy);verts.push(r,g,b,alpha);verts.push(p2x+perpx,p2y+perpy);verts.push(r,g,b,alpha);indices.push(indexStart);for(i=0;i=0;i--){var glTexture=texture._glTextures[i];var gl=PIXI.glContexts[i];if(gl&&glTexture){gl.deleteTexture(glTexture)}}texture._glTextures.length=0};PIXI.WebGLRenderer.updateTextureFrame=function(texture){texture.updateFrame=false;texture._updateWebGLuvs()};PIXI.WebGLRenderer.prototype.resize=function(width,height){this.width=width;this.height=height;this.view.width=width;this.view.height=height;this.gl.viewport(0,0,this.width,this.height);this.projection.x=this.width/2;this.projection.y=-this.height/2};PIXI.createWebGLTexture=function(texture,gl){if(texture.hasLoaded){texture._glTextures[gl.id]=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,texture._glTextures[gl.id]);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,texture.source);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,texture.scaleMode===PIXI.scaleModes.LINEAR?gl.LINEAR:gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,texture.scaleMode===PIXI.scaleModes.LINEAR?gl.LINEAR:gl.NEAREST);if(!texture._powerOf2){gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE)}else{gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.REPEAT);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.REPEAT)}gl.bindTexture(gl.TEXTURE_2D,null)}return texture._glTextures[gl.id]};PIXI.updateWebGLTexture=function(texture,gl){if(texture._glTextures[gl.id]){gl.bindTexture(gl.TEXTURE_2D,texture._glTextures[gl.id]);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,texture.source);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,texture.scaleMode===PIXI.scaleModes.LINEAR?gl.LINEAR:gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,texture.scaleMode===PIXI.scaleModes.LINEAR?gl.LINEAR:gl.NEAREST);if(!texture._powerOf2){gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE)}else{gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.REPEAT);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.REPEAT)}gl.bindTexture(gl.TEXTURE_2D,null)}};PIXI.WebGLRenderer.prototype.handleContextLost=function(event){event.preventDefault();this.contextLost=true};PIXI.WebGLRenderer.prototype.handleContextRestored=function(){try{this.gl=this.view.getContext("experimental-webgl",this.options)}catch(e){try{this.gl=this.view.getContext("webgl",this.options)}catch(e2){throw new Error(" This browser does not support webGL. Try using the canvas renderer"+this)}}var gl=this.gl;gl.id=PIXI.WebGLRenderer.glContextId++;this.shaderManager.setContext(gl);this.spriteBatch.setContext(gl);this.maskManager.setContext(gl);this.filterManager.setContext(gl);this.renderSession.gl=this.gl;gl.disable(gl.DEPTH_TEST);gl.disable(gl.CULL_FACE);gl.enable(gl.BLEND);gl.colorMask(true,true,true,this.transparent);this.gl.viewport(0,0,this.width,this.height);for(var key in PIXI.TextureCache){var texture=PIXI.TextureCache[key].baseTexture;texture._glTextures=[]}this.contextLost=false};PIXI.WebGLRenderer.prototype.destroy=function(){this.view.removeEventListener("webglcontextlost",this.contextLost);this.view.removeEventListener("webglcontextrestored",this.contextRestoredLost); PIXI.glContexts[this.glContextId]=null;this.projection=null;this.offset=null;this.shaderManager.destroy();this.spriteBatch.destroy();this.maskManager.destroy();this.filterManager.destroy();this.shaderManager=null;this.spriteBatch=null;this.maskManager=null;this.filterManager=null;this.gl=null;this.renderSession=null};PIXI.WebGLRenderer.glContextId=0;PIXI.WebGLMaskManager=function(gl){this.maskStack=[];this.maskPosition=0;this.setContext(gl)};PIXI.WebGLMaskManager.prototype.setContext=function(gl){this.gl=gl};PIXI.WebGLMaskManager.prototype.pushMask=function(maskData,renderSession){var gl=this.gl;if(this.maskStack.length===0){gl.enable(gl.STENCIL_TEST);gl.stencilFunc(gl.ALWAYS,1,1)}this.maskStack.push(maskData);gl.colorMask(false,false,false,false);gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);PIXI.WebGLGraphics.renderGraphics(maskData,renderSession);gl.colorMask(true,true,true,true);gl.stencilFunc(gl.NOTEQUAL,0,this.maskStack.length);gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP)};PIXI.WebGLMaskManager.prototype.popMask=function(renderSession){var gl=this.gl;var maskData=this.maskStack.pop();if(maskData){gl.colorMask(false,false,false,false);gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);PIXI.WebGLGraphics.renderGraphics(maskData,renderSession);gl.colorMask(true,true,true,true);gl.stencilFunc(gl.NOTEQUAL,0,this.maskStack.length);gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP)}if(this.maskStack.length===0)gl.disable(gl.STENCIL_TEST)};PIXI.WebGLMaskManager.prototype.destroy=function(){this.maskStack=null;this.gl=null};PIXI.WebGLShaderManager=function(gl){this.maxAttibs=10;this.attribState=[];this.tempAttribState=[];for(var i=0;i=this.size){this.flush();this.currentBaseTexture=texture.baseTexture}if(sprite.blendMode!==this.currentBlendMode){this.setBlendMode(sprite.blendMode)}var uvs=sprite._uvs||sprite.texture._uvs;if(!uvs)return;var alpha=sprite.worldAlpha;var tint=sprite.tint;var verticies=this.vertices;var aX=sprite.anchor.x;var aY=sprite.anchor.y;var w0,w1,h0,h1;if(sprite.texture.trim){var trim=sprite.texture.trim;w1=trim.x-aX*trim.width;w0=w1+texture.frame.width;h1=trim.y-aY*trim.height;h0=h1+texture.frame.height}else{w0=texture.frame.width*(1-aX);w1=texture.frame.width*-aX;h0=texture.frame.height*(1-aY);h1=texture.frame.height*-aY}var index=this.currentBatchSize*4*this.vertSize;var worldTransform=sprite.worldTransform;var a=worldTransform.a;var b=worldTransform.c;var c=worldTransform.b;var d=worldTransform.d;var tx=worldTransform.tx;var ty=worldTransform.ty;verticies[index++]=a*w1+c*h1+tx;verticies[index++]=d*h1+b*w1+ty;verticies[index++]=uvs.x0;verticies[index++]=uvs.y0;verticies[index++]=alpha;verticies[index++]=tint;verticies[index++]=a*w0+c*h1+tx;verticies[index++]=d*h1+b*w0+ty;verticies[index++]=uvs.x1;verticies[index++]=uvs.y1;verticies[index++]=alpha;verticies[index++]=tint;verticies[index++]=a*w0+c*h0+tx;verticies[index++]=d*h0+b*w0+ty;verticies[index++]=uvs.x2;verticies[index++]=uvs.y2;verticies[index++]=alpha;verticies[index++]=tint;verticies[index++]=a*w1+c*h0+tx;verticies[index++]=d*h0+b*w1+ty;verticies[index++]=uvs.x3;verticies[index++]=uvs.y3;verticies[index++]=alpha;verticies[index++]=tint;this.currentBatchSize++};PIXI.WebGLSpriteBatch.prototype.renderTilingSprite=function(tilingSprite){var texture=tilingSprite.tilingTexture;if(texture.baseTexture!==this.currentBaseTexture||this.currentBatchSize>=this.size){this.flush();this.currentBaseTexture=texture.baseTexture}if(tilingSprite.blendMode!==this.currentBlendMode){this.setBlendMode(tilingSprite.blendMode)}if(!tilingSprite._uvs)tilingSprite._uvs=new PIXI.TextureUvs;var uvs=tilingSprite._uvs;tilingSprite.tilePosition.x%=texture.baseTexture.width*tilingSprite.tileScaleOffset.x;tilingSprite.tilePosition.y%=texture.baseTexture.height*tilingSprite.tileScaleOffset.y;var offsetX=tilingSprite.tilePosition.x/(texture.baseTexture.width*tilingSprite.tileScaleOffset.x);var offsetY=tilingSprite.tilePosition.y/(texture.baseTexture.height*tilingSprite.tileScaleOffset.y);var scaleX=tilingSprite.width/texture.baseTexture.width/(tilingSprite.tileScale.x*tilingSprite.tileScaleOffset.x);var scaleY=tilingSprite.height/texture.baseTexture.height/(tilingSprite.tileScale.y*tilingSprite.tileScaleOffset.y);uvs.x0=0-offsetX;uvs.y0=0-offsetY;uvs.x1=1*scaleX-offsetX;uvs.y1=0-offsetY;uvs.x2=1*scaleX-offsetX;uvs.y2=1*scaleY-offsetY;uvs.x3=0-offsetX;uvs.y3=1*scaleY-offsetY;var alpha=tilingSprite.worldAlpha;var tint=tilingSprite.tint;var verticies=this.vertices;var width=tilingSprite.width;var height=tilingSprite.height;var aX=tilingSprite.anchor.x;var aY=tilingSprite.anchor.y;var w0=width*(1-aX);var w1=width*-aX;var h0=height*(1-aY);var h1=height*-aY;var index=this.currentBatchSize*4*this.vertSize;var worldTransform=tilingSprite.worldTransform;var a=worldTransform.a;var b=worldTransform.c;var c=worldTransform.b;var d=worldTransform.d;var tx=worldTransform.tx;var ty=worldTransform.ty;verticies[index++]=a*w1+c*h1+tx;verticies[index++]=d*h1+b*w1+ty;verticies[index++]=uvs.x0;verticies[index++]=uvs.y0;verticies[index++]=alpha;verticies[index++]=tint;verticies[index++]=a*w0+c*h1+tx;verticies[index++]=d*h1+b*w0+ty;verticies[index++]=uvs.x1;verticies[index++]=uvs.y1;verticies[index++]=alpha;verticies[index++]=tint;verticies[index++]=a*w0+c*h0+tx;verticies[index++]=d*h0+b*w0+ty;verticies[index++]=uvs.x2;verticies[index++]=uvs.y2;verticies[index++]=alpha;verticies[index++]=tint;verticies[index++]=a*w1+c*h0+tx;verticies[index++]=d*h0+b*w1+ty;verticies[index++]=uvs.x3;verticies[index++]=uvs.y3;verticies[index++]=alpha;verticies[index++]=tint;this.currentBatchSize++};PIXI.WebGLSpriteBatch.prototype.flush=function(){if(this.currentBatchSize===0)return;var gl=this.gl;gl.bindTexture(gl.TEXTURE_2D,this.currentBaseTexture._glTextures[gl.id]||PIXI.createWebGLTexture(this.currentBaseTexture,gl));if(this.currentBatchSize>this.size*.5){gl.bufferSubData(gl.ARRAY_BUFFER,0,this.vertices)}else{var view=this.vertices.subarray(0,this.currentBatchSize*4*this.vertSize);gl.bufferSubData(gl.ARRAY_BUFFER,0,view)}gl.drawElements(gl.TRIANGLES,this.currentBatchSize*6,gl.UNSIGNED_SHORT,0);this.currentBatchSize=0;this.renderSession.drawCount++};PIXI.WebGLSpriteBatch.prototype.stop=function(){this.flush()};PIXI.WebGLSpriteBatch.prototype.start=function(){var gl=this.gl;gl.activeTexture(gl.TEXTURE0);gl.bindBuffer(gl.ARRAY_BUFFER,this.vertexBuffer);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var projection=this.renderSession.projection;gl.uniform2f(this.shader.projectionVector,projection.x,projection.y);var stride=this.vertSize*4;gl.vertexAttribPointer(this.shader.aVertexPosition,2,gl.FLOAT,false,stride,0);gl.vertexAttribPointer(this.shader.aTextureCoord,2,gl.FLOAT,false,stride,2*4);gl.vertexAttribPointer(this.shader.colorAttribute,2,gl.FLOAT,false,stride,4*4);if(this.currentBlendMode!==PIXI.blendModes.NORMAL){this.setBlendMode(PIXI.blendModes.NORMAL)}};PIXI.WebGLSpriteBatch.prototype.setBlendMode=function(blendMode){this.flush();this.currentBlendMode=blendMode;var blendModeWebGL=PIXI.blendModesWebGL[this.currentBlendMode];this.gl.blendFunc(blendModeWebGL[0],blendModeWebGL[1])};PIXI.WebGLSpriteBatch.prototype.destroy=function(){this.vertices=null;this.indices=null;this.gl.deleteBuffer(this.vertexBuffer);this.gl.deleteBuffer(this.indexBuffer);this.currentBaseTexture=null;this.gl=null};PIXI.WebGLFastSpriteBatch=function(gl){this.vertSize=10;this.maxSize=6e3;this.size=this.maxSize;var numVerts=this.size*4*this.vertSize;var numIndices=this.maxSize*6;this.vertices=new Float32Array(numVerts);this.indices=new Uint16Array(numIndices);this.vertexBuffer=null;this.indexBuffer=null;this.lastIndexCount=0;for(var i=0,j=0;i=this.size){this.flush()}};PIXI.WebGLFastSpriteBatch.prototype.flush=function(){if(this.currentBatchSize===0)return;var gl=this.gl;if(!this.currentBaseTexture._glTextures[gl.id])PIXI.createWebGLTexture(this.currentBaseTexture,gl);gl.bindTexture(gl.TEXTURE_2D,this.currentBaseTexture._glTextures[gl.id]);if(this.currentBatchSize>this.size*.5){gl.bufferSubData(gl.ARRAY_BUFFER,0,this.vertices)}else{var view=this.vertices.subarray(0,this.currentBatchSize*4*this.vertSize);gl.bufferSubData(gl.ARRAY_BUFFER,0,view)}gl.drawElements(gl.TRIANGLES,this.currentBatchSize*6,gl.UNSIGNED_SHORT,0);this.currentBatchSize=0;this.renderSession.drawCount++};PIXI.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()};PIXI.WebGLFastSpriteBatch.prototype.start=function(){var gl=this.gl;gl.activeTexture(gl.TEXTURE0);gl.bindBuffer(gl.ARRAY_BUFFER,this.vertexBuffer);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var projection=this.renderSession.projection;gl.uniform2f(this.shader.projectionVector,projection.x,projection.y);gl.uniformMatrix3fv(this.shader.uMatrix,false,this.matrix);var stride=this.vertSize*4;gl.vertexAttribPointer(this.shader.aVertexPosition,2,gl.FLOAT,false,stride,0);gl.vertexAttribPointer(this.shader.aPositionCoord,2,gl.FLOAT,false,stride,2*4);gl.vertexAttribPointer(this.shader.aScale,2,gl.FLOAT,false,stride,4*4);gl.vertexAttribPointer(this.shader.aRotation,1,gl.FLOAT,false,stride,6*4);gl.vertexAttribPointer(this.shader.aTextureCoord,2,gl.FLOAT,false,stride,7*4);gl.vertexAttribPointer(this.shader.colorAttribute,1,gl.FLOAT,false,stride,9*4);if(this.currentBlendMode!==PIXI.blendModes.NORMAL){this.setBlendMode(PIXI.blendModes.NORMAL)}};PIXI.WebGLFastSpriteBatch.prototype.setBlendMode=function(blendMode){this.flush();this.currentBlendMode=blendMode;var blendModeWebGL=PIXI.blendModesWebGL[this.currentBlendMode];this.gl.blendFunc(blendModeWebGL[0],blendModeWebGL[1])};PIXI.WebGLFilterManager=function(gl,transparent){this.transparent=transparent;this.filterStack=[];this.offsetX=0;this.offsetY=0;this.setContext(gl)};PIXI.WebGLFilterManager.prototype.setContext=function(gl){this.gl=gl;this.texturePool=[];this.initShaderBuffers()};PIXI.WebGLFilterManager.prototype.begin=function(renderSession,buffer){this.renderSession=renderSession;this.defaultShader=renderSession.shaderManager.defaultShader;var projection=this.renderSession.projection;this.width=projection.x*2;this.height=-projection.y*2;this.buffer=buffer};PIXI.WebGLFilterManager.prototype.pushFilter=function(filterBlock){var gl=this.gl;var projection=this.renderSession.projection;var offset=this.renderSession.offset;filterBlock._filterArea=filterBlock.target.filterArea||filterBlock.target.getBounds();this.filterStack.push(filterBlock);var filter=filterBlock.filterPasses[0];this.offsetX+=filterBlock._filterArea.x;this.offsetY+=filterBlock._filterArea.y;var texture=this.texturePool.pop();if(!texture){texture=new PIXI.FilterTexture(this.gl,this.width,this.height)}else{texture.resize(this.width,this.height)}gl.bindTexture(gl.TEXTURE_2D,texture.texture);var filterArea=filterBlock._filterArea;var padding=filter.padding;filterArea.x-=padding;filterArea.y-=padding;filterArea.width+=padding*2;filterArea.height+=padding*2;if(filterArea.x<0)filterArea.x=0;if(filterArea.width>this.width)filterArea.width=this.width;if(filterArea.y<0)filterArea.y=0;if(filterArea.height>this.height)filterArea.height=this.height;gl.bindFramebuffer(gl.FRAMEBUFFER,texture.frameBuffer);gl.viewport(0,0,filterArea.width,filterArea.height);projection.x=filterArea.width/2;projection.y=-filterArea.height/2;offset.x=-filterArea.x;offset.y=-filterArea.y;gl.uniform2f(this.defaultShader.projectionVector,filterArea.width/2,-filterArea.height/2);gl.uniform2f(this.defaultShader.offsetVector,-filterArea.x,-filterArea.y);gl.colorMask(true,true,true,true);gl.clearColor(0,0,0,0);gl.clear(gl.COLOR_BUFFER_BIT);filterBlock._glFilterTexture=texture};PIXI.WebGLFilterManager.prototype.popFilter=function(){var gl=this.gl;var filterBlock=this.filterStack.pop();var filterArea=filterBlock._filterArea;var texture=filterBlock._glFilterTexture;var projection=this.renderSession.projection;var offset=this.renderSession.offset;if(filterBlock.filterPasses.length>1){gl.viewport(0,0,filterArea.width,filterArea.height);gl.bindBuffer(gl.ARRAY_BUFFER,this.vertexBuffer);this.vertexArray[0]=0;this.vertexArray[1]=filterArea.height;this.vertexArray[2]=filterArea.width;this.vertexArray[3]=filterArea.height;this.vertexArray[4]=0;this.vertexArray[5]=0;this.vertexArray[6]=filterArea.width;this.vertexArray[7]=0;gl.bufferSubData(gl.ARRAY_BUFFER,0,this.vertexArray);gl.bindBuffer(gl.ARRAY_BUFFER,this.uvBuffer);this.uvArray[2]=filterArea.width/this.width;this.uvArray[5]=filterArea.height/this.height;this.uvArray[6]=filterArea.width/this.width;this.uvArray[7]=filterArea.height/this.height;gl.bufferSubData(gl.ARRAY_BUFFER,0,this.uvArray);var inputTexture=texture;var outputTexture=this.texturePool.pop();if(!outputTexture)outputTexture=new PIXI.FilterTexture(this.gl,this.width,this.height);outputTexture.resize(this.width,this.height);gl.bindFramebuffer(gl.FRAMEBUFFER,outputTexture.frameBuffer);gl.clear(gl.COLOR_BUFFER_BIT);gl.disable(gl.BLEND);for(var i=0;i0){PIXI.Texture.frameUpdates.length=0}};PIXI.CanvasRenderer.prototype.resize=function(width,height){this.width=width;this.height=height;this.view.width=width;this.view.height=height};PIXI.CanvasRenderer.prototype.renderDisplayObject=function(displayObject,context){this.renderSession.context=context||this.context;displayObject._renderCanvas(this.renderSession)};PIXI.CanvasRenderer.prototype.renderStripFlat=function(strip){var context=this.context;var verticies=strip.verticies;var length=verticies.length/2;this.count++;context.beginPath();for(var i=1;i1){len=1;window.console.log("Pixi.js warning: masks in canvas can only mask using the first path in the graphics object")}for(var i=0;i<1;i++){var data=graphics.graphicsData[i];var points=data.points;if(data.type===PIXI.Graphics.POLY){context.beginPath();context.moveTo(points[0],points[1]);for(var j=1;jmaxX?x2:maxX;maxX=x3>maxX?x3:maxX;maxX=x4>maxX?x4:maxX;maxY=y2>maxY?y2:maxY;maxY=y3>maxY?y3:maxY;maxY=y4>maxY?y4:maxY;var bounds=this._bounds;bounds.x=minX;bounds.width=maxX-minX;bounds.y=minY;bounds.height=maxY-minY;return bounds};PIXI.Graphics.prototype.updateBounds=function(){var minX=Infinity;var maxX=-Infinity;var minY=Infinity;var maxY=-Infinity;var points,x,y,w,h;for(var i=0;imaxX?x+w:maxX;minY=ymaxY?y+h:maxY}else if(type===PIXI.Graphics.CIRC||type===PIXI.Graphics.ELIP){x=points[0];y=points[1];w=points[2]+lineWidth/2;h=points[3]+lineWidth/2;minX=x-wmaxX?x+w:maxX;minY=y-hmaxY?y+h:maxY}else{for(var j=0;jmaxX?x+lineWidth:maxX;minY=y-lineWidthmaxY?y+lineWidth:maxY}}}var padding=this.boundsPadding;this.bounds=new PIXI.Rectangle(minX-padding,minY-padding,maxX-minX+padding*2,maxY-minY+padding*2)};PIXI.Graphics.prototype._generateCachedSprite=function(){var bounds=this.getLocalBounds();if(!this._cachedSprite){var canvasBuffer=new PIXI.CanvasBuffer(bounds.width,bounds.height);var texture=PIXI.Texture.fromCanvas(canvasBuffer.canvas);this._cachedSprite=new PIXI.Sprite(texture);this._cachedSprite.buffer=canvasBuffer;this._cachedSprite.worldTransform=this.worldTransform}else{this._cachedSprite.buffer.resize(bounds.width,bounds.height)}this._cachedSprite.anchor.x=-(bounds.x/bounds.width);this._cachedSprite.anchor.y=-(bounds.y/bounds.height);this._cachedSprite.buffer.context.translate(-bounds.x,-bounds.y);PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context);this._cachedSprite.alpha=this.alpha};PIXI.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(true);this._cachedSprite=null};PIXI.Graphics.POLY=0;PIXI.Graphics.RECT=1;PIXI.Graphics.CIRC=2;PIXI.Graphics.ELIP=3;PIXI.TilingSprite=function(texture,width,height){PIXI.Sprite.call(this,texture);this.width=width||100;this.height=height||100;this.tileScale=new PIXI.Point(1,1);this.tileScaleOffset=new PIXI.Point(1,1);this.tilePosition=new PIXI.Point(0,0);this.renderable=true;this.tint=16777215;this.blendMode=PIXI.blendModes.NORMAL};PIXI.TilingSprite.prototype=Object.create(PIXI.Sprite.prototype);PIXI.TilingSprite.prototype.constructor=PIXI.TilingSprite;Object.defineProperty(PIXI.TilingSprite.prototype,"width",{get:function(){return this._width},set:function(value){this._width=value}});Object.defineProperty(PIXI.TilingSprite.prototype,"height",{get:function(){return this._height},set:function(value){this._height=value}});PIXI.TilingSprite.prototype.onTextureUpdate=function(){this.updateFrame=true};PIXI.TilingSprite.prototype.setTexture=function(texture){if(this.texture===texture)return;this.texture=texture;this.refreshTexture=true;this.cachedTint=16777215};PIXI.TilingSprite.prototype._renderWebGL=function(renderSession){if(this.visible===false||this.alpha===0)return;var i,j;if(this.mask){renderSession.spriteBatch.stop();renderSession.maskManager.pushMask(this.mask,renderSession);renderSession.spriteBatch.start()}if(this.filters){renderSession.spriteBatch.flush();renderSession.filterManager.pushFilter(this._filterBlock)}if(!this.tilingTexture||this.refreshTexture){this.generateTilingTexture(true);if(this.tilingTexture&&this.tilingTexture.needsUpdate){PIXI.updateWebGLTexture(this.tilingTexture.baseTexture,renderSession.gl);this.tilingTexture.needsUpdate=false}}else renderSession.spriteBatch.renderTilingSprite(this);for(i=0,j=this.children.length;imaxX?x1:maxX;maxX=x2>maxX?x2:maxX;maxX=x3>maxX?x3:maxX;maxX=x4>maxX?x4:maxX;maxY=y1>maxY?y1:maxY;maxY=y2>maxY?y2:maxY;maxY=y3>maxY?y3:maxY;maxY=y4>maxY?y4:maxY;var bounds=this._bounds;bounds.x=minX;bounds.width=maxX-minX;bounds.y=minY;bounds.height=maxY-minY;this._currentBounds=bounds;return bounds};PIXI.TilingSprite.prototype.generateTilingTexture=function(forcePowerOfTwo){var texture=this.texture;if(!texture.baseTexture.hasLoaded)return;var baseTexture=texture.baseTexture;var frame=texture.frame;var targetWidth,targetHeight;var isFrame=frame.width!==baseTexture.width||frame.height!==baseTexture.height;var newTextureRequired=false;if(!forcePowerOfTwo){if(isFrame){targetWidth=frame.width;targetHeight=frame.height;newTextureRequired=true}}else{targetWidth=PIXI.getNextPowerOfTwo(frame.width);targetHeight=PIXI.getNextPowerOfTwo(frame.height);if(frame.width!==targetWidth&&frame.height!==targetHeight)newTextureRequired=true}if(newTextureRequired){var canvasBuffer;if(this.tilingTexture&&this.tilingTexture.isTiling){canvasBuffer=this.tilingTexture.canvasBuffer;canvasBuffer.resize(targetWidth,targetHeight);this.tilingTexture.baseTexture.width=targetWidth;this.tilingTexture.baseTexture.height=targetHeight;this.tilingTexture.needsUpdate=true}else{canvasBuffer=new PIXI.CanvasBuffer(targetWidth,targetHeight);this.tilingTexture=PIXI.Texture.fromCanvas(canvasBuffer.canvas);this.tilingTexture.canvasBuffer=canvasBuffer;this.tilingTexture.isTiling=true}canvasBuffer.context.drawImage(texture.baseTexture.source,frame.x,frame.y,frame.width,frame.height,0,0,targetWidth,targetHeight);this.tileScaleOffset.x=frame.width/targetWidth;this.tileScaleOffset.y=frame.height/targetHeight}else{if(this.tilingTexture&&this.tilingTexture.isTiling){this.tilingTexture.destroy(true)}this.tileScaleOffset.x=1;this.tileScaleOffset.y=1;this.tilingTexture=texture}this.refreshTexture=false;this.tilingTexture.baseTexture._powerOf2=true};PIXI.BaseTextureCache={};PIXI.texturesToUpdate=[];PIXI.texturesToDestroy=[];PIXI.BaseTextureCacheIdGenerator=0;PIXI.BaseTexture=function(source,scaleMode){PIXI.EventTarget.call(this);this.width=100;this.height=100;this.scaleMode=scaleMode||PIXI.scaleModes.DEFAULT;this.hasLoaded=false;this.source=source;this.id=PIXI.BaseTextureCacheIdGenerator++;this._glTextures=[];if(!source)return;if((this.source.complete||this.source.getContext)&&this.source.width&&this.source.height){this.hasLoaded=true;this.width=this.source.width;this.height=this.source.height;PIXI.texturesToUpdate.push(this)}else{var scope=this;this.source.onload=function(){scope.hasLoaded=true;scope.width=scope.source.width;scope.height=scope.source.height;PIXI.texturesToUpdate.push(scope);scope.dispatchEvent({type:"loaded",content:scope})}}this.imageUrl=null;this._powerOf2=false};PIXI.BaseTexture.prototype.constructor=PIXI.BaseTexture;PIXI.BaseTexture.prototype.destroy=function(){if(this.imageUrl){delete PIXI.BaseTextureCache[this.imageUrl];this.imageUrl=null;this.source.src=null}this.source=null;PIXI.texturesToDestroy.push(this)};PIXI.BaseTexture.prototype.updateSourceImage=function(newSrc){this.hasLoaded=false;this.source.src=null;this.source.src=newSrc};PIXI.BaseTexture.fromImage=function(imageUrl,crossorigin,scaleMode){var baseTexture=PIXI.BaseTextureCache[imageUrl];if(crossorigin===undefined&&imageUrl.indexOf("data:")===-1)crossorigin=true;if(!baseTexture){var image=new Image;if(crossorigin){image.crossOrigin=""}image.src=imageUrl;baseTexture=new PIXI.BaseTexture(image,scaleMode);baseTexture.imageUrl=imageUrl;PIXI.BaseTextureCache[imageUrl]=baseTexture}return baseTexture};PIXI.BaseTexture.fromCanvas=function(canvas,scaleMode){if(!canvas._pixiId){canvas._pixiId="canvas_"+PIXI.TextureCacheIdGenerator++}var baseTexture=PIXI.BaseTextureCache[canvas._pixiId];if(!baseTexture){baseTexture=new PIXI.BaseTexture(canvas,scaleMode);PIXI.BaseTextureCache[canvas._pixiId]=baseTexture}return baseTexture};PIXI.TextureCache={};PIXI.FrameCache={};PIXI.TextureCacheIdGenerator=0;PIXI.Texture=function(baseTexture,frame){PIXI.EventTarget.call(this);if(!frame){this.noFrame=true;frame=new PIXI.Rectangle(0,0,1,1)}if(baseTexture instanceof PIXI.Texture)baseTexture=baseTexture.baseTexture;this.baseTexture=baseTexture;this.frame=frame;this.trim=null;this.scope=this;this._uvs=null;if(baseTexture.hasLoaded){if(this.noFrame)frame=new PIXI.Rectangle(0,0,baseTexture.width,baseTexture.height);this.setFrame(frame)}else{var scope=this;baseTexture.addEventListener("loaded",function(){scope.onBaseTextureLoaded()})}};PIXI.Texture.prototype.constructor=PIXI.Texture;PIXI.Texture.prototype.onBaseTextureLoaded=function(){var baseTexture=this.baseTexture;baseTexture.removeEventListener("loaded",this.onLoaded);if(this.noFrame)this.frame=new PIXI.Rectangle(0,0,baseTexture.width,baseTexture.height);this.setFrame(this.frame);this.scope.dispatchEvent({type:"update",content:this})};PIXI.Texture.prototype.destroy=function(destroyBase){if(destroyBase)this.baseTexture.destroy()};PIXI.Texture.prototype.setFrame=function(frame){this.frame=frame;this.width=frame.width;this.height=frame.height;if(frame.x+frame.width>this.baseTexture.width||frame.y+frame.height>this.baseTexture.height){throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this)}this.updateFrame=true;PIXI.Texture.frameUpdates.push(this)};PIXI.Texture.prototype._updateWebGLuvs=function(){if(!this._uvs)this._uvs=new PIXI.TextureUvs;var frame=this.frame;var tw=this.baseTexture.width;var th=this.baseTexture.height;this._uvs.x0=frame.x/tw;this._uvs.y0=frame.y/th;this._uvs.x1=(frame.x+frame.width)/tw;this._uvs.y1=frame.y/th;this._uvs.x2=(frame.x+frame.width)/tw;this._uvs.y2=(frame.y+frame.height)/th;this._uvs.x3=frame.x/tw;this._uvs.y3=(frame.y+frame.height)/th};PIXI.Texture.fromImage=function(imageUrl,crossorigin,scaleMode){var texture=PIXI.TextureCache[imageUrl];if(!texture){texture=new PIXI.Texture(PIXI.BaseTexture.fromImage(imageUrl,crossorigin,scaleMode));PIXI.TextureCache[imageUrl]=texture}return texture};PIXI.Texture.fromFrame=function(frameId){var texture=PIXI.TextureCache[frameId];if(!texture)throw new Error('The frameId "'+frameId+'" does not exist in the texture cache ');return texture};PIXI.Texture.fromCanvas=function(canvas,scaleMode){var baseTexture=PIXI.BaseTexture.fromCanvas(canvas,scaleMode);return new PIXI.Texture(baseTexture)};PIXI.Texture.addTextureToCache=function(texture,id){PIXI.TextureCache[id]=texture};PIXI.Texture.removeTextureFromCache=function(id){var texture=PIXI.TextureCache[id];delete PIXI.TextureCache[id];delete PIXI.BaseTextureCache[id];return texture};PIXI.Texture.frameUpdates=[];PIXI.TextureUvs=function(){this.x0=0;this.y0=0;this.x1=0;this.y1=0;this.x2=0;this.y2=0;this.x3=0;this.y4=0};PIXI.RenderTexture=function(width,height,renderer,scaleMode){PIXI.EventTarget.call(this);this.width=width||100;this.height=height||100;this.frame=new PIXI.Rectangle(0,0,this.width,this.height);this.baseTexture=new PIXI.BaseTexture;this.baseTexture.width=this.width;this.baseTexture.height=this.height;this.baseTexture._glTextures=[];this.baseTexture.scaleMode=scaleMode||PIXI.scaleModes.DEFAULT;this.baseTexture.hasLoaded=true;this.renderer=renderer||PIXI.defaultRenderer;if(this.renderer.type===PIXI.WEBGL_RENDERER){var gl=this.renderer.gl;this.textureBuffer=new PIXI.FilterTexture(gl,this.width,this.height,this.baseTexture.scaleMode);this.baseTexture._glTextures[gl.id]=this.textureBuffer.texture;this.render=this.renderWebGL;this.projection=new PIXI.Point(this.width/2,-this.height/2)}else{this.render=this.renderCanvas;this.textureBuffer=new PIXI.CanvasBuffer(this.width,this.height);this.baseTexture.source=this.textureBuffer.canvas}PIXI.Texture.frameUpdates.push(this)};PIXI.RenderTexture.prototype=Object.create(PIXI.Texture.prototype);PIXI.RenderTexture.prototype.constructor=PIXI.RenderTexture;PIXI.RenderTexture.prototype.resize=function(width,height,updateBase){if(width===this.width&&height===this.height){return}this.width=width;this.height=height;this.frame.width=this.width;this.frame.height=this.height;if(updateBase){this.baseTexture.width=this.width;this.baseTexture.height=this.height}if(this.renderer.type===PIXI.WEBGL_RENDERER){this.projection.x=this.width/2;this.projection.y=-this.height/2}this.textureBuffer.resize(this.width,this.height)};PIXI.RenderTexture.prototype.clear=function(){if(this.renderer.type===PIXI.WEBGL_RENDERER){this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer)}this.textureBuffer.clear()};PIXI.RenderTexture.prototype.renderWebGL=function(displayObject,position,clear){var gl=this.renderer.gl;gl.colorMask(true,true,true,true);gl.viewport(0,0,this.width,this.height);gl.bindFramebuffer(gl.FRAMEBUFFER,this.textureBuffer.frameBuffer);if(clear)this.textureBuffer.clear();var children=displayObject.children;var originalWorldTransform=displayObject.worldTransform;displayObject.worldTransform=PIXI.RenderTexture.tempMatrix;displayObject.worldTransform.d=-1;displayObject.worldTransform.ty=this.projection.y*-2;if(position){displayObject.worldTransform.tx=position.x;displayObject.worldTransform.ty-=position.y}for(var i=0,j=children.length;i-1;j--){result[i][j]=array[j][i]}}return result},rotateArray:function(matrix,direction){if(typeof direction!=="string"){direction=(direction%360+360)%360}if(direction===90||direction===-270||direction==="rotateLeft"){matrix=Phaser.Utils.transposeArray(matrix);matrix=matrix.reverse()}else if(direction===-90||direction===270||direction==="rotateRight"){matrix=matrix.reverse();matrix=Phaser.Utils.transposeArray(matrix)}else if(Math.abs(direction)===180||direction==="rotate180"){for(var i=0;i0;i--){var j=Math.floor(Math.random()*(i+1));var temp=array[i];array[i]=array[j];array[j]=temp}return array},pad:function(str,len,pad,dir){if(typeof len=="undefined"){var len=0}if(typeof pad=="undefined"){var pad=" "}if(typeof dir=="undefined"){var dir=3}var padlen=0;if(len+1>=str.length){switch(dir){ case 1:str=new Array(len+1-str.length).join(pad)+str;break;case 3:var right=Math.ceil((padlen=len-str.length)/2);var left=padlen-right;str=new Array(left+1).join(pad)+str+new Array(right+1).join(pad);break;default:str=str+new Array(len+1-str.length).join(pad);break}}return str},isPlainObject:function(obj){if(typeof obj!=="object"||obj.nodeType||obj===obj.window){return false}try{if(obj.constructor&&!{}.hasOwnProperty.call(obj.constructor.prototype,"isPrototypeOf")){return false}}catch(e){return false}return true},extend:function(){var options,name,src,copy,copyIsArray,clone,target=arguments[0]||{},i=1,length=arguments.length,deep=false;if(typeof target==="boolean"){deep=target;target=arguments[1]||{};i=2}if(length===i){target=this;--i}for(;i>>0;if(typeof fun!=="function"){throw new TypeError}var thisArg=arguments.length>=2?arguments[1]:void 0;for(var i=0;i0){this._radius=diameter*.5}else{this._radius=0}};Phaser.Circle.prototype={circumference:function(){return 2*(Math.PI*this._radius)},setTo:function(x,y,diameter){this.x=x;this.y=y;this._diameter=diameter;this._radius=diameter*.5;return this},copyFrom:function(source){return this.setTo(source.x,source.y,source.diameter)},copyTo:function(dest){dest.x=this.x;dest.y=this.y;dest.diameter=this._diameter;return dest},distance:function(dest,round){if(typeof round==="undefined"){round=false}if(round){return Phaser.Math.distanceRounded(this.x,this.y,dest.x,dest.y)}else{return Phaser.Math.distance(this.x,this.y,dest.x,dest.y)}},clone:function(out){if(typeof out==="undefined"){out=new Phaser.Circle(this.x,this.y,this.diameter)}else{out.setTo(this.x,this.y,this.diameter)}return out},contains:function(x,y){return Phaser.Circle.contains(this,x,y)},circumferencePoint:function(angle,asDegrees,out){return Phaser.Circle.circumferencePoint(this,angle,asDegrees,out)},offset:function(dx,dy){this.x+=dx;this.y+=dy;return this},offsetPoint:function(point){return this.offset(point.x,point.y)},toString:function(){return"[{Phaser.Circle (x="+this.x+" y="+this.y+" diameter="+this.diameter+" radius="+this.radius+")}]"}};Phaser.Circle.prototype.constructor=Phaser.Circle;Object.defineProperty(Phaser.Circle.prototype,"diameter",{get:function(){return this._diameter},set:function(value){if(value>0){this._diameter=value;this._radius=value*.5}}});Object.defineProperty(Phaser.Circle.prototype,"radius",{get:function(){return this._radius},set:function(value){if(value>0){this._radius=value;this._diameter=value*2}}});Object.defineProperty(Phaser.Circle.prototype,"left",{get:function(){return this.x-this._radius},set:function(value){if(value>this.x){this._radius=0;this._diameter=0}else{this.radius=this.x-value}}});Object.defineProperty(Phaser.Circle.prototype,"right",{get:function(){return this.x+this._radius},set:function(value){if(valuethis.y){this._radius=0;this._diameter=0}else{this.radius=this.y-value}}});Object.defineProperty(Phaser.Circle.prototype,"bottom",{get:function(){return this.y+this._radius},set:function(value){if(value0){return Math.PI*this._radius*this._radius}else{return 0}}});Object.defineProperty(Phaser.Circle.prototype,"empty",{get:function(){return this._diameter===0},set:function(value){if(value===true){this.setTo(0,0,0)}}});Phaser.Circle.contains=function(a,x,y){if(a.radius>0&&x>=a.left&&x<=a.right&&y>=a.top&&y<=a.bottom){var dx=(a.x-x)*(a.x-x);var dy=(a.y-y)*(a.y-y);return dx+dy<=a.radius*a.radius}else{return false}};Phaser.Circle.equals=function(a,b){return a.x==b.x&&a.y==b.y&&a.diameter==b.diameter};Phaser.Circle.intersects=function(a,b){return Phaser.Math.distance(a.x,a.y,b.x,b.y)<=a.radius+b.radius};Phaser.Circle.circumferencePoint=function(a,angle,asDegrees,out){if(typeof asDegrees==="undefined"){asDegrees=false}if(typeof out==="undefined"){out=new Phaser.Point}if(asDegrees===true){angle=Phaser.Math.degToRad(angle)}out.x=a.x+a.radius*Math.cos(angle);out.y=a.y+a.radius*Math.sin(angle);return out};Phaser.Circle.intersectsRectangle=function(c,r){var cx=Math.abs(c.x-r.x-r.halfWidth);var xDist=r.halfWidth+c.radius;if(cx>xDist){return false}var cy=Math.abs(c.y-r.y-r.halfHeight);var yDist=r.halfHeight+c.radius;if(cy>yDist){return false}if(cx<=r.halfWidth||cy<=r.halfHeight){return true}var xCornerDist=cx-r.halfWidth;var yCornerDist=cy-r.halfHeight;var xCornerDistSq=xCornerDist*xCornerDist;var yCornerDistSq=yCornerDist*yCornerDist;var maxCornerDistSq=c.radius*c.radius;return xCornerDistSq+yCornerDistSq<=maxCornerDistSq};PIXI.Circle=Phaser.Circle;Phaser.Point=function(x,y){x=x||0;y=y||0;this.x=x;this.y=y};Phaser.Point.prototype={copyFrom:function(source){return this.setTo(source.x,source.y)},invert:function(){return this.setTo(this.y,this.x)},setTo:function(x,y){this.x=x||0;this.y=y||(y!==0?this.x:0);return this},set:function(x,y){this.x=x||0;this.y=y||(y!==0?this.x:0);return this},add:function(x,y){this.x+=x;this.y+=y;return this},subtract:function(x,y){this.x-=x;this.y-=y;return this},multiply:function(x,y){this.x*=x;this.y*=y;return this},divide:function(x,y){this.x/=x;this.y/=y;return this},clampX:function(min,max){this.x=Phaser.Math.clamp(this.x,min,max);return this},clampY:function(min,max){this.y=Phaser.Math.clamp(this.y,min,max);return this},clamp:function(min,max){this.x=Phaser.Math.clamp(this.x,min,max);this.y=Phaser.Math.clamp(this.y,min,max);return this},clone:function(output){if(typeof output==="undefined"){output=new Phaser.Point(this.x,this.y)}else{output.setTo(this.x,this.y)}return output},copyTo:function(dest){dest.x=this.x;dest.y=this.y;return dest},distance:function(dest,round){return Phaser.Point.distance(this,dest,round)},equals:function(a){return a.x===this.x&&a.y===this.y},angle:function(a,asDegrees){if(typeof asDegrees==="undefined"){asDegrees=false}if(asDegrees){return Phaser.Math.radToDeg(Math.atan2(a.y-this.y,a.x-this.x))}else{return Math.atan2(a.y-this.y,a.x-this.x)}},angleSq:function(a){return this.subtract(a).angle(a.subtract(this))},rotate:function(x,y,angle,asDegrees,distance){return Phaser.Point.rotate(this,x,y,angle,asDegrees,distance)},getMagnitude:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},getMagnitudeSq:function(){return this.x*this.x+this.y*this.y},setMagnitude:function(magnitude){return this.normalize().multiply(magnitude,magnitude)},normalize:function(){if(!this.isZero()){var m=this.getMagnitude();this.x/=m;this.y/=m}return this},isZero:function(){return this.x===0&&this.y===0},dot:function(a){return this.x*a.x+this.y*a.y},cross:function(a){return this.x*a.y-this.y*a.x},perp:function(){return this.setTo(-this.y,this.x)},rperp:function(){return this.setTo(this.y,-this.x)},normalRightHand:function(){return this.setTo(this.y*-1,this.x)},toString:function(){return"[{Point (x="+this.x+" y="+this.y+")}]"}};Phaser.Point.prototype.constructor=Phaser.Point;Phaser.Point.add=function(a,b,out){if(typeof out==="undefined"){out=new Phaser.Point}out.x=a.x+b.x;out.y=a.y+b.y;return out};Phaser.Point.subtract=function(a,b,out){if(typeof out==="undefined"){out=new Phaser.Point}out.x=a.x-b.x;out.y=a.y-b.y;return out};Phaser.Point.multiply=function(a,b,out){if(typeof out==="undefined"){out=new Phaser.Point}out.x=a.x*b.x;out.y=a.y*b.y;return out};Phaser.Point.divide=function(a,b,out){if(typeof out==="undefined"){out=new Phaser.Point}out.x=a.x/b.x;out.y=a.y/b.y;return out};Phaser.Point.equals=function(a,b){return a.x===b.x&&a.y===b.y};Phaser.Point.angle=function(a,b){return Math.atan2(a.y-b.y,a.x-b.x)};Phaser.Point.angleSq=function(a,b){return a.subtract(b).angle(b.subtract(a))};Phaser.Point.negative=function(a,out){if(typeof out==="undefined"){out=new Phaser.Point}return out.setTo(-a.x,-a.y)};Phaser.Point.multiplyAdd=function(a,b,s,out){if(typeof out==="undefined"){out=new Phaser.Point}return out.setTo(a.x+b.x*s,a.y+b.y*s)};Phaser.Point.interpolate=function(a,b,f,out){if(typeof out==="undefined"){out=new Phaser.Point}return out.setTo(a.x+(b.x-a.x)*f,a.y+(b.y-a.y)*f)};Phaser.Point.perp=function(a,out){if(typeof out==="undefined"){out=new Phaser.Point}return out.setTo(-a.y,a.x)};Phaser.Point.rperp=function(a,out){if(typeof out==="undefined"){out=new Phaser.Point}return out.setTo(a.y,-a.x)};Phaser.Point.distance=function(a,b,round){if(typeof round==="undefined"){round=false}if(round){return Phaser.Math.distanceRounded(a.x,a.y,b.x,b.y)}else{return Phaser.Math.distance(a.x,a.y,b.x,b.y)}};Phaser.Point.project=function(a,b,out){if(typeof out==="undefined"){out=new Phaser.Point}var amt=a.dot(b)/b.getMagnitudeSq();if(amt!==0){out.setTo(amt*b.x,amt*b.y)}return out};Phaser.Point.projectUnit=function(a,b,out){if(typeof out==="undefined"){out=new Phaser.Point}var amt=a.dot(b);if(amt!==0){out.setTo(amt*b.x,amt*b.y)}return out};Phaser.Point.normalRightHand=function(a,out){if(typeof out==="undefined"){out=new Phaser.Point}return out.setTo(a.y*-1,a.x)};Phaser.Point.normalize=function(a,out){if(typeof out==="undefined"){out=new Phaser.Point}var m=a.getMagnitude();if(m!==0){out.setTo(a.x/m,a.y/m)}return out};Phaser.Point.rotate=function(a,x,y,angle,asDegrees,distance){asDegrees=asDegrees||false;distance=distance||null;if(asDegrees){angle=Phaser.Math.degToRad(angle)}if(distance===null){distance=Math.sqrt((x-a.x)*(x-a.x)+(y-a.y)*(y-a.y))}return a.setTo(x+distance*Math.cos(angle),y+distance*Math.sin(angle))};Phaser.Point.centroid=function(points,out){if(typeof out==="undefined"){out=new Phaser.Point}if(Object.prototype.toString.call(points)!=="[object Array]"){throw new Error("Phaser.Point. Parameter 'points' must be an array")}var pointslength=points.length;if(pointslength<1){throw new Error("Phaser.Point. Parameter 'points' array must not be empty")}if(pointslength===1){out.copyFrom(points[0]);return out}for(var i=0;i=this.right){this.width=0}else{this.width=this.right-value}this.x=value}});Object.defineProperty(Phaser.Rectangle.prototype,"right",{get:function(){return this.x+this.width},set:function(value){if(value<=this.x){this.width=0}else{this.width=this.x+value}}});Object.defineProperty(Phaser.Rectangle.prototype,"volume",{get:function(){return this.width*this.height}});Object.defineProperty(Phaser.Rectangle.prototype,"perimeter",{get:function(){return this.width*2+this.height*2}});Object.defineProperty(Phaser.Rectangle.prototype,"centerX",{get:function(){return this.x+this.halfWidth},set:function(value){this.x=value-this.halfWidth}});Object.defineProperty(Phaser.Rectangle.prototype,"centerY",{get:function(){return this.y+this.halfHeight},set:function(value){this.y=value-this.halfHeight}});Object.defineProperty(Phaser.Rectangle.prototype,"top",{get:function(){return this.y},set:function(value){if(value>=this.bottom){this.height=0;this.y=value}else{this.height=this.bottom-value}}});Object.defineProperty(Phaser.Rectangle.prototype,"topLeft",{get:function(){return new Phaser.Point(this.x,this.y)},set:function(value){this.x=value.x;this.y=value.y}});Object.defineProperty(Phaser.Rectangle.prototype,"empty",{get:function(){return!this.width||!this.height},set:function(value){if(value===true){this.setTo(0,0,0,0)}}});Phaser.Rectangle.prototype.constructor=Phaser.Rectangle;Phaser.Rectangle.inflate=function(a,dx,dy){a.x-=dx;a.width+=2*dx;a.y-=dy;a.height+=2*dy;return a};Phaser.Rectangle.inflatePoint=function(a,point){return Phaser.Rectangle.inflate(a,point.x,point.y)};Phaser.Rectangle.size=function(a,output){if(typeof output==="undefined"){output=new Phaser.Point(a.width,a.height)}else{output.setTo(a.width,a.height)}return output};Phaser.Rectangle.clone=function(a,output){if(typeof output==="undefined"){output=new Phaser.Rectangle(a.x,a.y,a.width,a.height)}else{output.setTo(a.x,a.y,a.width,a.height)}return output};Phaser.Rectangle.contains=function(a,x,y){if(a.width<=0||a.height<=0){return false}return x>=a.x&&x<=a.right&&y>=a.y&&y<=a.bottom};Phaser.Rectangle.containsRaw=function(rx,ry,rw,rh,x,y){return x>=rx&&x<=rx+rw&&y>=ry&&y<=ry+rh};Phaser.Rectangle.containsPoint=function(a,point){return Phaser.Rectangle.contains(a,point.x,point.y)};Phaser.Rectangle.containsRect=function(a,b){if(a.volume>b.volume){return false}return a.x>=b.x&&a.y>=b.y&&a.right<=b.right&&a.bottom<=b.bottom};Phaser.Rectangle.equals=function(a,b){return a.x==b.x&&a.y==b.y&&a.width==b.width&&a.height==b.height};Phaser.Rectangle.intersection=function(a,b,output){if(typeof output==="undefined"){output=new Phaser.Rectangle}if(Phaser.Rectangle.intersects(a,b)){output.x=Math.max(a.x,b.x);output.y=Math.max(a.y,b.y);output.width=Math.min(a.right,b.right)-output.x;output.height=Math.min(a.bottom,b.bottom)-output.y}return output};Phaser.Rectangle.intersects=function(a,b){if(a.width<=0||a.height<=0||b.width<=0||b.height<=0){return false}return!(a.rightb.right||a.y>b.bottom)};Phaser.Rectangle.intersectsRaw=function(a,left,right,top,bottom,tolerance){if(typeof tolerance==="undefined"){tolerance=0}return!(left>a.right+tolerance||righta.bottom+tolerance||bottom=xMin&&x<=xMax)&&(y>=yMin&&y<=yMax)},coordinatesOnLine:function(stepRate,results){if(typeof stepRate==="undefined"){stepRate=1}if(typeof results==="undefined"){results=[]}var x1=Math.round(this.start.x);var y1=Math.round(this.start.y);var x2=Math.round(this.end.x);var y2=Math.round(this.end.y);var dx=Math.abs(x2-x1);var dy=Math.abs(y2-y1);var sx=x1-dy){err-=dy;x1+=sx}if(e2Math.max(a.x,b.x)||result.yMath.max(a.y,b.y)||result.xMath.max(e.x,f.x)||result.yMath.max(e.y,f.y)){return null}}return result};Phaser.Line.intersects=function(a,b,asSegment,result){return Phaser.Line.intersectsPoints(a.start,a.end,b.start,b.end,asSegment,result)};Phaser.Ellipse=function(x,y,width,height){this.type=Phaser.ELLIPSE;x=x||0;y=y||0;width=width||0;height=height||0;this.x=x;this.y=y;this.width=width;this.height=height};Phaser.Ellipse.prototype={setTo:function(x,y,width,height){this.x=x;this.y=y;this.width=width;this.height=height;return this},copyFrom:function(source){return this.setTo(source.x,source.y,source.width,source.height)},copyTo:function(dest){dest.x=this.x;dest.y=this.y;dest.width=this.width;dest.height=this.height;return dest},clone:function(out){if(typeof out==="undefined"){out=new Phaser.Ellipse(this.x,this.y,this.width,this.height)}else{out.setTo(this.x,this.y,this.width,this.height)}return out},contains:function(x,y){return Phaser.Ellipse.contains(this,x,y)},toString:function(){return"[{Phaser.Ellipse (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")}]"}};Phaser.Ellipse.prototype.constructor=Phaser.Ellipse;Object.defineProperty(Phaser.Ellipse.prototype,"left",{get:function(){return this.x},set:function(value){this.x=value}});Object.defineProperty(Phaser.Ellipse.prototype,"right",{get:function(){return this.x+this.width},set:function(value){if(valuey!==yj>y&&x<(xj-xi)*(y-yi)/(yj-yi)+xi;if(intersect){inside=!inside}}return inside}};Phaser.Polygon.prototype.constructor=Phaser.Polygon;Object.defineProperty(Phaser.Polygon.prototype,"points",{get:function(){return this._points},set:function(points){if(!(points instanceof Array)){points=Array.prototype.slice.call(arguments)}if(typeof points[0]==="number"){var p=[];for(var i=0,len=points.length;ithis._edge){this.view.x=this._edge}this._edge=this.target.x+this.target.width-this.deadzone.x-this.deadzone.width;if(this.view.xthis._edge){this.view.y=this._edge}this._edge=this.target.y+this.target.height-this.deadzone.y-this.deadzone.height;if(this.view.y=this.bounds.right){this.atLimit.x=true;this.view.x=this.bounds.right-this.width}if(this.view.y<=this.bounds.top){this.atLimit.y=true;this.view.y=this.bounds.top}if(this.view.bottom>=this.bounds.bottom){this.atLimit.y=true;this.view.y=this.bounds.bottom-this.height}this.view.floor()},setPosition:function(x,y){this.view.x=x;this.view.y=y;if(this.bounds){this.checkBounds()}},setSize:function(width,height){this.view.width=width;this.view.height=height},reset:function(){this.target=null;this.view.x=0;this.view.y=0}};Phaser.Camera.prototype.constructor=Phaser.Camera;Object.defineProperty(Phaser.Camera.prototype,"x",{get:function(){return this.view.x},set:function(value){this.view.x=value;if(this.bounds){this.checkBounds()}}});Object.defineProperty(Phaser.Camera.prototype,"y",{get:function(){return this.view.y},set:function(value){this.view.y=value;if(this.bounds){this.checkBounds()}}});Object.defineProperty(Phaser.Camera.prototype,"width",{get:function(){return this.view.width},set:function(value){this.view.width=value}});Object.defineProperty(Phaser.Camera.prototype,"height",{get:function(){return this.view.height},set:function(value){this.view.height=value}});Phaser.State=function(){this.game=null;this.add=null;this.make=null;this.camera=null;this.cache=null;this.input=null;this.load=null;this.math=null;this.sound=null;this.scale=null;this.stage=null;this.time=null;this.tweens=null;this.world=null;this.particles=null;this.physics=null;this.rnd=null};Phaser.State.prototype={preload:function(){},loadUpdate:function(){},loadRender:function(){},create:function(){},update:function(){},render:function(){},paused:function(){},pauseUpdate:function(){},shutdown:function(){}};Phaser.State.prototype.constructor=Phaser.State;Phaser.StateManager=function(game,pendingState){this.game=game;this.states={};this._pendingState=null;if(typeof pendingState!=="undefined"&&pendingState!==null){this._pendingState=pendingState}this._clearWorld=false;this._clearCache=false;this._created=false;this._args=[];this.current="";this.onInitCallback=null;this.onPreloadCallback=null;this.onCreateCallback=null;this.onUpdateCallback=null;this.onRenderCallback=null;this.onPreRenderCallback=null;this.onLoadUpdateCallback=null;this.onLoadRenderCallback=null;this.onPausedCallback=null;this.onResumedCallback=null;this.onPauseUpdateCallback=null;this.onShutDownCallback=null};Phaser.StateManager.prototype={boot:function(){this.game.onPause.add(this.pause,this);this.game.onResume.add(this.resume,this);this.game.load.onLoadComplete.add(this.loadComplete,this);if(this._pendingState!==null){if(typeof this._pendingState==="string"){this.start(this._pendingState,false,false)}else{this.add("default",this._pendingState,true)}}},add:function(key,state,autoStart){if(typeof autoStart==="undefined"){autoStart=false}var newState;if(state instanceof Phaser.State){newState=state}else if(typeof state==="object"){newState=state;newState.game=this.game}else if(typeof state==="function"){newState=new state(this.game)}this.states[key]=newState;if(autoStart){if(this.game.isBooted){this.start(key)}else{this._pendingState=key}}return newState},remove:function(key){if(this.current===key){this.callbackContext=null;this.onInitCallback=null;this.onShutDownCallback=null;this.onPreloadCallback=null;this.onLoadRenderCallback=null;this.onLoadUpdateCallback=null;this.onCreateCallback=null;this.onUpdateCallback=null;this.onRenderCallback=null;this.onPausedCallback=null;this.onResumedCallback=null;this.onPauseUpdateCallback=null}delete this.states[key]},start:function(key,clearWorld,clearCache){if(typeof clearWorld==="undefined"){clearWorld=true}if(typeof clearCache==="undefined"){clearCache=false}if(this.checkState(key)){this._pendingState=key; this._clearWorld=clearWorld;this._clearCache=clearCache;if(arguments.length>3){this._args=Array.prototype.splice.call(arguments,3)}}},restart:function(clearWorld,clearCache){if(typeof clearWorld==="undefined"){clearWorld=true}if(typeof clearCache==="undefined"){clearCache=false}this._pendingState=this.current;this._clearWorld=clearWorld;this._clearCache=clearCache;if(arguments.length>2){this._args=Array.prototype.splice.call(arguments,2)}},dummy:function(){},preUpdate:function(){if(this._pendingState&&this.game.isBooted){if(this.current){this.onShutDownCallback.call(this.callbackContext,this.game);this.game.tweens.removeAll();this.game.camera.reset();this.game.input.reset(true);this.game.physics.clear();this.game.time.removeAll();if(this._clearWorld){this.game.world.shutdown();if(this._clearCache===true){this.game.cache.destroy()}}}this.setCurrentState(this._pendingState);if(this.onPreloadCallback){this.game.load.reset();this.onPreloadCallback.call(this.callbackContext,this.game);if(this.game.load.totalQueuedFiles()===0){this.loadComplete()}else{this.game.load.start()}}else{this.loadComplete()}if(this.current===this._pendingState){this._pendingState=null}}},checkState:function(key){if(this.states[key]){var valid=false;if(this.states[key]["preload"]){valid=true}if(this.states[key]["create"]){valid=true}if(this.states[key]["update"]){valid=true}if(this.states[key]["render"]){valid=true}if(valid===false){console.warn("Invalid Phaser State object given. Must contain at least a one of the required functions: preload, create, update or render");return false}return true}else{console.warn("Phaser.StateManager - No state found with the key: "+key);return false}},link:function(key){this.states[key].game=this.game;this.states[key].add=this.game.add;this.states[key].make=this.game.make;this.states[key].camera=this.game.camera;this.states[key].cache=this.game.cache;this.states[key].input=this.game.input;this.states[key].load=this.game.load;this.states[key].math=this.game.math;this.states[key].sound=this.game.sound;this.states[key].scale=this.game.scale;this.states[key].state=this;this.states[key].stage=this.game.stage;this.states[key].time=this.game.time;this.states[key].tweens=this.game.tweens;this.states[key].world=this.game.world;this.states[key].particles=this.game.particles;this.states[key].rnd=this.game.rnd;this.states[key].physics=this.game.physics},setCurrentState:function(key){this.callbackContext=this.states[key];this.link(key);this.onInitCallback=this.states[key]["init"]||this.dummy;this.onPreloadCallback=this.states[key]["preload"]||null;this.onLoadRenderCallback=this.states[key]["loadRender"]||null;this.onLoadUpdateCallback=this.states[key]["loadUpdate"]||null;this.onCreateCallback=this.states[key]["create"]||null;this.onUpdateCallback=this.states[key]["update"]||null;this.onPreRenderCallback=this.states[key]["preRender"]||null;this.onRenderCallback=this.states[key]["render"]||null;this.onPausedCallback=this.states[key]["paused"]||null;this.onResumedCallback=this.states[key]["resumed"]||null;this.onPauseUpdateCallback=this.states[key]["pauseUpdate"]||null;this.onShutDownCallback=this.states[key]["shutdown"]||this.dummy;this.current=key;this._created=false;this.onInitCallback.apply(this.callbackContext,this._args);this._args=[]},getCurrentState:function(){return this.states[this.current]},loadComplete:function(){if(this._created===false&&this.onCreateCallback){this._created=true;this.onCreateCallback.call(this.callbackContext,this.game)}else{this._created=true}},pause:function(){if(this._created&&this.onPausedCallback){this.onPausedCallback.call(this.callbackContext,this.game)}},resume:function(){if(this._created&&this.onResumedCallback){this.onResumedCallback.call(this.callbackContext,this.game)}},update:function(){if(this._created&&this.onUpdateCallback){this.onUpdateCallback.call(this.callbackContext,this.game)}else{if(this.onLoadUpdateCallback){this.onLoadUpdateCallback.call(this.callbackContext,this.game)}}},pauseUpdate:function(){if(this._created&&this.onPauseUpdateCallback){this.onPauseUpdateCallback.call(this.callbackContext,this.game)}else{if(this.onLoadUpdateCallback){this.onLoadUpdateCallback.call(this.callbackContext,this.game)}}},preRender:function(){if(this.onPreRenderCallback){this.onPreRenderCallback.call(this.callbackContext,this.game)}},render:function(){if(this._created&&this.onRenderCallback){if(this.game.renderType===Phaser.CANVAS){this.game.context.save();this.game.context.setTransform(1,0,0,1,0,0)}this.onRenderCallback.call(this.callbackContext,this.game);if(this.game.renderType===Phaser.CANVAS){this.game.context.restore()}}else{if(this.onLoadRenderCallback){this.onLoadRenderCallback.call(this.callbackContext,this.game)}}},destroy:function(){this.callbackContext=null;this.onInitCallback=null;this.onShutDownCallback=null;this.onPreloadCallback=null;this.onLoadRenderCallback=null;this.onLoadUpdateCallback=null;this.onCreateCallback=null;this.onUpdateCallback=null;this.onRenderCallback=null;this.onPausedCallback=null;this.onResumedCallback=null;this.onPauseUpdateCallback=null;this.game=null;this.states={};this._pendingState=null}};Phaser.StateManager.prototype.constructor=Phaser.StateManager;Phaser.LinkedList=function(){this.next=null;this.prev=null;this.first=null;this.last=null;this.total=0};Phaser.LinkedList.prototype={add:function(child){if(this.total===0&&this.first===null&&this.last===null){this.first=child;this.last=child;this.next=child;child.prev=this;this.total++;return child}this.last.next=child;child.prev=this.last;this.last=child;this.total++;return child},reset:function(){this.first=null;this.last=null;this.next=null;this.prev=null;this.total=0},remove:function(child){if(this.total===1){this.reset();child.next=child.prev=null;return}if(child===this.first){this.first=this.first.next}else if(child===this.last){this.last=this.last.prev}if(child.prev){child.prev.next=child.next}if(child.next){child.next.prev=child.prev}child.next=child.prev=null;if(this.first===null){this.last=null}this.total--},callAll:function(callback){if(!this.first||!this.last){return}var entity=this.first;do{if(entity&&entity[callback]){entity[callback].call(entity)}entity=entity.next}while(entity!=this.last.next)}};Phaser.LinkedList.prototype.constructor=Phaser.LinkedList;Phaser.ArrayList=function(){this.total=0;this.position=0;this.list=[]};Phaser.ArrayList.prototype={add:function(child){if(!this.exists(child)){this.list.push(child);this.total++}return child},getIndex:function(child){return this.list.indexOf(child)},exists:function(child){return this.list.indexOf(child)>-1},reset:function(){this.list.length=0;this.total=0},remove:function(child){var idx=this.list.indexOf(child);if(idx>-1){this.list.splice(idx,1);this.total--;return child}},callAll:function(callback){var args=Array.prototype.splice.call(arguments,1);var i=this.list.length;while(i--){if(this.list[i]&&this.list[i][callback]){this.list[i][callback].apply(this.list[i],args)}}}};Object.defineProperty(Phaser.ArrayList.prototype,"first",{get:function(){this.position=0;if(this.total>0){return this.list[0]}else{return null}}});Object.defineProperty(Phaser.ArrayList.prototype,"next",{get:function(){if(this.position0){this.uniforms.mouse.x=pointer.x.toFixed(2)}if(pointer.y>0){this.uniforms.mouse.y=pointer.y.toFixed(2)}}this.uniforms.time.value=this.game.time.totalElapsedSeconds()},destroy:function(){this.game=null}};Phaser.Filter.prototype.constructor=Phaser.Filter;Object.defineProperty(Phaser.Filter.prototype,"width",{get:function(){return this.uniforms.resolution.value.x},set:function(value){this.uniforms.resolution.value.x=value}});Object.defineProperty(Phaser.Filter.prototype,"height",{get:function(){return this.uniforms.resolution.value.y},set:function(value){this.uniforms.resolution.value.y=value}});Phaser.Plugin=function(game,parent){if(typeof parent==="undefined"){parent=null}this.game=game;this.parent=parent;this.active=false;this.visible=false;this.hasPreUpdate=false;this.hasUpdate=false;this.hasPostUpdate=false;this.hasRender=false;this.hasPostRender=false};Phaser.Plugin.prototype={preUpdate:function(){},update:function(){},render:function(){},postRender:function(){},destroy:function(){this.game=null;this.parent=null;this.active=false;this.visible=false}};Phaser.Plugin.prototype.constructor=Phaser.Plugin;Phaser.PluginManager=function(game){this.game=game;this.plugins=[];this._len=0;this._i=0};Phaser.PluginManager.prototype={add:function(plugin){var args=Array.prototype.splice.call(arguments,1);var result=false;if(typeof plugin==="function"){plugin=new plugin(this.game,this)}else{plugin.game=this.game;plugin.parent=this}if(typeof plugin["preUpdate"]==="function"){plugin.hasPreUpdate=true;result=true}if(typeof plugin["update"]==="function"){plugin.hasUpdate=true;result=true}if(typeof plugin["postUpdate"]==="function"){plugin.hasPostUpdate=true;result=true}if(typeof plugin["render"]==="function"){plugin.hasRender=true;result=true}if(typeof plugin["postRender"]==="function"){plugin.hasPostRender=true;result=true}if(result){if(plugin.hasPreUpdate||plugin.hasUpdate||plugin.hasPostUpdate){plugin.active=true}if(plugin.hasRender||plugin.hasPostRender){plugin.visible=true}this._len=this.plugins.push(plugin);if(typeof plugin["init"]==="function"){plugin.init.apply(plugin,args)}return plugin}else{return null}},remove:function(plugin){this._i=this._len;while(this._i--){if(this.plugins[this._i]===plugin){plugin.destroy();this.plugins.splice(this._i,1);this._len--;return}}},removeAll:function(){this._i=this._len;while(this._i--){this.plugins[this._i].destroy()}this.plugins.length=0;this._len=0},preUpdate:function(){this._i=this._len;while(this._i--){if(this.plugins[this._i].active&&this.plugins[this._i].hasPreUpdate){this.plugins[this._i].preUpdate()}}},update:function(){this._i=this._len;while(this._i--){if(this.plugins[this._i].active&&this.plugins[this._i].hasUpdate){this.plugins[this._i].update()}}},postUpdate:function(){this._i=this._len;while(this._i--){if(this.plugins[this._i].active&&this.plugins[this._i].hasPostUpdate){this.plugins[this._i].postUpdate()}}},render:function(){this._i=this._len;while(this._i--){if(this.plugins[this._i].visible&&this.plugins[this._i].hasRender){this.plugins[this._i].render()}}},postRender:function(){this._i=this._len;while(this._i--){if(this.plugins[this._i].visible&&this.plugins[this._i].hasPostRender){this.plugins[this._i].postRender()}}},destroy:function(){this.removeAll();this.game=null}};Phaser.PluginManager.prototype.constructor=Phaser.PluginManager;Phaser.Stage=function(game,width,height){this.game=game;this.offset=new Phaser.Point;this.bounds=new Phaser.Rectangle(0,0,width,height);PIXI.Stage.call(this,0,false);this.name="_stage_root";this.interactive=false;this.disableVisibilityChange=false;this.checkOffsetInterval=2500;this.exists=true;this.currentRenderOrderID=0;this._hiddenVar="hidden";this._nextOffsetCheck=0;this._backgroundColor=0;if(game.config){this.parseConfig(game.config)}else{this.game.canvas=Phaser.Canvas.create(width,height);this.game.canvas.style["-webkit-full-screen"]="width: 100%; height: 100%"}};Phaser.Stage.prototype=Object.create(PIXI.Stage.prototype);Phaser.Stage.prototype.constructor=Phaser.Stage;Phaser.Stage.prototype.preUpdate=function(){this.currentRenderOrderID=0;var len=this.children.length;for(var i=0;ithis._nextOffsetCheck){Phaser.Canvas.getOffset(this.game.canvas,this.offset);this.bounds.x=this.offset.x;this.bounds.y=this.offset.y;this._nextOffsetCheck=this.game.time.now+this.checkOffsetInterval}}};Phaser.Stage.prototype.parseConfig=function(config){if(config["canvasID"]){this.game.canvas=Phaser.Canvas.create(this.game.width,this.game.height,config["canvasID"])}else{this.game.canvas=Phaser.Canvas.create(this.game.width,this.game.height)}if(config["canvasStyle"]){this.game.canvas.stlye=config["canvasStyle"]}else{this.game.canvas.style["-webkit-full-screen"]="width: 100%; height: 100%"}if(config["checkOffsetInterval"]){this.checkOffsetInterval=config["checkOffsetInterval"]}if(config["disableVisibilityChange"]){this.disableVisibilityChange=config["disableVisibilityChange"]}if(config["fullScreenScaleMode"]){this.fullScreenScaleMode=config["fullScreenScaleMode"]}if(config["scaleMode"]){this.scaleMode=config["scaleMode"]}if(config["backgroundColor"]){this.backgroundColor=config["backgroundColor"]}};Phaser.Stage.prototype.boot=function(){Phaser.Canvas.getOffset(this.game.canvas,this.offset);this.bounds.setTo(this.offset.x,this.offset.y,this.game.width,this.game.height);var _this=this;this._onChange=function(event){return _this.visibilityChange(event)};Phaser.Canvas.setUserSelect(this.game.canvas,"none");Phaser.Canvas.setTouchAction(this.game.canvas,"none");this.checkVisibility()};Phaser.Stage.prototype.checkVisibility=function(){if(document.webkitHidden!==undefined){this._hiddenVar="webkitvisibilitychange"}else if(document.mozHidden!==undefined){this._hiddenVar="mozvisibilitychange"}else if(document.msHidden!==undefined){this._hiddenVar="msvisibilitychange"}else if(document.hidden!==undefined){this._hiddenVar="visibilitychange"}else{this._hiddenVar=null}if(this._hiddenVar){document.addEventListener(this._hiddenVar,this._onChange,false)}window.onpagehide=this._onChange;window.onpageshow=this._onChange;window.onblur=this._onChange;window.onfocus=this._onChange};Phaser.Stage.prototype.visibilityChange=function(event){if(this.disableVisibilityChange){return}if(event.type==="pagehide"||event.type==="blur"||event.type==="pageshow"||event.type==="focus"){if(event.type==="pagehide"||event.type==="blur"){this.game.focusLoss(event)}else if(event.type==="pageshow"||event.type==="focus"){this.game.focusGain(event)}return}if(document.hidden||document.mozHidden||document.msHidden||document.webkitHidden){this.game.gamePaused(event)}else{this.game.gameResumed(event)}};Phaser.Stage.prototype.setBackgroundColor=function(backgroundColor){if(typeof backgroundColor==="string"){var rgb=Phaser.Color.hexToColor(backgroundColor);this._backgroundColor=Phaser.Color.getColor(rgb.r,rgb.g,rgb.b)}else{var rgb=Phaser.Color.getRGB(backgroundColor);this._backgroundColor=backgroundColor}this.backgroundColorSplit=[rgb.r/255,rgb.g/255,rgb.b/255];this.backgroundColorString=Phaser.Color.RGBtoString(rgb.r,rgb.g,rgb.b,255,"#")};Object.defineProperty(Phaser.Stage.prototype,"backgroundColor",{get:function(){return this._backgroundColor},set:function(color){if(!this.game.transparent){this.setBackgroundColor(color)}}});Object.defineProperty(Phaser.Stage.prototype,"smoothed",{get:function(){return!PIXI.scaleModes.LINEAR},set:function(value){if(value){PIXI.scaleModes.LINEAR=0}else{PIXI.scaleModes.LINEAR=1}}});Phaser.Group=function(game,parent,name,addToStage,enableBody,physicsBodyType){if(typeof addToStage==="undefined"){addToStage=false}if(typeof enableBody==="undefined"){enableBody=false}if(typeof physicsBodyType==="undefined"){physicsBodyType=Phaser.Physics.ARCADE}this.game=game;if(typeof parent==="undefined"){parent=game.world}this.name=name||"group";PIXI.DisplayObjectContainer.call(this);if(addToStage){this.game.stage.addChild(this)}else{if(parent){parent.addChild(this)}}this.z=0;this.type=Phaser.GROUP;this.alive=true;this.exists=true;this.classType=Phaser.Sprite;this.scale=new Phaser.Point(1,1);this.cursor=null;this.cameraOffset=new Phaser.Point;this.enableBody=enableBody;this.enableBodyDebug=false;this.physicsBodyType=physicsBodyType;this._sortProperty="z";this._cache=[0,0,0,0,1,0,1,0,0,0]};Phaser.Group.prototype=Object.create(PIXI.DisplayObjectContainer.prototype);Phaser.Group.prototype.constructor=Phaser.Group;Phaser.Group.RETURN_NONE=0;Phaser.Group.RETURN_TOTAL=1;Phaser.Group.RETURN_CHILD=2;Phaser.Group.SORT_ASCENDING=-1;Phaser.Group.SORT_DESCENDING=1;Phaser.Group.prototype.add=function(child){if(child.parent!==this){if(this.enableBody){this.game.physics.enable(child,this.physicsBodyType)}this.addChild(child);child.z=this.children.length;if(child.events){child.events.onAddedToGroup.dispatch(child,this)}if(this.cursor===null){this.cursor=child}}return child};Phaser.Group.prototype.addAt=function(child,index){if(child.parent!==this){if(this.enableBody){this.game.physics.enable(child,this.physicsBodyType)}this.addChildAt(child,index);this.updateZ();if(child.events){child.events.onAddedToGroup.dispatch(child,this)}if(this.cursor===null){this.cursor=child}}return child};Phaser.Group.prototype.getAt=function(index){if(index<0||index>=this.children.length){return-1}else{return this.getChildAt(index)}};Phaser.Group.prototype.create=function(x,y,key,frame,exists){if(typeof exists==="undefined"){exists=true}var child=new this.classType(this.game,x,y,key,frame);if(this.enableBody){this.game.physics.enable(child,this.physicsBodyType)}child.exists=exists;child.visible=exists;child.alive=exists;this.addChild(child);child.z=this.children.length;if(child.events){child.events.onAddedToGroup.dispatch(child,this)}if(this.cursor===null){this.cursor=child}return child};Phaser.Group.prototype.createMultiple=function(quantity,key,frame,exists){if(typeof exists==="undefined"){exists=false}for(var i=0;ithis.children.length-1){index=0}if(this.cursor){this._cache[8]=index;this.cursor=this.children[this._cache[8]];return this.cursor}};Phaser.Group.prototype.next=function(){if(this.cursor){if(this._cache[8]>=this.children.length-1){this._cache[8]=0}else{this._cache[8]++}this.cursor=this.children[this._cache[8]];return this.cursor}};Phaser.Group.prototype.previous=function(){if(this.cursor){if(this._cache[8]===0){this._cache[8]=this.children.length-1}else{this._cache[8]--}this.cursor=this.children[this._cache[8]];return this.cursor}};Phaser.Group.prototype.swap=function(child1,child2){var result=this.swapChildren(child1,child2);if(result){this.updateZ()}return result};Phaser.Group.prototype.bringToTop=function(child){if(child.parent===this&&this.getIndex(child)0){this.remove(child);this.addAt(child,0)}return child};Phaser.Group.prototype.moveUp=function(child){if(child.parent===this&&this.getIndex(child)0){var a=this.getIndex(child);var b=this.getAt(a-1);if(b){this.swap(child,b)}}return child};Phaser.Group.prototype.xy=function(index,x,y){if(index<0||index>this.children.length){return-1}else{this.getChildAt(index).x=x;this.getChildAt(index).y=y}};Phaser.Group.prototype.reverse=function(){this.children.reverse();this.updateZ()};Phaser.Group.prototype.getIndex=function(child){return this.children.indexOf(child)};Phaser.Group.prototype.replace=function(oldChild,newChild){var index=this.getIndex(oldChild);if(index!==-1){if(newChild.parent!==undefined){newChild.events.onRemovedFromGroup.dispatch(newChild,this);newChild.parent.removeChild(newChild);if(newChild.parent instanceof Phaser.Group){newChild.parent.updateZ()}}var temp=oldChild;this.remove(temp);this.addAt(newChild,index);return temp}};Phaser.Group.prototype.hasProperty=function(child,key){var len=key.length;if(len===1&&key[0]in child){return true}else if(len===2&&key[0]in child&&key[1]in child[key[0]]){return true}else if(len===3&&key[0]in child&&key[1]in child[key[0]]&&key[2]in child[key[0]][key[1]]){return true}else if(len===4&&key[0]in child&&key[1]in child[key[0]]&&key[2]in child[key[0]][key[1]]&&key[3]in child[key[0]][key[1]][key[2]]){return true}return false};Phaser.Group.prototype.setProperty=function(child,key,value,operation,force){if(typeof force==="undefined"){force=false}operation=operation||0;if(!this.hasProperty(child,key)&&(!force||operation>0)){return false}var len=key.length;if(len===1){if(operation===0){child[key[0]]=value}else if(operation==1){child[key[0]]+=value}else if(operation==2){child[key[0]]-=value}else if(operation==3){child[key[0]]*=value}else if(operation==4){child[key[0]]/=value}}else if(len===2){if(operation===0){child[key[0]][key[1]]=value}else if(operation==1){child[key[0]][key[1]]+=value}else if(operation==2){child[key[0]][key[1]]-=value}else if(operation==3){child[key[0]][key[1]]*=value}else if(operation==4){child[key[0]][key[1]]/=value}}else if(len===3){if(operation===0){child[key[0]][key[1]][key[2]]=value}else if(operation==1){child[key[0]][key[1]][key[2]]+=value}else if(operation==2){child[key[0]][key[1]][key[2]]-=value}else if(operation==3){child[key[0]][key[1]][key[2]]*=value}else if(operation==4){child[key[0]][key[1]][key[2]]/=value}}else if(len===4){if(operation===0){child[key[0]][key[1]][key[2]][key[3]]=value}else if(operation==1){child[key[0]][key[1]][key[2]][key[3]]+=value}else if(operation==2){child[key[0]][key[1]][key[2]][key[3]]-=value}else if(operation==3){child[key[0]][key[1]][key[2]][key[3]]*=value}else if(operation==4){child[key[0]][key[1]][key[2]][key[3]]/=value}}return true};Phaser.Group.prototype.set=function(child,key,value,checkAlive,checkVisible,operation,force){if(typeof force==="undefined"){force=false}key=key.split(".");if(typeof checkAlive==="undefined"){checkAlive=false}if(typeof checkVisible==="undefined"){checkVisible=false}if((checkAlive===false||checkAlive&&child.alive)&&(checkVisible===false||checkVisible&&child.visible)){return this.setProperty(child,key,value,operation,force)}};Phaser.Group.prototype.setAll=function(key,value,checkAlive,checkVisible,operation,force){if(typeof checkAlive==="undefined"){checkAlive=false}if(typeof checkVisible==="undefined"){checkVisible=false}if(typeof force==="undefined"){force=false}key=key.split(".");operation=operation||0;for(var i=0,len=this.children.length;ib[this._sortProperty]){return 1}else{if(a.zb[this._sortProperty]){return-1}else{return 0}};Phaser.Group.prototype.iterate=function(key,value,returnType,callback,callbackContext,args){if(returnType===Phaser.Group.RETURN_TOTAL&&this.children.length===0){return 0}if(typeof callback==="undefined"){callback=false}var total=0;for(var i=0,len=this.children.length;i0){return this.children[this.children.length-1]}};Phaser.Group.prototype.getBottom=function(){if(this.children.length>0){return this.children[0]}};Phaser.Group.prototype.countLiving=function(){return this.iterate("alive",true,Phaser.Group.RETURN_TOTAL)};Phaser.Group.prototype.countDead=function(){return this.iterate("alive",false,Phaser.Group.RETURN_TOTAL)};Phaser.Group.prototype.getRandom=function(startIndex,length){if(this.children.length===0){return null}startIndex=startIndex||0;length=length||this.children.length;return this.game.math.getRandom(this.children,startIndex,length)};Phaser.Group.prototype.remove=function(child,destroy){if(typeof destroy==="undefined"){destroy=false}if(this.children.length===0||this.children.indexOf(child)===-1){return false}if(child.events&&!child.destroyPhase){child.events.onRemovedFromGroup.dispatch(child,this)}var removed=this.removeChild(child);this.updateZ();if(this.cursor===child){this.next()}if(destroy&&removed){removed.destroy(true)}return true};Phaser.Group.prototype.removeAll=function(destroy){if(typeof destroy==="undefined"){destroy=false}if(this.children.length===0){return}do{if(this.children[0].events){this.children[0].events.onRemovedFromGroup.dispatch(this.children[0],this)}var removed=this.removeChild(this.children[0]);if(destroy&&removed){removed.destroy(true)}}while(this.children.length>0);this.cursor=null};Phaser.Group.prototype.removeBetween=function(startIndex,endIndex,destroy){if(typeof endIndex==="undefined"){endIndex=this.children.length}if(typeof destroy==="undefined"){destroy=false}if(this.children.length===0){return}if(startIndex>endIndex||startIndex<0||endIndex>this.children.length){return false}var i=endIndex;while(i>=startIndex){if(this.children[i].events){this.children[i].events.onRemovedFromGroup.dispatch(this.children[i],this)}var removed=this.removeChild(this.children[i]);if(destroy&&removed){removed.destroy(true)}if(this.cursor===this.children[i]){this.cursor=null}i--}this.updateZ()};Phaser.Group.prototype.destroy=function(destroyChildren,soft){if(this.game===null){return}if(typeof destroyChildren==="undefined"){destroyChildren=true}if(typeof soft==="undefined"){soft=false}this.removeAll(destroyChildren);this.cursor=null;if(!soft){if(this.parent){this.parent.removeChild(this)}this.game=null;this.exists=false}};Object.defineProperty(Phaser.Group.prototype,"total",{get:function(){return this.iterate("exists",true,Phaser.Group.RETURN_TOTAL)}});Object.defineProperty(Phaser.Group.prototype,"length",{get:function(){return this.children.length}});Object.defineProperty(Phaser.Group.prototype,"angle",{get:function(){return Phaser.Math.radToDeg(this.rotation)},set:function(value){this.rotation=Phaser.Math.degToRad(value)}});Object.defineProperty(Phaser.Group.prototype,"fixedToCamera",{get:function(){return!!this._cache[7]},set:function(value){if(value){this._cache[7]=1;this.cameraOffset.set(this.x,this.y)}else{this._cache[7]=0}}});Phaser.World=function(game){Phaser.Group.call(this,game,null,"__world",false);this.bounds=new Phaser.Rectangle(0,0,game.width,game.height);this.camera=null};Phaser.World.prototype=Object.create(Phaser.Group.prototype);Phaser.World.prototype.constructor=Phaser.World;Phaser.World.prototype.boot=function(){this.camera=new Phaser.Camera(this.game,0,0,0,this.game.width,this.game.height);this.camera.displayObject=this;this.camera.scale=this.scale;this.game.camera=this.camera;this.game.stage.addChild(this)};Phaser.World.prototype.setBounds=function(x,y,width,height){if(widththis.bounds.right){sprite.x=this.bounds.left-padding}if(sprite.y+paddingthis.bounds.bottom){sprite.y=this.bounds.top-padding}}else{sprite.getBounds();if(sprite._currentBounds.rightthis.bounds.right){sprite.x=this.bounds.left}if(sprite._currentBounds.bottomthis.bounds.bottom){sprite.y=this.bounds.top}}};Object.defineProperty(Phaser.World.prototype,"width",{get:function(){return this.bounds.width},set:function(value){this.bounds.width=value}});Object.defineProperty(Phaser.World.prototype,"height",{get:function(){return this.bounds.height},set:function(value){this.bounds.height=value}});Object.defineProperty(Phaser.World.prototype,"centerX",{get:function(){return this.bounds.halfWidth}});Object.defineProperty(Phaser.World.prototype,"centerY",{get:function(){return this.bounds.halfHeight}});Object.defineProperty(Phaser.World.prototype,"randomX",{get:function(){if(this.bounds.x<0){return this.game.rnd.integerInRange(this.bounds.x,this.bounds.width-Math.abs(this.bounds.x))}else{return this.game.rnd.integerInRange(this.bounds.x,this.bounds.width)}}});Object.defineProperty(Phaser.World.prototype,"randomY",{get:function(){if(this.bounds.y<0){return this.game.rnd.integerInRange(this.bounds.y,this.bounds.height-Math.abs(this.bounds.y))}else{return this.game.rnd.integerInRange(this.bounds.y,this.bounds.height)}}});Phaser.ScaleManager=function(game,width,height){this.game=game;this.width=width;this.height=height;this.minWidth=null;this.maxWidth=null;this.minHeight=null;this.maxHeight=null;this.forceLandscape=false;this.forcePortrait=false;this.incorrectOrientation=false;this.pageAlignHorizontally=false;this.pageAlignVertically=false;this.maxIterations=5;this.orientationSprite=null;this.enterLandscape=new Phaser.Signal;this.enterPortrait=new Phaser.Signal;this.enterIncorrectOrientation=new Phaser.Signal;this.leaveIncorrectOrientation=new Phaser.Signal;this.hasResized=new Phaser.Signal;this.fullScreenTarget=this.game.canvas;this.enterFullScreen=new Phaser.Signal;this.leaveFullScreen=new Phaser.Signal;this.orientation=0;if(window["orientation"]){this.orientation=window["orientation"]}else{if(window.outerWidth>window.outerHeight){this.orientation=90}}this.scaleFactor=new Phaser.Point(1,1);this.scaleFactorInversed=new Phaser.Point(1,1);this.margin=new Phaser.Point(0,0);this.bounds=new Phaser.Rectangle(0,0,width,height);this.aspectRatio=0;this.sourceAspectRatio=width/height;this.event=null;this.scaleMode=Phaser.ScaleManager.NO_SCALE;this.fullScreenScaleMode=Phaser.ScaleManager.NO_SCALE;this._startHeight=0;this._width=0;this._height=0;this._check=null;var _this=this;window.addEventListener("orientationchange",function(event){return _this.checkOrientation(event)},false);window.addEventListener("resize",function(event){return _this.checkResize(event)},false);document.addEventListener("webkitfullscreenchange",function(event){return _this.fullScreenChange(event)},false);document.addEventListener("mozfullscreenchange",function(event){return _this.fullScreenChange(event)},false);document.addEventListener("fullscreenchange",function(event){return _this.fullScreenChange(event)},false)};Phaser.ScaleManager.EXACT_FIT=0;Phaser.ScaleManager.NO_SCALE=1;Phaser.ScaleManager.SHOW_ALL=2;Phaser.ScaleManager.prototype={startFullScreen:function(antialias){if(this.isFullScreen||!this.game.device.fullscreen){return}if(typeof antialias!=="undefined"&&this.game.renderType===Phaser.CANVAS){this.game.stage.smoothed=antialias}this._width=this.width;this._height=this.height;if(this.game.device.fullscreenKeyboard){this.fullScreenTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT)}else{this.fullScreenTarget[this.game.device.requestFullscreen]()}},stopFullScreen:function(){this.fullScreenTarget[this.game.device.cancelFullscreen]()},fullScreenChange:function(event){this.event=event;if(this.isFullScreen){if(this.fullScreenScaleMode===Phaser.ScaleManager.EXACT_FIT){this.fullScreenTarget.style["width"]="100%";this.fullScreenTarget.style["height"]="100%";this.width=window.outerWidth;this.height=window.outerHeight;this.game.input.scale.setTo(this.game.width/this.width,this.game.height/this.height);this.aspectRatio=this.width/this.height;this.scaleFactor.x=this.game.width/this.width;this.scaleFactor.y=this.game.height/this.height;this.checkResize()}else if(this.fullScreenScaleMode===Phaser.ScaleManager.SHOW_ALL){this.setShowAll();this.refresh()}this.enterFullScreen.dispatch(this.width,this.height)}else{this.fullScreenTarget.style["width"]=this.game.width+"px";this.fullScreenTarget.style["height"]=this.game.height+"px";this.width=this._width;this.height=this._height;this.game.input.scale.setTo(this.game.width/this.width,this.game.height/this.height);this.aspectRatio=this.width/this.height;this.scaleFactor.x=this.game.width/this.width;this.scaleFactor.y=this.game.height/this.height;this.leaveFullScreen.dispatch(this.width,this.height)}},forceOrientation:function(forceLandscape,forcePortrait,orientationImage){if(typeof forcePortrait==="undefined"){forcePortrait=false}this.forceLandscape=forceLandscape;this.forcePortrait=forcePortrait;if(typeof orientationImage!=="undefined"){if(orientationImage===null||this.game.cache.checkImageKey(orientationImage)===false){orientationImage="__default"}this.orientationSprite=new Phaser.Image(this.game,this.game.width/2,this.game.height/2,PIXI.TextureCache[orientationImage]);this.orientationSprite.anchor.set(.5);this.checkOrientationState();if(this.incorrectOrientation){this.orientationSprite.visible=true;this.game.world.visible=false}else{this.orientationSprite.visible=false;this.game.world.visible=true}this.game.stage.addChild(this.orientationSprite)}},checkOrientationState:function(){if(this.incorrectOrientation){if(this.forceLandscape&&window.innerWidth>window.innerHeight||this.forcePortrait&&window.innerHeight>window.innerWidth){this.incorrectOrientation=false;this.leaveIncorrectOrientation.dispatch();if(this.orientationSprite){this.orientationSprite.visible=false;this.game.world.visible=true}if(this.scaleMode!==Phaser.ScaleManager.NO_SCALE){this.refresh()}}}else{if(this.forceLandscape&&window.innerWidthwindow.outerHeight){this.orientation=90}else{this.orientation=0}if(this.isLandscape){this.enterLandscape.dispatch(this.orientation,true,false)}else{this.enterPortrait.dispatch(this.orientation,false,true)}if(this.scaleMode!==Phaser.ScaleManager.NO_SCALE){this.refresh()}this.checkOrientationState()},refresh:function(){if(!this.game.device.iPad&&!this.game.device.webApp&&!this.game.device.desktop){if(this.game.device.android&&!this.game.device.chrome){window.scrollTo(0,1)}else{window.scrollTo(0,0)}}if(this._check===null&&this.maxIterations>0){this._iterations=this.maxIterations;var _this=this;this._check=window.setInterval(function(){return _this.setScreenSize()},10);this.setScreenSize()}},setScreenSize:function(force){if(typeof force==="undefined"){force=false}if(!this.game.device.iPad&&!this.game.device.webApp&&!this.game.device.desktop){if(this.game.device.android&&!this.game.device.chrome){window.scrollTo(0,1)}else{window.scrollTo(0,0)}}this._iterations--;if(force||window.innerHeight>this._startHeight||this._iterations<0){document.documentElement["style"].minHeight=window.innerHeight+"px";if(this.incorrectOrientation){this.setMaximum()}else if(!this.isFullScreen){if(this.scaleMode===Phaser.ScaleManager.EXACT_FIT){this.setExactFit()}else if(this.scaleMode===Phaser.ScaleManager.SHOW_ALL){this.setShowAll()}}else{if(this.fullScreenScaleMode===Phaser.ScaleManager.EXACT_FIT){this.setExactFit()}else if(this.fullScreenScaleMode===Phaser.ScaleManager.SHOW_ALL){this.setShowAll()}}this.setSize();clearInterval(this._check);this._check=null}},setSize:function(){if(!this.incorrectOrientation){if(this.maxWidth&&this.width>this.maxWidth){this.width=this.maxWidth}if(this.maxHeight&&this.height>this.maxHeight){this.height=this.maxHeight}if(this.minWidth&&this.widththis.maxWidth){this.width=this.maxWidth}else{this.width=availableWidth}if(this.maxHeight&&availableHeight>this.maxHeight){this.height=this.maxHeight}else{this.height=availableHeight}}};Phaser.ScaleManager.prototype.constructor=Phaser.ScaleManager;Object.defineProperty(Phaser.ScaleManager.prototype,"isFullScreen",{get:function(){return document["fullscreenElement"]||document["mozFullScreenElement"]||document["webkitFullscreenElement"]}});Object.defineProperty(Phaser.ScaleManager.prototype,"isPortrait",{get:function(){return this.orientation===0||this.orientation===180}});Object.defineProperty(Phaser.ScaleManager.prototype,"isLandscape",{get:function(){return this.orientation===90||this.orientation===-90}});Phaser.Game=function(width,height,renderer,parent,state,transparent,antialias,physicsConfig){this.id=Phaser.GAMES.push(this)-1;this.config=null;this.physicsConfig=physicsConfig;this.parent="";this.width=800;this.height=600;this.transparent=false;this.antialias=true;this.renderer=null;this.renderType=Phaser.AUTO;this.state=null;this.isBooted=false;this.isRunning=false;this.raf=null;this.add=null;this.make=null;this.cache=null;this.input=null;this.load=null;this.math=null;this.net=null;this.scale=null;this.sound=null;this.stage=null;this.time=null;this.tweens=null;this.world=null;this.physics=null;this.rnd=null;this.device=null;this.camera=null;this.canvas=null;this.context=null;this.debug=null;this.particles=null;this.stepping=false;this.pendingStep=false;this.stepCount=0;this.onPause=null;this.onResume=null;this.onBlur=null;this.onFocus=null;this._paused=false;this._codePaused=false;if(arguments.length===1&&typeof arguments[0]==="object"){this.parseConfig(arguments[0])}else{if(typeof width!=="undefined"){this.width=width}if(typeof height!=="undefined"){this.height=height}if(typeof renderer!=="undefined"){this.renderer=renderer;this.renderType=renderer}if(typeof parent!=="undefined"){this.parent=parent}if(typeof transparent!=="undefined"){this.transparent=transparent}if(typeof antialias!=="undefined"){this.antialias=antialias}this.rnd=new Phaser.RandomDataGenerator([(Date.now()*Math.random()).toString()]);this.state=new Phaser.StateManager(this,state)}var _this=this;this._onBoot=function(){return _this.boot()};if(document.readyState==="complete"||document.readyState==="interactive"){window.setTimeout(this._onBoot,0)}else{document.addEventListener("DOMContentLoaded",this._onBoot,false);window.addEventListener("load",this._onBoot,false)}return this};Phaser.Game.prototype={parseConfig:function(config){this.config=config;if(config["width"]){this.width=Phaser.Utils.parseDimension(config["width"],0)}if(config["height"]){this.height=Phaser.Utils.parseDimension(config["height"],1)}if(config["renderer"]){this.renderer=config["renderer"];this.renderType=config["renderer"]}if(config["parent"]){this.parent=config["parent"]}if(config["transparent"]){this.transparent=config["transparent"]}if(config["antialias"]){this.antialias=config["antialias"]}if(config["physicsConfig"]){this.physicsConfig=config["physicsConfig"]}var seed=[(Date.now()*Math.random()).toString()];if(config["seed"]){seed=config["seed"]}this.rnd=new Phaser.RandomDataGenerator(seed);var state=null;if(config["state"]){state=config["state"]}this.state=new Phaser.StateManager(this,state)},boot:function(){if(this.isBooted){return}if(!document.body){window.setTimeout(this._onBoot,20)}else{document.removeEventListener("DOMContentLoaded",this._onBoot);window.removeEventListener("load",this._onBoot);this.onPause=new Phaser.Signal;this.onResume=new Phaser.Signal;this.onBlur=new Phaser.Signal;this.onFocus=new Phaser.Signal;this.isBooted=true;this.device=new Phaser.Device(this);this.math=Phaser.Math;this.stage=new Phaser.Stage(this,this.width,this.height);this.scale=new Phaser.ScaleManager(this,this.width,this.height);this.setUpRenderer();this.device.checkFullScreenSupport();this.world=new Phaser.World(this);this.add=new Phaser.GameObjectFactory(this);this.make=new Phaser.GameObjectCreator(this);this.cache=new Phaser.Cache(this);this.load=new Phaser.Loader(this);this.time=new Phaser.Time(this);this.tweens=new Phaser.TweenManager(this);this.input=new Phaser.Input(this);this.sound=new Phaser.SoundManager(this);this.physics=new Phaser.Physics(this,this.physicsConfig);this.particles=new Phaser.Particles(this);this.plugins=new Phaser.PluginManager(this);this.net=new Phaser.Net(this);this.debug=new Phaser.Utils.Debug(this);this.scratch=new Phaser.BitmapData(this,"__root",1024,1024);this.time.boot();this.stage.boot();this.world.boot();this.input.boot();this.sound.boot();this.state.boot();this.debug.boot();this.showDebugHeader();this.isRunning=true;if(this.config&&this.config["forceSetTimeOut"]){this.raf=new Phaser.RequestAnimationFrame(this,this.config["forceSetTimeOut"])}else{this.raf=new Phaser.RequestAnimationFrame(this,false)}this.raf.start()}},showDebugHeader:function(){var v=Phaser.VERSION;var r="Canvas";var a="HTML Audio";var c=1;if(this.renderType===Phaser.WEBGL){r="WebGL";c++}else if(this.renderType==Phaser.HEADLESS){r="Headless"}if(this.device.webAudio){a="WebAudio";c++}if(this.device.chrome){var args=["%c %c %c Phaser v"+v+" - "+r+" - "+a+" %c %c "+" http://phaser.io %c %c ♥%c♥%c♥ ","background: #0cf300","background: #00bc17","color: #ffffff; background: #00711f;","background: #00bc17","background: #0cf300","background: #00bc17"];for(var i=0;i<3;i++){if(i0;i--){if(this["pointer"+i]===null){next=i}}if(next===0){console.warn("You can only have 10 Pointer objects");return null}else{this["pointer"+next]=new Phaser.Pointer(this.game,next);return this["pointer"+next]}},update:function(){this.keyboard.update();if(this.pollRate>0&&this._pollCounterx1&&this._localPoint.xy1&&this._localPoint.yx1&&this._localPoint.xy1&&this._localPoint.y0&&this._pollCounter=this.game.input.holdRate){if(this.game.input.multiInputOverride==Phaser.Input.MOUSE_OVERRIDES_TOUCH||this.game.input.multiInputOverride==Phaser.Input.MOUSE_TOUCH_COMBINE||this.game.input.multiInputOverride==Phaser.Input.TOUCH_OVERRIDES_MOUSE&&this.game.input.currentPointers===0){this.game.input.onHold.dispatch(this)}this._holdSent=true}if(this.game.input.recordPointerHistory&&this.game.time.now>=this._nextDrop){this._nextDrop=this.game.time.now+this.game.input.recordRate;this._history.push({x:this.position.x,y:this.position.y});if(this._history.length>this.game.input.recordLimit){this._history.shift()}}}},move:function(event,fromClick){if(this.game.input.pollLocked){return}if(typeof fromClick==="undefined"){fromClick=false}if(typeof event.button!=="undefined"){this.button=event.button}this.clientX=event.clientX;this.clientY=event.clientY;this.pageX=event.pageX;this.pageY=event.pageY;this.screenX=event.screenX;this.screenY=event.screenY;if(this.isMouse&&this.game.input.mouse.locked&&!fromClick){this.rawMovementX=event.movementX||event.mozMovementX||event.webkitMovementX||0;this.rawMovementY=event.movementY||event.mozMovementY||event.webkitMovementY||0;this.movementX+=this.rawMovementX;this.movementY+=this.rawMovementY}this.x=(this.pageX-this.game.stage.offset.x)*this.game.input.scale.x;this.y=(this.pageY-this.game.stage.offset.y)*this.game.input.scale.y;this.position.setTo(this.x,this.y);this.circle.x=this.x;this.circle.y=this.y;if(this.game.input.multiInputOverride===Phaser.Input.MOUSE_OVERRIDES_TOUCH||this.game.input.multiInputOverride===Phaser.Input.MOUSE_TOUCH_COMBINE||this.game.input.multiInputOverride===Phaser.Input.TOUCH_OVERRIDES_MOUSE&&this.game.input.currentPointers===0){this.game.input.activePointer=this;this.game.input.x=this.x;this.game.input.y=this.y;this.game.input.position.setTo(this.game.input.x,this.game.input.y);this.game.input.circle.x=this.game.input.x;this.game.input.circle.y=this.game.input.y}this.withinGame=this.game.scale.bounds.contains(this.pageX,this.pageY);if(this.game.paused){return this}if(this.game.input.moveCallback){this.game.input.moveCallback.call(this.game.input.moveCallbackContext,this,this.x,this.y)}var i=this.game.input.moveCallbacks.length;while(i--){this.game.input.moveCallbacks[i].callback.call(this.game.input.moveCallbacks[i].context,this,this.x,this.y)}if(this.targetObject!==null&&this.targetObject.isDragged===true){if(this.targetObject.update(this)===false){this.targetObject=null}return this}this._highestRenderOrderID=Number.MAX_SAFE_INTEGER;this._highestRenderObject=null;this._highestInputPriorityID=-1;if(this.game.input.interactiveItems.total>0){var currentNode=this.game.input.interactiveItems.first;do{if(currentNode&¤tNode.validForInput(this._highestInputPriorityID,this._highestRenderOrderID)){if(!fromClick&¤tNode.checkPointerOver(this)||fromClick&¤tNode.checkPointerDown(this)){this._highestRenderOrderID=currentNode.sprite._cache[3];this._highestInputPriorityID=currentNode.priorityID;this._highestRenderObject=currentNode}}currentNode=this.game.input.interactiveItems.next}while(currentNode!==null)}if(this._highestRenderObject===null){if(this.targetObject){this.targetObject._pointerOutHandler(this);this.targetObject=null}}else{if(this.targetObject===null){this.targetObject=this._highestRenderObject;this._highestRenderObject._pointerOverHandler(this)}else{if(this.targetObject===this._highestRenderObject){if(this._highestRenderObject.update(this)===false){this.targetObject=null}}else{this.targetObject._pointerOutHandler(this);this.targetObject=this._highestRenderObject;this.targetObject._pointerOverHandler(this)}}}return this},leave:function(event){this.withinGame=false;this.move(event,false)},stop:function(event){if(this._stateReset){event.preventDefault();return}this.timeUp=this.game.time.now;if(this.game.input.multiInputOverride===Phaser.Input.MOUSE_OVERRIDES_TOUCH||this.game.input.multiInputOverride===Phaser.Input.MOUSE_TOUCH_COMBINE||this.game.input.multiInputOverride===Phaser.Input.TOUCH_OVERRIDES_MOUSE&&this.game.input.currentPointers===0){this.game.input.onUp.dispatch(this,event);if(this.duration>=0&&this.duration<=this.game.input.tapRate){if(this.timeUp-this.previousTapTime0){this.active=false}this.withinGame=false;this.isDown=false;this.isUp=true;this.pointerId=null;this.identifier=null;this.positionUp.setTo(this.x,this.y);if(this.isMouse===false){this.game.input.currentPointers--}this.game.input.interactiveItems.callAll("_releasedHandler",this);this.targetObject=null;return this},justPressed:function(duration){duration=duration||this.game.input.justPressedRate;return this.isDown===true&&this.timeDown+duration>this.game.time.now},justReleased:function(duration){duration=duration||this.game.input.justReleasedRate;return this.isUp===true&&this.timeUp+duration>this.game.time.now},reset:function(){if(this.isMouse===false){this.active=false}this.pointerId=null;this.identifier=null;this.isDown=false;this.isUp=true;this.totalTouches=0;this._holdSent=false;this._history.length=0;this._stateReset=true;if(this.targetObject){this.targetObject._releasedHandler(this)}this.targetObject=null},resetMovement:function(){this.movementX=0;this.movementY=0}};Phaser.Pointer.prototype.constructor=Phaser.Pointer;Object.defineProperty(Phaser.Pointer.prototype,"duration",{get:function(){if(this.isUp){return-1}return this.game.time.now-this.timeDown}});Object.defineProperty(Phaser.Pointer.prototype,"worldX",{get:function(){return this.game.world.camera.x+this.x}});Object.defineProperty(Phaser.Pointer.prototype,"worldY",{get:function(){return this.game.world.camera.y+this.y}});Phaser.Touch=function(game){this.game=game;this.disabled=false;this.callbackContext=this.game;this.touchStartCallback=null;this.touchMoveCallback=null;this.touchEndCallback=null;this.touchEnterCallback=null;this.touchLeaveCallback=null;this.touchCancelCallback=null;this.preventDefault=true;this.event=null;this._onTouchStart=null;this._onTouchMove=null;this._onTouchEnd=null;this._onTouchEnter=null;this._onTouchLeave=null;this._onTouchCancel=null;this._onTouchMove=null};Phaser.Touch.prototype={start:function(){if(this._onTouchStart!==null){return}var _this=this;if(this.game.device.touch){this._onTouchStart=function(event){return _this.onTouchStart(event)};this._onTouchMove=function(event){return _this.onTouchMove(event)};this._onTouchEnd=function(event){return _this.onTouchEnd(event)};this._onTouchEnter=function(event){return _this.onTouchEnter(event)};this._onTouchLeave=function(event){return _this.onTouchLeave(event)};this._onTouchCancel=function(event){return _this.onTouchCancel(event)};this.game.canvas.addEventListener("touchstart",this._onTouchStart,false);this.game.canvas.addEventListener("touchmove",this._onTouchMove,false);this.game.canvas.addEventListener("touchend",this._onTouchEnd,false);this.game.canvas.addEventListener("touchenter",this._onTouchEnter,false);this.game.canvas.addEventListener("touchleave",this._onTouchLeave,false);this.game.canvas.addEventListener("touchcancel",this._onTouchCancel,false)}},consumeDocumentTouches:function(){this._documentTouchMove=function(event){event.preventDefault()};document.addEventListener("touchmove",this._documentTouchMove,false)},onTouchStart:function(event){this.event=event;if(this.touchStartCallback){this.touchStartCallback.call(this.callbackContext,event)}if(this.game.input.disabled||this.disabled){return}if(this.preventDefault){event.preventDefault()}for(var i=0;i0&&axis>this.deadZone||axis<0&&axis<-this.deadZone){this.processAxisChange({axis:j,value:axis})}else{this.processAxisChange({axis:j,value:0})}}this._prevTimestamp=this._rawPad.timestamp},connect:function(rawPad){var triggerCallback=!this._connected;this._index=rawPad.index;this._connected=true;this._rawPad=rawPad;this._rawButtons=rawPad.buttons;this._axes=rawPad.axes;if(triggerCallback&&this._padParent.onConnectCallback){this._padParent.onConnectCallback.call(this._padParent.callbackContext,this._index)}if(triggerCallback&&this.onConnectCallback){this.onConnectCallback.call(this.callbackContext)}},disconnect:function(){var triggerCallback=this._connected;this._connected=false;this._rawPad=undefined;this._rawButtons=[];this._buttons=[];var disconnectingIndex=this._index;this._index=null;if(triggerCallback&&this._padParent.onDisconnectCallback){this._padParent.onDisconnectCallback.call(this._padParent.callbackContext,disconnectingIndex)}if(triggerCallback&&this.onDisconnectCallback){this.onDisconnectCallback.call(this.callbackContext)}},processAxisChange:function(axisState){if(this.game.input.disabled||this.game.input.gamepad.disabled){return}if(this._axes[axisState.axis]===axisState.value){return}this._axes[axisState.axis]=axisState.value;if(this._padParent.onAxisCallback){this._padParent.onAxisCallback.call(this._padParent.callbackContext,axisState,this._index)}if(this.onAxisCallback){this.onAxisCallback.call(this.callbackContext,axisState)}},processButtonDown:function(buttonCode,value){if(this.game.input.disabled||this.game.input.gamepad.disabled){return}if(this._padParent.onDownCallback){this._padParent.onDownCallback.call(this._padParent.callbackContext,buttonCode,value,this._index)}if(this.onDownCallback){this.onDownCallback.call(this.callbackContext,buttonCode,value)}if(this._buttons[buttonCode]&&this._buttons[buttonCode].isDown){this._buttons[buttonCode].duration=this.game.time.now-this._buttons[buttonCode].timeDown}else{if(!this._buttons[buttonCode]){this._buttons[buttonCode]={isDown:true,timeDown:this.game.time.now,timeUp:0,duration:0,value:value}}else{this._buttons[buttonCode].isDown=true;this._buttons[buttonCode].timeDown=this.game.time.now;this._buttons[buttonCode].duration=0;this._buttons[buttonCode].value=value}}if(this._hotkeys[buttonCode]){this._hotkeys[buttonCode].processButtonDown(value)}},processButtonUp:function(buttonCode,value){if(this.game.input.disabled||this.game.input.gamepad.disabled){return}if(this._padParent.onUpCallback){this._padParent.onUpCallback.call(this._padParent.callbackContext,buttonCode,value,this._index)}if(this.onUpCallback){this.onUpCallback.call(this.callbackContext,buttonCode,value)}if(this._hotkeys[buttonCode]){this._hotkeys[buttonCode].processButtonUp(value)}if(this._buttons[buttonCode]){this._buttons[buttonCode].isDown=false;this._buttons[buttonCode].timeUp=this.game.time.now;this._buttons[buttonCode].value=value}else{this._buttons[buttonCode]={isDown:false,timeDown:this.game.time.now,timeUp:this.game.time.now,duration:0,value:value}}},processButtonFloat:function(buttonCode,value){if(this.game.input.disabled||this.game.input.gamepad.disabled){return}if(this._padParent.onFloatCallback){this._padParent.onFloatCallback.call(this._padParent.callbackContext,buttonCode,value,this._index)}if(this.onFloatCallback){this.onFloatCallback.call(this.callbackContext,buttonCode,value)}if(!this._buttons[buttonCode]){this._buttons[buttonCode]={value:value}}else{this._buttons[buttonCode].value=value}if(this._hotkeys[buttonCode]){this._hotkeys[buttonCode].processButtonFloat(value)}},axis:function(axisCode){if(this._axes[axisCode]){return this._axes[axisCode]}return false},isDown:function(buttonCode){if(this._buttons[buttonCode]){return this._buttons[buttonCode].isDown}return false},justReleased:function(buttonCode,duration){if(typeof duration==="undefined"){duration=250}return this._buttons[buttonCode]&&this._buttons[buttonCode].isDown===false&&this.game.time.now-this._buttons[buttonCode].timeUphighestID||this.priorityID===highestID&&this.sprite._cache[3]=this.pixelPerfectAlpha){return true}}return false},update:function(pointer){if(this.sprite===null||this.sprite.parent===undefined){return}if(!this.enabled||!this.sprite.visible||!this.sprite.parent.visible){this._pointerOutHandler(pointer);return false}if(this.draggable&&this._draggedPointerID==pointer.id){return this.updateDrag(pointer)}else if(this._pointerData[pointer.id].isOver===true){if(this.checkPointerOver(pointer)){this._pointerData[pointer.id].x=pointer.x-this.sprite.x;this._pointerData[pointer.id].y=pointer.y-this.sprite.y;return true}else{this._pointerOutHandler(pointer);return false}}},_pointerOverHandler:function(pointer){if(this.sprite===null){return}if(this._pointerData[pointer.id].isOver===false){this._pointerData[pointer.id].isOver=true;this._pointerData[pointer.id].isOut=false;this._pointerData[pointer.id].timeOver=this.game.time.now;this._pointerData[pointer.id].x=pointer.x-this.sprite.x;this._pointerData[pointer.id].y=pointer.y-this.sprite.y;if(this.useHandCursor&&this._pointerData[pointer.id].isDragged===false){this.game.canvas.style.cursor="pointer";this._setHandCursor=true}if(this.sprite&&this.sprite.events){this.sprite.events.onInputOver.dispatch(this.sprite,pointer)}}},_pointerOutHandler:function(pointer){if(this.sprite===null){return}this._pointerData[pointer.id].isOver=false;this._pointerData[pointer.id].isOut=true;this._pointerData[pointer.id].timeOut=this.game.time.now;if(this.useHandCursor&&this._pointerData[pointer.id].isDragged===false){this.game.canvas.style.cursor="default";this._setHandCursor=false}if(this.sprite&&this.sprite.events){this.sprite.events.onInputOut.dispatch(this.sprite,pointer)}},_touchedHandler:function(pointer){if(this.sprite===null){return}if(this._pointerData[pointer.id].isDown===false&&this._pointerData[pointer.id].isOver===true){if(this.pixelPerfectClick&&!this.checkPixel(null,null,pointer)){return}this._pointerData[pointer.id].isDown=true;this._pointerData[pointer.id].isUp=false;this._pointerData[pointer.id].timeDown=this.game.time.now;if(this.sprite&&this.sprite.events){this.sprite.events.onInputDown.dispatch(this.sprite,pointer)}if(this.draggable&&this.isDragged===false){this.startDrag(pointer)}if(this.bringToTop){this.sprite.bringToTop()}}return this.consumePointerEvent},_releasedHandler:function(pointer){if(this.sprite===null){return}if(this._pointerData[pointer.id].isDown&&pointer.isUp){this._pointerData[pointer.id].isDown=false;this._pointerData[pointer.id].isUp=true;this._pointerData[pointer.id].timeUp=this.game.time.now;this._pointerData[pointer.id].downDuration=this._pointerData[pointer.id].timeUp-this._pointerData[pointer.id].timeDown;if(this.checkPointerOver(pointer)){if(this.sprite&&this.sprite.events){this.sprite.events.onInputUp.dispatch(this.sprite,pointer,true)}}else{if(this.sprite&&this.sprite.events){this.sprite.events.onInputUp.dispatch(this.sprite,pointer,false)}if(this.useHandCursor){this.game.canvas.style.cursor="default";this._setHandCursor=false}}if(this.draggable&&this.isDragged&&this._draggedPointerID===pointer.id){this.stopDrag(pointer)}}},updateDrag:function(pointer){if(pointer.isUp){this.stopDrag(pointer);return false}if(this.sprite.fixedToCamera){if(this.allowHorizontalDrag){this.sprite.cameraOffset.x=pointer.x+this._dragPoint.x+this.dragOffset.x}if(this.allowVerticalDrag){this.sprite.cameraOffset.y=pointer.y+this._dragPoint.y+this.dragOffset.y}if(this.boundsRect){this.checkBoundsRect()}if(this.boundsSprite){this.checkBoundsSprite()}if(this.snapOnDrag){this.sprite.cameraOffset.x=Math.round((this.sprite.cameraOffset.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX;this.sprite.cameraOffset.y=Math.round((this.sprite.cameraOffset.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY}}else{if(this.allowHorizontalDrag){this.sprite.x=pointer.x+this._dragPoint.x+this.dragOffset.x}if(this.allowVerticalDrag){this.sprite.y=pointer.y+this._dragPoint.y+this.dragOffset.y}if(this.boundsRect){this.checkBoundsRect()}if(this.boundsSprite){this.checkBoundsSprite()}if(this.snapOnDrag){this.sprite.x=Math.round((this.sprite.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX;this.sprite.y=Math.round((this.sprite.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY}}return true},justOver:function(pointer,delay){pointer=pointer||0;delay=delay||500;return this._pointerData[pointer].isOver&&this.overDuration(pointer)this.boundsRect.right){this.sprite.cameraOffset.x=this.boundsRect.right-this.sprite.width}if(this.sprite.cameraOffset.ythis.boundsRect.bottom){this.sprite.cameraOffset.y=this.boundsRect.bottom-this.sprite.height}}else{if(this.sprite.xthis.boundsRect.right){this.sprite.x=this.boundsRect.right-this.sprite.width}if(this.sprite.ythis.boundsRect.bottom){this.sprite.y=this.boundsRect.bottom-this.sprite.height}}},checkBoundsSprite:function(){if(this.sprite.fixedToCamera&&this.boundsSprite.fixedToCamera){if(this.sprite.cameraOffset.xthis.boundsSprite.camerOffset.x+this.boundsSprite.width){this.sprite.cameraOffset.x=this.boundsSprite.camerOffset.x+this.boundsSprite.width-this.sprite.width}if(this.sprite.cameraOffset.ythis.boundsSprite.camerOffset.y+this.boundsSprite.height){this.sprite.cameraOffset.y=this.boundsSprite.camerOffset.y+this.boundsSprite.height-this.sprite.height}}else{if(this.sprite.xthis.boundsSprite.x+this.boundsSprite.width){this.sprite.x=this.boundsSprite.x+this.boundsSprite.width-this.sprite.width}if(this.sprite.ythis.boundsSprite.y+this.boundsSprite.height){this.sprite.y=this.boundsSprite.y+this.boundsSprite.height-this.sprite.height}}}};Phaser.InputHandler.prototype.constructor=Phaser.InputHandler;Phaser.Events=function(sprite){this.parent=sprite;this.onAddedToGroup=new Phaser.Signal;this.onRemovedFromGroup=new Phaser.Signal;this.onKilled=new Phaser.Signal;this.onRevived=new Phaser.Signal;this.onOutOfBounds=new Phaser.Signal;this.onEnterBounds=new Phaser.Signal;this.onInputOver=null;this.onInputOut=null;this.onInputDown=null;this.onInputUp=null;this.onDragStart=null;this.onDragStop=null;this.onAnimationStart=null;this.onAnimationComplete=null;this.onAnimationLoop=null};Phaser.Events.prototype={destroy:function(){this.parent=null;this.onAddedToGroup.dispose();this.onRemovedFromGroup.dispose();this.onKilled.dispose();this.onRevived.dispose();this.onOutOfBounds.dispose();if(this.onInputOver){this.onInputOver.dispose();this.onInputOut.dispose();this.onInputDown.dispose();this.onInputUp.dispose();this.onDragStart.dispose();this.onDragStop.dispose()}if(this.onAnimationStart){this.onAnimationStart.dispose();this.onAnimationComplete.dispose();this.onAnimationLoop.dispose()}}};Phaser.Events.prototype.constructor=Phaser.Events;Phaser.GameObjectFactory=function(game){this.game=game;this.world=this.game.world};Phaser.GameObjectFactory.prototype={existing:function(object){return this.world.add(object)},image:function(x,y,key,frame,group){if(typeof group==="undefined"){group=this.world}return group.add(new Phaser.Image(this.game,x,y,key,frame))},sprite:function(x,y,key,frame,group){if(typeof group==="undefined"){group=this.world}return group.create(x,y,key,frame)},tween:function(obj){return this.game.tweens.create(obj)},group:function(parent,name,addToStage,enableBody,physicsBodyType){return new Phaser.Group(this.game,parent,name,addToStage,enableBody,physicsBodyType)},physicsGroup:function(physicsBodyType,parent,name,addToStage){return new Phaser.Group(this.game,parent,name,addToStage,true,physicsBodyType)},spriteBatch:function(parent,name,addToStage){if(typeof name==="undefined"){name="group"}if(typeof addToStage==="undefined"){addToStage=false}return new Phaser.SpriteBatch(this.game,parent,name,addToStage)},audio:function(key,volume,loop,connect){return this.game.sound.add(key,volume,loop,connect)},sound:function(key,volume,loop,connect){return this.game.sound.add(key,volume,loop,connect)},tileSprite:function(x,y,width,height,key,frame,group){if(typeof group==="undefined"){group=this.world}return group.add(new Phaser.TileSprite(this.game,x,y,width,height,key,frame))},text:function(x,y,text,style,group){if(typeof group==="undefined"){group=this.world}return group.add(new Phaser.Text(this.game,x,y,text,style))},button:function(x,y,key,callback,callbackContext,overFrame,outFrame,downFrame,upFrame,group){if(typeof group==="undefined"){group=this.world}return group.add(new Phaser.Button(this.game,x,y,key,callback,callbackContext,overFrame,outFrame,downFrame,upFrame))},graphics:function(x,y,group){if(typeof group==="undefined"){group=this.world}return group.add(new Phaser.Graphics(this.game,x,y))},emitter:function(x,y,maxParticles){return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game,x,y,maxParticles))},retroFont:function(font,characterWidth,characterHeight,chars,charsPerRow,xSpacing,ySpacing,xOffset,yOffset){return new Phaser.RetroFont(this.game,font,characterWidth,characterHeight,chars,charsPerRow,xSpacing,ySpacing,xOffset,yOffset)},bitmapText:function(x,y,font,text,size,group){if(typeof group==="undefined"){group=this.world}return group.add(new Phaser.BitmapText(this.game,x,y,font,text,size))},tilemap:function(key,tileWidth,tileHeight,width,height){return new Phaser.Tilemap(this.game,key,tileWidth,tileHeight,width,height)},renderTexture:function(width,height,key,addToCache){if(typeof key==="undefined"||key===""){key=this.game.rnd.uuid()}if(typeof addToCache==="undefined"){addToCache=false}var texture=new Phaser.RenderTexture(this.game,width,height,key);if(addToCache){this.game.cache.addRenderTexture(key,texture)}return texture},bitmapData:function(width,height,key,addToCache){if(typeof addToCache==="undefined"){addToCache=false}if(typeof key==="undefined"||key===""){key=this.game.rnd.uuid()}var texture=new Phaser.BitmapData(this.game,key,width,height);if(addToCache){this.game.cache.addBitmapData(key,texture)}return texture},filter:function(filter){var args=Array.prototype.splice.call(arguments,1);var filter=new Phaser.Filter[filter](this.game);filter.init.apply(filter,args);return filter}};Phaser.GameObjectFactory.prototype.constructor=Phaser.GameObjectFactory;Phaser.GameObjectCreator=function(game){this.game=game;this.world=this.game.world};Phaser.GameObjectCreator.prototype={image:function(x,y,key,frame){return new Phaser.Image(this.game,x,y,key,frame)},sprite:function(x,y,key,frame){return new Phaser.Sprite(this.game,x,y,key,frame)},tween:function(obj){return new Phaser.Tween(obj,this.game)},group:function(parent,name,addToStage,enableBody,physicsBodyType){return new Phaser.Group(this.game,null,name,addToStage,enableBody,physicsBodyType)},spriteBatch:function(parent,name,addToStage){if(typeof name==="undefined"){name="group"}if(typeof addToStage==="undefined"){ addToStage=false}return new Phaser.SpriteBatch(this.game,parent,name,addToStage)},audio:function(key,volume,loop,connect){return this.game.sound.add(key,volume,loop,connect)},sound:function(key,volume,loop,connect){return this.game.sound.add(key,volume,loop,connect)},tileSprite:function(x,y,width,height,key,frame){return new Phaser.TileSprite(this.game,x,y,width,height,key,frame)},text:function(x,y,text,style){return new Phaser.Text(this.game,x,y,text,style)},button:function(x,y,key,callback,callbackContext,overFrame,outFrame,downFrame,upFrame){return new Phaser.Button(this.game,x,y,key,callback,callbackContext,overFrame,outFrame,downFrame,upFrame)},graphics:function(x,y){return new Phaser.Graphics(this.game,x,y)},emitter:function(x,y,maxParticles){return new Phaser.Particles.Arcade.Emitter(this.game,x,y,maxParticles)},retroFont:function(font,characterWidth,characterHeight,chars,charsPerRow,xSpacing,ySpacing,xOffset,yOffset){return new Phaser.RetroFont(this.game,font,characterWidth,characterHeight,chars,charsPerRow,xSpacing,ySpacing,xOffset,yOffset)},bitmapText:function(x,y,font,text,size){return new Phaser.BitmapText(this.game,x,y,font,text,size)},tilemap:function(key,tileWidth,tileHeight,width,height){return new Phaser.Tilemap(this.game,key,tileWidth,tileHeight,width,height)},renderTexture:function(width,height,key,addToCache){if(typeof key==="undefined"||key===""){key=this.game.rnd.uuid()}if(typeof addToCache==="undefined"){addToCache=false}var texture=new Phaser.RenderTexture(this.game,width,height,key);if(addToCache){this.game.cache.addRenderTexture(key,texture)}return texture},bitmapData:function(width,height,key,addToCache){if(typeof addToCache==="undefined"){addToCache=false}if(typeof key==="undefined"||key===""){key=this.game.rnd.uuid()}var texture=new Phaser.BitmapData(this.game,key,width,height);if(addToCache){this.game.cache.addBitmapData(key,texture)}return texture},filter:function(filter){var args=Array.prototype.splice.call(arguments,1);var filter=new Phaser.Filter[filter](this.game);filter.init.apply(filter,args);return filter}};Phaser.GameObjectCreator.prototype.constructor=Phaser.GameObjectCreator;Phaser.BitmapData=function(game,key,width,height){if(typeof width==="undefined"){width=100}if(typeof height==="undefined"){height=100}this.game=game;this.key=key;this.width=width;this.height=height;this.canvas=Phaser.Canvas.create(width,height,"",true);this.context=this.canvas.getContext("2d");this.ctx=this.context;this.imageData=this.context.getImageData(0,0,width,height);this.data=this.imageData.data;this.pixels=null;if(this.imageData.data.buffer){this.buffer=this.imageData.data.buffer;this.pixels=new Uint32Array(this.buffer)}else{if(window["ArrayBuffer"]){this.buffer=new ArrayBuffer(this.imageData.data.length);this.pixels=new Uint32Array(this.buffer)}else{this.pixels=this.imageData.data}}this.baseTexture=new PIXI.BaseTexture(this.canvas);this.texture=new PIXI.Texture(this.baseTexture);this.textureFrame=new Phaser.Frame(0,0,0,width,height,"bitmapData",game.rnd.uuid());this.type=Phaser.BITMAPDATA;this.disableTextureUpload=false;this.dirty=false;this.cls=this.clear;this.update=this.refreshBuffer;this._tempR=0;this._tempG=0;this._tempB=0};Phaser.BitmapData.prototype={add:function(object){if(Array.isArray(object)){for(var i=0;i=0&&x<=this.width&&y>=0&&y<=this.height){if(Phaser.Device.LITTLE_ENDIAN){this.pixels[y*this.width+x]=alpha<<24|blue<<16|green<<8|red}else{this.pixels[y*this.width+x]=red<<24|green<<16|blue<<8|alpha}if(immediate){this.context.putImageData(this.imageData,0,0);this.dirty=true}}},setPixel:function(x,y,red,green,blue,immediate){this.setPixel32(x,y,red,green,blue,255,immediate)},getPixel:function(x,y,out){if(!out){out=Phaser.Color.createColor()}var index=~~(x+y*this.width);index*=4;if(this.data[index]){out.r=this.data[index];out.g=this.data[++index];out.b=this.data[++index];out.a=this.data[++index]}return out},getPixel32:function(x,y){if(x>=0&&x<=this.width&&y>=0&&y<=this.height){return this.pixels[y*this.width+x]}},getPixelRGB:function(x,y,out,hsl,hsv){return Phaser.Color.unpackPixel(this.getPixel32(x,y),out,hsl,hsv)},getPixels:function(rect){return this.context.getImageData(rect.x,rect.y,rect.width,rect.height)},copyPixels:function(source,area,destX,destY){if(typeof source==="string"){source=this.game.cache.getImage(source)}if(source){this.context.drawImage(source,area.x,area.y,area.width,area.height,destX,destY,area.width,area.height)}this.dirty=true},draw:function(source,x,y){if(typeof x==="undefined"){x=0}if(typeof y==="undefined"){y=0}if(typeof source==="string"){source=this.game.cache.getImage(source)}if(source){this.context.drawImage(source,0,0,source.width,source.height,x,y,source.width,source.height)}this.dirty=true},drawSprite:function(sprite,x,y){if(typeof x==="undefined"){x=0}if(typeof y==="undefined"){y=0}var frame=sprite.texture.frame;this.context.drawImage(sprite.texture.baseTexture.source,frame.x,frame.y,frame.width,frame.height,x,y,frame.width,frame.height);this.dirty=true},alphaMask:function(source,mask){var temp=this.context.globalCompositeOperation;if(typeof mask==="string"){mask=this.game.cache.getImage(mask)}if(mask){this.context.drawImage(mask,0,0)}this.context.globalCompositeOperation="source-atop";if(typeof source==="string"){source=this.game.cache.getImage(source)}if(source){this.context.drawImage(source,0,0)}this.context.globalCompositeOperation=temp;this.dirty=true},extract:function(destination,r,g,b,a){if(typeof a==="undefined"){a=255}this.processPixelRGB(function(pixel,x,y){if(pixel.r===r&&pixel.g===g&&pixel.b===b){destination.setPixel32(x,y,r,g,b,a,false)}return false},this);destination.context.putImageData(destination.imageData,0,0);destination.dirty=true;return destination},rect:function(x,y,width,height,fillStyle){if(typeof fillStyle!=="undefined"){this.context.fillStyle=fillStyle}this.context.fillRect(x,y,width,height);this.context.fill()},circle:function(x,y,radius,fillStyle){if(typeof fillStyle!=="undefined"){this.context.fillStyle=fillStyle}this.context.beginPath();this.context.arc(x,y,radius,0,Math.PI*2,false);this.context.closePath();this.context.fill()},render:function(){if(!this.disableTextureUpload&&this.game.renderType===Phaser.WEBGL&&this.dirty){PIXI.updateWebGLTexture(this.baseTexture,this.game.renderer.gl);this.dirty=false}}};Phaser.BitmapData.prototype.constructor=Phaser.BitmapData;Phaser.Sprite=function(game,x,y,key,frame){x=x||0;y=y||0;key=key||null;frame=frame||null;this.game=game;this.name="";this.type=Phaser.SPRITE;this.z=0;this.events=new Phaser.Events(this);this.animations=new Phaser.AnimationManager(this);this.key=key;this._frame=0;this._frameName="";PIXI.Sprite.call(this,PIXI.TextureCache["__default"]);this.loadTexture(key,frame);this.position.set(x,y);this.world=new Phaser.Point(x,y);this.autoCull=false;this.input=null;this.body=null;this.health=1;this.lifespan=0;this.checkWorldBounds=false;this.outOfBoundsKill=false;this.debug=false;this.cameraOffset=new Phaser.Point;this._cache=[0,0,0,0,1,0,1,0,0];this._bounds=new Phaser.Rectangle};Phaser.Sprite.prototype=Object.create(PIXI.Sprite.prototype);Phaser.Sprite.prototype.constructor=Phaser.Sprite;Phaser.Sprite.prototype.preUpdate=function(){if(this._cache[4]===1&&this.exists){this.world.setTo(this.parent.position.x+this.position.x,this.parent.position.y+this.position.y);this.worldTransform.tx=this.world.x;this.worldTransform.ty=this.world.y;this._cache[0]=this.world.x;this._cache[1]=this.world.y;this._cache[2]=this.rotation;if(this.body){this.body.preUpdate()}this._cache[4]=0;return false}this._cache[0]=this.world.x;this._cache[1]=this.world.y;this._cache[2]=this.rotation;if(!this.exists||!this.parent.exists){this._cache[3]=-1;return false}if(this.lifespan>0){this.lifespan-=this.game.time.elapsed;if(this.lifespan<=0){this.kill();return false}}if(this.autoCull||this.checkWorldBounds){this._bounds.copyFrom(this.getBounds())}if(this.autoCull){this.renderable=this.game.world.camera.screenView.intersects(this._bounds)}if(this.checkWorldBounds){if(this._cache[5]===1&&this.game.world.bounds.intersects(this._bounds)){this._cache[5]=0;this.events.onEnterBounds.dispatch(this)}else if(this._cache[5]===0&&!this.game.world.bounds.intersects(this._bounds)){this._cache[5]=1;this.events.onOutOfBounds.dispatch(this);if(this.outOfBoundsKill){this.kill();return false}}}this.world.setTo(this.game.camera.x+this.worldTransform.tx,this.game.camera.y+this.worldTransform.ty);if(this.visible){this._cache[3]=this.game.stage.currentRenderOrderID++}this.animations.update();if(this.body){this.body.preUpdate()}for(var i=0,len=this.children.length;ispaceLeft){if(j>0){result+="\n"}result+=words[j]+" ";spaceLeft=this.style.wordWrapWidth-wordWidth}else{spaceLeft-=wordWidthWithSpace;result+=words[j]+" "}}if(i0){this.drawPolygon(triangle)}}else{this.drawPolygon(triangle)}};Phaser.Graphics.prototype.drawTriangles=function(vertices,indices,cull){if(typeof cull==="undefined"){cull=false}var point1=new Phaser.Point;var point2=new Phaser.Point;var point3=new Phaser.Point;var points=[];var i;if(!indices){if(vertices[0]instanceof Phaser.Point){for(i=0;i?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";Phaser.RetroFont.TEXT_SET2=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ";Phaser.RetroFont.TEXT_SET3="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";Phaser.RetroFont.TEXT_SET4="ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789";Phaser.RetroFont.TEXT_SET5="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789";Phaser.RetroFont.TEXT_SET6="ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ";Phaser.RetroFont.TEXT_SET7="AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39";Phaser.RetroFont.TEXT_SET8="0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ";Phaser.RetroFont.TEXT_SET9="ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!";Phaser.RetroFont.TEXT_SET10="ABCDEFGHIJKLMNOPQRSTUVWXYZ";Phaser.RetroFont.TEXT_SET11="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789";Phaser.RetroFont.prototype.setFixedWidth=function(width,lineAlignment){if(typeof lineAlignment==="undefined"){lineAlignment="left"}this.fixedWidth=width;this.align=lineAlignment};Phaser.RetroFont.prototype.setText=function(content,multiLine,characterSpacing,lineSpacing,lineAlignment,allowLowerCase){this.multiLine=multiLine||false;this.customSpacingX=characterSpacing||0;this.customSpacingY=lineSpacing||0;this.align=lineAlignment||"left";if(allowLowerCase){this.autoUpperCase=false}else{this.autoUpperCase=true}if(content.length>0){this.text=content}};Phaser.RetroFont.prototype.buildRetroFontText=function(){var cx=0;var cy=0;this.clear();if(this.multiLine){var lines=this._text.split("\n");if(this.fixedWidth>0){this.resize(this.fixedWidth,lines.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,true)}else{this.resize(this.getLongestLine()*(this.characterWidth+this.customSpacingX),lines.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,true)}for(var i=0;i0){this.resize(this.fixedWidth,this.characterHeight,true)}else{this.resize(this._text.length*(this.characterWidth+this.customSpacingX),this.characterHeight,true)}switch(this.align){case Phaser.RetroFont.ALIGN_LEFT:cx=0;break;case Phaser.RetroFont.ALIGN_RIGHT:cx=this.width-this._text.length*(this.characterWidth+this.customSpacingX);break;case Phaser.RetroFont.ALIGN_CENTER:cx=this.width/2-this._text.length*(this.characterWidth+this.customSpacingX)/2;cx+=this.customSpacingX/2;break}this.textureBuffer.clear();this.pasteLine(this._text,cx,0,this.customSpacingX)}};Phaser.RetroFont.prototype.pasteLine=function(line,x,y,customSpacingX){var p=new Phaser.Point;for(var c=0;c=0){this.stamp.frame=this.grabData[line.charCodeAt(c)];p.set(x,y);this.render(this.stamp,p,false);x+=this.characterWidth+customSpacingX;if(x>this.width){break}}}}};Phaser.RetroFont.prototype.getLongestLine=function(){var longestLine=0;if(this._text.length>0){var lines=this._text.split("\n");for(var i=0;ilongestLine){longestLine=lines[i].length}}}return longestLine};Phaser.RetroFont.prototype.removeUnsupportedCharacters=function(stripCR){var newString="";for(var c=0;c=0||!stripCR&&aChar==="\n"){newString=newString.concat(aChar)}}return newString};Object.defineProperty(Phaser.RetroFont.prototype,"text",{get:function(){return this._text},set:function(value){var newText;if(this.autoUpperCase){newText=value.toUpperCase()}else{newText=value}if(newText!==this._text){this._text=newText;this.removeUnsupportedCharacters(this.multiLine);this.buildRetroFontText()}}});Phaser.Particle=function(game,x,y,key,frame){Phaser.Sprite.call(this,game,x,y,key,frame); this.autoScale=false;this.scaleData=null;this._s=0;this.autoAlpha=false;this.alphaData=null;this._a=0};Phaser.Particle.prototype=Object.create(Phaser.Sprite.prototype);Phaser.Particle.prototype.constructor=Phaser.Particle;Phaser.Particle.prototype.update=function(){if(this.autoScale){this._s--;if(this._s){this.scale.set(this.scaleData[this._s].x,this.scaleData[this._s].y)}else{this.autoScale=false}}if(this.autoAlpha){this._a--;if(this._a){this.alpha=this.alphaData[this._a].v}else{this.autoAlpha=false}}};Phaser.Particle.prototype.onEmit=function(){};Phaser.Particle.prototype.setAlphaData=function(data){this.alphaData=data;this._a=data.length-1;this.alpha=this.alphaData[this._a].v;this.autoAlpha=true};Phaser.Particle.prototype.setScaleData=function(data){this.scaleData=data;this._s=data.length-1;this.scale.set(this.scaleData[this._s].x,this.scaleData[this._s].y);this.autoScale=true};Phaser.Particle.prototype.reset=function(x,y,health){if(typeof health==="undefined"){health=1}this.world.setTo(x,y);this.position.x=x;this.position.y=y;this.alive=true;this.exists=true;this.visible=true;this.renderable=true;this._outOfBoundsFired=false;this.health=health;if(this.body){this.body.reset(x,y,false,false)}this._cache[4]=1;this.alpha=1;this.scale.set(1);this.autoScale=false;this.autoAlpha=false;return this};Phaser.Canvas={create:function(width,height,id,noCocoon){if(typeof noCocoon==="undefined"){noCocoon=false}width=width||256;height=height||256;if(noCocoon){var canvas=document.createElement("canvas")}else{var canvas=document.createElement(navigator.isCocoonJS?"screencanvas":"canvas")}if(typeof id==="string"&&id!==""){canvas.id=id}canvas.width=width;canvas.height=height;canvas.style.display="block";return canvas},getOffset:function(element,point){point=point||new Phaser.Point;var box=element.getBoundingClientRect();var clientTop=element.clientTop||document.body.clientTop||0;var clientLeft=element.clientLeft||document.body.clientLeft||0;var scrollTop=0;var scrollLeft=0;if(document.compatMode==="CSS1Compat"){scrollTop=window.pageYOffset||document.documentElement.scrollTop||element.scrollTop||0;scrollLeft=window.pageXOffset||document.documentElement.scrollLeft||element.scrollLeft||0}else{scrollTop=window.pageYOffset||document.body.scrollTop||element.scrollTop||0;scrollLeft=window.pageXOffset||document.body.scrollLeft||element.scrollLeft||0}point.x=box.left+scrollLeft-clientLeft;point.y=box.top+scrollTop-clientTop;return point},getAspectRatio:function(canvas){return canvas.width/canvas.height},setBackgroundColor:function(canvas,color){color=color||"rgb(0,0,0)";canvas.style.backgroundColor=color;return canvas},setTouchAction:function(canvas,value){value=value||"none";canvas.style.msTouchAction=value;canvas.style["ms-touch-action"]=value;canvas.style["touch-action"]=value;return canvas},setUserSelect:function(canvas,value){value=value||"none";canvas.style["-webkit-touch-callout"]=value;canvas.style["-webkit-user-select"]=value;canvas.style["-khtml-user-select"]=value;canvas.style["-moz-user-select"]=value;canvas.style["-ms-user-select"]=value;canvas.style["user-select"]=value;canvas.style["-webkit-tap-highlight-color"]="rgba(0, 0, 0, 0)";return canvas},addToDOM:function(canvas,parent,overflowHidden){var target;if(typeof overflowHidden==="undefined"){overflowHidden=true}if(parent){if(typeof parent==="string"){target=document.getElementById(parent)}else if(typeof parent==="object"&&parent.nodeType===1){target=parent}}if(!target){target=document.body}if(overflowHidden&&target.style){target.style.overflow="hidden"}target.appendChild(canvas);return canvas},setTransform:function(context,translateX,translateY,scaleX,scaleY,skewX,skewY){context.setTransform(scaleX,skewX,skewY,scaleY,translateX,translateY);return context},setSmoothingEnabled:function(context,value){context["imageSmoothingEnabled"]=value;context["mozImageSmoothingEnabled"]=value;context["oImageSmoothingEnabled"]=value;context["webkitImageSmoothingEnabled"]=value;context["msImageSmoothingEnabled"]=value;return context},setImageRenderingCrisp:function(canvas){canvas.style["image-rendering"]="optimizeSpeed";canvas.style["image-rendering"]="crisp-edges";canvas.style["image-rendering"]="-moz-crisp-edges";canvas.style["image-rendering"]="-webkit-optimize-contrast";canvas.style["image-rendering"]="optimize-contrast";canvas.style.msInterpolationMode="nearest-neighbor";return canvas},setImageRenderingBicubic:function(canvas){canvas.style["image-rendering"]="auto";canvas.style.msInterpolationMode="bicubic";return canvas}};Phaser.Device=function(game){this.game=game;this.desktop=false;this.iOS=false;this.cocoonJS=false;this.ejecta=false;this.crosswalk=false;this.android=false;this.chromeOS=false;this.linux=false;this.macOS=false;this.windows=false;this.windowsPhone=false;this.canvas=false;this.file=false;this.fileSystem=false;this.localStorage=false;this.webGL=false;this.worker=false;this.touch=false;this.mspointer=false;this.css3D=false;this.pointerLock=false;this.typedArray=false;this.vibration=false;this.getUserMedia=false;this.quirksMode=false;this.arora=false;this.chrome=false;this.epiphany=false;this.firefox=false;this.ie=false;this.ieVersion=0;this.trident=false;this.tridentVersion=0;this.mobileSafari=false;this.midori=false;this.opera=false;this.safari=false;this.webApp=false;this.silk=false;this.audioData=false;this.webAudio=false;this.ogg=false;this.opus=false;this.mp3=false;this.wav=false;this.m4a=false;this.webm=false;this.iPhone=false;this.iPhone4=false;this.iPad=false;this.pixelRatio=0;this.littleEndian=false;this.support32bit=false;this.fullscreen=false;this.requestFullscreen="";this.cancelFullscreen="";this.fullscreenKeyboard=false;this._checkAudio();this._checkBrowser();this._checkCSS3D();this._checkDevice();this._checkFeatures();this._checkOS()};Phaser.Device.LITTLE_ENDIAN=false;Phaser.Device.prototype={_checkOS:function(){var ua=navigator.userAgent;if(/Android/.test(ua)){this.android=true}else if(/CrOS/.test(ua)){this.chromeOS=true}else if(/iP[ao]d|iPhone/i.test(ua)){this.iOS=true}else if(/Linux/.test(ua)){this.linux=true}else if(/Mac OS/.test(ua)){this.macOS=true}else if(/Windows/.test(ua)){this.windows=true;if(/Windows Phone/i.test(ua)){this.windowsPhone=true}}if(this.windows||this.macOS||this.linux&&this.silk===false){this.desktop=true}if(this.windowsPhone||/Windows NT/i.test(ua)&&/Touch/i.test(ua)){this.desktop=false}},_checkFeatures:function(){this.canvas=!!window["CanvasRenderingContext2D"]||this.cocoonJS;try{this.localStorage=!!localStorage.getItem}catch(error){this.localStorage=false}this.file=!!window["File"]&&!!window["FileReader"]&&!!window["FileList"]&&!!window["Blob"];this.fileSystem=!!window["requestFileSystem"];this.webGL=function(){try{var canvas=document.createElement("canvas");return!!window.WebGLRenderingContext&&(canvas.getContext("webgl")||canvas.getContext("experimental-webgl"))}catch(e){return false}}();if(this.webGL===null||this.webGL===false){this.webGL=false}else{this.webGL=true}this.worker=!!window["Worker"];if("ontouchstart"in document.documentElement||window.navigator.maxTouchPoints&&window.navigator.maxTouchPoints>1){this.touch=true}if(window.navigator.msPointerEnabled||window.navigator.pointerEnabled){this.mspointer=true}this.pointerLock="pointerLockElement"in document||"mozPointerLockElement"in document||"webkitPointerLockElement"in document;this.quirksMode=document.compatMode==="CSS1Compat"?false:true;this.getUserMedia=!!(navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia)},checkFullScreenSupport:function(){var fs=["requestFullscreen","requestFullScreen","webkitRequestFullscreen","webkitRequestFullScreen","msRequestFullscreen","msRequestFullScreen","mozRequestFullScreen","mozRequestFullscreen"];for(var i=0;i0&&has3d!=="none"},canPlayAudio:function(type){if(type=="mp3"&&this.mp3){return true}else if(type=="ogg"&&(this.ogg||this.opus)){return true}else if(type=="m4a"&&this.m4a){return true}else if(type=="wav"&&this.wav){return true}else if(type=="webm"&&this.webm){return true}return false},isConsoleOpen:function(){if(window.console&&window.console["firebug"]){return true}if(window.console){console.profile();console.profileEnd();if(console.clear){console.clear()}if(console["profiles"]){return console["profiles"].length>0}}return false}};Phaser.Device.prototype.constructor=Phaser.Device;Phaser.RequestAnimationFrame=function(game,forceSetTimeOut){if(typeof forceSetTimeOut==="undefined"){forceSetTimeOut=false}this.game=game;this.isRunning=false;this.forceSetTimeOut=forceSetTimeOut;var vendors=["ms","moz","webkit","o"];for(var x=0;xb-epsilon},fuzzyCeil:function(val,epsilon){if(typeof epsilon==="undefined"){epsilon=1e-4}return Math.ceil(val-epsilon)},fuzzyFloor:function(val,epsilon){if(typeof epsilon==="undefined"){epsilon=1e-4}return Math.floor(val+epsilon)},average:function(){var args=[];for(var _i=0;_i0?Math.floor(n):Math.ceil(n)},shear:function(n){return n%1},snapTo:function(input,gap,start){if(typeof start==="undefined"){start=0}if(gap===0){return input}input-=start;input=gap*Math.round(input/gap);return start+input},snapToFloor:function(input,gap,start){if(typeof start==="undefined"){start=0}if(gap===0){return input}input-=start;input=gap*Math.floor(input/gap);return start+input},snapToCeil:function(input,gap,start){if(typeof start==="undefined"){start=0}if(gap===0){return input}input-=start;input=gap*Math.ceil(input/gap);return start+input},snapToInArray:function(input,arr,sort){if(typeof sort==="undefined"){sort=true}if(sort){arr.sort()}if(input=0?angleRad:angleRad+2*Math.PI},normalizeLatitude:function(lat){return Math.max(-90,Math.min(90,lat))},normalizeLongitude:function(lng){if(lng%360==180){return 180}lng=lng%360;return lng<-180?lng+360:lng>180?lng-360:lng},chanceRoll:function(chance){if(typeof chance==="undefined"){chance=50}if(chance<=0){return false}else if(chance>=100){return true}else{if(Math.random()*100>=chance){return false}else{return true}}},numberArray:function(min,max){var result=[];for(var i=min;i<=max;i++){result.push(i)}return result},maxAdd:function(value,amount,max){value+=amount;if(value>max){value=max}return value},minSub:function(value,amount,min){value-=amount;if(valuemax?max:value},randomSign:function(){return Math.random()>.5?1:-1},isOdd:function(n){return n&1},isEven:function(n){if(n&1){return false}else{return true}},min:function(){if(arguments.length===1&&typeof arguments[0]==="object"){var data=arguments[0]}else{var data=arguments}for(var i=1,min=0,len=data.length;idata[max]){max=i}}return data[max]},minProperty:function(property){if(arguments.length===2&&typeof arguments[1]==="object"){var data=arguments[1]}else{var data=arguments.slice(1)}for(var i=1,min=0,len=data.length;idata[max][property]){max=i}}return data[max][property]},wrapAngle:function(angle,radians){var radianFactor=radians?Math.PI/180:1;return this.wrap(angle,-180*radianFactor,180*radianFactor)},angleLimit:function(angle,min,max){var result=angle;if(angle>max){result=max}else if(angle1){return this.linear(v[m],v[m-1],m-f)}return this.linear(v[i],v[i+1>m?m:i+1],f-i)},bezierInterpolation:function(v,k){var b=0;var n=v.length-1;for(var i=0;i<=n;i++){b+=Math.pow(1-k,n-i)*Math.pow(k,i)*v[i]*this.bernstein(n,i)}return b},catmullRomInterpolation:function(v,k){var m=v.length-1;var f=m*k;var i=Math.floor(f);if(v[0]===v[m]){if(k<0){i=Math.floor(f=m*(1+k))}return this.catmullRom(v[(i-1+m)%m],v[i],v[(i+1)%m],v[(i+2)%m],f-i)}else{if(k<0){return v[0]-(this.catmullRom(v[0],v[0],v[1],v[1],-f)-v[0])}if(k>1){return v[m]-(this.catmullRom(v[m],v[m],v[m-1],v[m-1],f-m)-v[m])}return this.catmullRom(v[i?i-1:0],v[i],v[mobjects.length-startIndex){l=objects.length-startIndex}if(l>0){return objects[startIndex+Math.floor(Math.random()*l)]}}return null},removeRandom:function(objects,startIndex,length){if(typeof startIndex==="undefined"){startIndex=0}if(typeof length==="undefined"){length=0}if(objects!=null){var l=length;if(l===0||l>objects.length-startIndex){l=objects.length-startIndex}if(l>0){var idx=startIndex+Math.floor(Math.random()*l);var removed=objects.splice(idx,1);return removed[0]}}return null},floor:function(value){var n=value|0;return value>0?n:n!=value?n-1:n},ceil:function(value){var n=value|0;return value>0?n!=value?n+1:n:n},sinCosGenerator:function(length,sinAmplitude,cosAmplitude,frequency){if(typeof sinAmplitude==="undefined"){sinAmplitude=1}if(typeof cosAmplitude==="undefined"){cosAmplitude=1}if(typeof frequency==="undefined"){frequency=1}var sin=sinAmplitude;var cos=cosAmplitude;var frq=frequency*Math.PI/length;var cosTable=[];var sinTable=[];for(var c=0;c0;i--){var j=Math.floor(Math.random()*(i+1));var temp=array[i];array[i]=array[j];array[j]=temp}return array},distance:function(x1,y1,x2,y2){var dx=x1-x2;var dy=y1-y2;return Math.sqrt(dx*dx+dy*dy)},distancePow:function(x1,y1,x2,y2,pow){if(typeof pow==="undefined"){pow=2}return Math.sqrt(Math.pow(x2-x1,pow)+Math.pow(y2-y1,pow))},distanceRounded:function(x1,y1,x2,y2){return Math.round(Phaser.Math.distance(x1,y1,x2,y2))},clamp:function(x,a,b){return xb?b:x},clampBottom:function(x,a){return x0?1:0},percent:function(a,b,base){if(typeof base==="undefined"){base=0}if(a>b||base>b){return 1}else if(aa){return 0}else{return(a-base)/b}},degToRad:function(){var degreeToRadiansFactor=Math.PI/180;return function(degrees){return degrees*degreeToRadiansFactor}}(),radToDeg:function(){var radianToDegreesFactor=180/Math.PI;return function(radians){return radians*radianToDegreesFactor}}()};Phaser.RandomDataGenerator=function(seeds){if(typeof seeds==="undefined"){seeds=[]}this.c=1;this.s0=0;this.s1=0;this.s2=0;this.sow(seeds)};Phaser.RandomDataGenerator.prototype={rnd:function(){var t=2091639*this.s0+this.c*2.3283064365386963e-10;this.c=t|0;this.s0=this.s1;this.s1=this.s2;this.s2=t-this.c;return this.s2},sow:function(seeds){if(typeof seeds==="undefined"){seeds=[]}this.s0=this.hash(" ");this.s1=this.hash(this.s0);this.s2=this.hash(this.s1);this.c=1;var seed;for(var i=0;seed=seeds[i++];){this.s0-=this.hash(seed);this.s0+=~~(this.s0<0);this.s1-=this.hash(seed);this.s1+=~~(this.s1<0);this.s2-=this.hash(seed);this.s2+=~~(this.s2<0)}},hash:function(data){var h,i,n;n=4022871197;data=data.toString();for(i=0;i>>0;h-=n;h*=n;n=h>>>0;h-=n;n+=h*4294967296}return(n>>>0)*2.3283064365386963e-10},integer:function(){return this.rnd.apply(this)*4294967296},frac:function(){return this.rnd.apply(this)+(this.rnd.apply(this)*2097152|0)*1.1102230246251565e-16},real:function(){return this.integer()+this.frac()},integerInRange:function(min,max){return Math.floor(this.realInRange(0,max-min+1)+min)},realInRange:function(min,max){return this.frac()*(max-min)+min},normal:function(){return 1-2*this.frac()},uuid:function(){var a="";var b="";for(b=a="";a++<36;b+=~a%5|a*3&4?(a^15?8^this.frac()*(a^20?16:4):4).toString(16):"-"){}return b},pick:function(ary){return ary[this.integerInRange(0,ary.length-1)]},weightedPick:function(ary){return ary[~~(Math.pow(this.frac(),2)*(ary.length-1))]},timestamp:function(min,max){return this.realInRange(min||9466848e5,max||1577862e6)},angle:function(){return this.integerInRange(-180,180)}};Phaser.RandomDataGenerator.prototype.constructor=Phaser.RandomDataGenerator;Phaser.QuadTree=function(x,y,width,height,maxObjects,maxLevels,level){this.maxObjects=10;this.maxLevels=4;this.level=0;this.bounds={};this.objects=[];this.nodes=[];this._empty=[];this.reset(x,y,width,height,maxObjects,maxLevels,level)};Phaser.QuadTree.prototype={reset:function(x,y,width,height,maxObjects,maxLevels,level){this.maxObjects=maxObjects||10;this.maxLevels=maxLevels||4;this.level=level||0;this.bounds={x:Math.round(x),y:Math.round(y),width:width,height:height,subWidth:Math.floor(width/2),subHeight:Math.floor(height/2),right:Math.round(x)+Math.floor(width/2),bottom:Math.round(y)+Math.floor(height/2)};this.objects.length=0;this.nodes.length=0},populate:function(group){group.forEach(this.populateHandler,this,true)},populateHandler:function(sprite){if(sprite.body&&sprite.exists){this.insert(sprite.body)}},split:function(){this.level++;this.nodes[0]=new Phaser.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level);this.nodes[1]=new Phaser.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level);this.nodes[2]=new Phaser.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level);this.nodes[3]=new Phaser.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level)},insert:function(body){var i=0;var index;if(this.nodes[0]!=null){index=this.getIndex(body);if(index!==-1){this.nodes[index].insert(body);return}}this.objects.push(body);if(this.objects.length>this.maxObjects&&this.levelthis.bounds.bottom){index=2}}else if(rect.x>this.bounds.right){if(rect.ythis.bounds.bottom){index=3}}return index},retrieve:function(source){if(source instanceof Phaser.Rectangle){var returnObjects=this.objects;var index=this.getIndex(source)}else{if(!source.body){return this._empty}var returnObjects=this.objects;var index=this.getIndex(source.body)}if(this.nodes[0]){if(index!==-1){returnObjects=returnObjects.concat(this.nodes[index].retrieve(source))}else{returnObjects=returnObjects.concat(this.nodes[0].retrieve(source));returnObjects=returnObjects.concat(this.nodes[1].retrieve(source));returnObjects=returnObjects.concat(this.nodes[2].retrieve(source));returnObjects=returnObjects.concat(this.nodes[3].retrieve(source))}}return returnObjects},clear:function(){this.objects.length=0;var i=this.nodes.length;while(i--){this.nodes[i].clear();this.nodes.splice(i,1)}this.nodes.length=0}};Phaser.QuadTree.prototype.constructor=Phaser.QuadTree;Phaser.Net=function(game){this.game=game};Phaser.Net.prototype={getHostName:function(){if(window.location&&window.location.hostname){return window.location.hostname}return null},checkDomainName:function(domain){return window.location.hostname.indexOf(domain)!==-1},updateQueryString:function(key,value,redirect,url){if(typeof redirect==="undefined"){redirect=false}if(typeof url==="undefined"||url===""){url=window.location.href}var output="";var re=new RegExp("([?|&])"+key+"=.*?(&|#|$)(.*)","gi");if(re.test(url)){if(typeof value!=="undefined"&&value!==null){output=url.replace(re,"$1"+key+"="+value+"$2$3")}else{output=url.replace(re,"$1$3").replace(/(&|\?)$/,"")}}else{if(typeof value!=="undefined"&&value!==null){var separator=url.indexOf("?")!==-1?"&":"?";var hash=url.split("#");url=hash[0]+separator+key+"="+value;if(hash[1]){url+="#"+hash[1]}output=url}else{output=url}}if(redirect){window.location.href=output}else{return output}},getQueryString:function(parameter){if(typeof parameter==="undefined"){parameter=""}var output={};var keyValues=location.search.substring(1).split("&");for(var i in keyValues){var key=keyValues[i].split("=");if(key.length>1){if(parameter&¶meter==this.decodeURI(key[0])){return this.decodeURI(key[1])}else{output[this.decodeURI(key[0])]=this.decodeURI(key[1])}}}return output},decodeURI:function(value){return decodeURIComponent(value.replace(/\+/g," "))}};Phaser.Net.prototype.constructor=Phaser.Net;Phaser.TweenManager=function(game){this.game=game;this._tweens=[];this._add=[];this.game.onPause.add(this._pauseAll,this);this.game.onResume.add(this._resumeAll,this)};Phaser.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var i=0;i0){this._tweens=this._tweens.concat(this._add);this._add.length=0}return true},isTweening:function(object){return this._tweens.some(function(tween){return tween._object===object})},_pauseAll:function(){for(var i=this._tweens.length-1;i>=0;i--){this._tweens[i]._pause()}},_resumeAll:function(){for(var i=this._tweens.length-1;i>=0;i--){this._tweens[i]._resume()}},pauseAll:function(){for(var i=this._tweens.length-1;i>=0;i--){this._tweens[i].pause()}},resumeAll:function(){for(var i=this._tweens.length-1;i>=0;i--){this._tweens[i].resume(true)}}};Phaser.TweenManager.prototype.constructor=Phaser.TweenManager;Phaser.Tween=function(object,game,manager){this._object=object;this.game=game;this._manager=manager;this._valuesStart={};this._valuesEnd={};this._valuesStartRepeat={};this._duration=1e3;this._repeat=0;this._yoyo=false;this._reversed=false;this._delayTime=0;this._startTime=null;this._easingFunction=Phaser.Easing.Linear.None;this._interpolationFunction=Phaser.Math.linearInterpolation;this._chainedTweens=[];this._onStartCallbackFired=false;this._onUpdateCallback=null;this._onUpdateCallbackContext=null;this._paused=false;this._pausedTime=0;this._codePaused=false;this.pendingDelete=false;this.onStart=new Phaser.Signal;this.onLoop=new Phaser.Signal;this.onComplete=new Phaser.Signal;this.isRunning=false};Phaser.Tween.prototype={to:function(properties,duration,ease,autoStart,delay,repeat,yoyo){duration=duration||1e3;ease=ease||null;autoStart=autoStart||false;delay=delay||0;repeat=repeat||0;yoyo=yoyo||false;if(yoyo&&repeat===0){repeat=1}var self;if(this._parent){self=this._manager.create(this._object);this._lastChild.chain(self);this._lastChild=self}else{self=this;this._parent=this;this._lastChild=this}self._repeat=repeat;self._duration=duration;self._valuesEnd=properties;if(ease!==null){self._easingFunction=ease}if(delay>0){self._delayTime=delay}self._yoyo=yoyo;if(autoStart){return this.start()}else{return this}},from:function(properties,duration,ease,autoStart,delay,repeat,yoyo){var _cache={};for(var prop in properties){if(properties.hasOwnProperty(prop)){_cache[prop]=this._object[prop];this._object[prop]=properties[prop]}}this.to(_cache,duration,ease,autoStart,delay,repeat,yoyo)},start:function(){if(this.game===null||this._object===null){return}this._manager.add(this); this.isRunning=true;this._onStartCallbackFired=false;this._startTime=this.game.time.now+this._delayTime;for(var property in this._valuesEnd){if(Array.isArray(this._valuesEnd[property])){if(this._valuesEnd[property].length===0){continue}this._valuesEnd[property]=[this._object[property]].concat(this._valuesEnd[property])}this._valuesStart[property]=this._object[property];if(!Array.isArray(this._valuesStart[property])){this._valuesStart[property]*=1}this._valuesStartRepeat[property]=this._valuesStart[property]||0}return this},generateData:function(frameRate,data){if(this.game===null||this._object===null){return null}this._startTime=0;for(var property in this._valuesEnd){if(Array.isArray(this._valuesEnd[property])){if(this._valuesEnd[property].length===0){continue}this._valuesEnd[property]=[this._object[property]].concat(this._valuesEnd[property])}this._valuesStart[property]=this._object[property];if(!Array.isArray(this._valuesStart[property])){this._valuesStart[property]*=1}this._valuesStartRepeat[property]=this._valuesStart[property]||0}var time=0;var total=Math.floor(frameRate*(this._duration/1e3));var tick=this._duration/total;var output=[];while(total--){var property;var elapsed=(time-this._startTime)/this._duration;elapsed=elapsed>1?1:elapsed;var value=this._easingFunction(elapsed);var blob={};for(property in this._valuesEnd){var start=this._valuesStart[property]||0;var end=this._valuesEnd[property];if(end instanceof Array){blob[property]=this._interpolationFunction(end,value)}else{if(typeof end==="string"){end=start+parseFloat(end,10)}if(typeof end==="number"){blob[property]=start+(end-start)*value}}}output.push(blob);time+=tick}if(this._yoyo){var reversed=output.slice();reversed.reverse();output=output.concat(reversed)}if(typeof data!=="undefined"){data=data.concat(output);return data}else{return output}},stop:function(){this.isRunning=false;this._onUpdateCallback=null;this._manager.remove(this);return this},delay:function(amount){this._delayTime=amount;return this},repeat:function(times){this._repeat=times;return this},yoyo:function(yoyo){this._yoyo=yoyo;if(yoyo&&this._repeat===0){this._repeat=1}return this},easing:function(easing){this._easingFunction=easing;return this},interpolation:function(interpolation){this._interpolationFunction=interpolation;return this},chain:function(){this._chainedTweens=arguments;return this},loop:function(){this._lastChild.chain(this);return this},onUpdateCallback:function(callback,callbackContext){this._onUpdateCallback=callback;this._onUpdateCallbackContext=callbackContext;return this},pause:function(){this._codePaused=true;this._paused=true;this._pausedTime=this.game.time.now},_pause:function(){if(!this._codePaused){this._paused=true;this._pausedTime=this.game.time.now}},resume:function(){if(this._paused){this._paused=false;this._codePaused=false;this._startTime+=this.game.time.now-this._pausedTime}},_resume:function(){if(this._codePaused){return}else{this._startTime+=this.game.time.pauseDuration;this._paused=false}},update:function(time){if(this.pendingDelete){return false}if(this._paused||time1?1:elapsed;var value=this._easingFunction(elapsed);for(property in this._valuesEnd){var start=this._valuesStart[property]||0;var end=this._valuesEnd[property];if(end instanceof Array){this._object[property]=this._interpolationFunction(end,value)}else{if(typeof end==="string"){end=start+parseFloat(end,10)}if(typeof end==="number"){this._object[property]=start+(end-start)*value}}}if(this._onUpdateCallback!==null){this._onUpdateCallback.call(this._onUpdateCallbackContext,this,value)}if(elapsed==1){if(this._repeat>0){if(isFinite(this._repeat)){this._repeat--}for(property in this._valuesStartRepeat){if(typeof this._valuesEnd[property]==="string"){this._valuesStartRepeat[property]=this._valuesStartRepeat[property]+parseFloat(this._valuesEnd[property],10)}if(this._yoyo){var tmp=this._valuesStartRepeat[property];this._valuesStartRepeat[property]=this._valuesEnd[property];this._valuesEnd[property]=tmp}this._valuesStart[property]=this._valuesStartRepeat[property]}if(this._yoyo){this._reversed=!this._reversed}this._startTime=time+this._delayTime;this.onLoop.dispatch(this._object);return true}else{this.isRunning=false;this.onComplete.dispatch(this._object);for(var i=0,numChainedTweens=this._chainedTweens.length;ithis.timeCap){this.elapsed=1/60}this.physicsElapsed=this.elapsed/1e3||1/60;if(this.deltaCap>0&&this.physicsElapsed>this.deltaCap){this.physicsElapsed=this.deltaCap}if(this.advancedTiming){this.msMin=this.game.math.min(this.msMin,this.elapsed);this.msMax=this.game.math.max(this.msMax,this.elapsed);this.frames++;if(this.now>this._timeLastSecond+1e3){this.fps=Math.round(this.frames*1e3/(this.now-this._timeLastSecond));this.fpsMin=this.game.math.min(this.fpsMin,this.fps);this.fpsMax=this.game.math.max(this.fpsMax,this.fps);this._timeLastSecond=this.now;this.frames=0}}this.time=this.now;this.lastTime=time+this.timeToCall;if(!this.game.paused){this.events.update(this.now);this._i=0;this._len=this._timers.length;while(this._i0){this.events.sort(this.sortHandler);this.nextTick=this.events[0].tick}},sortHandler:function(a,b){if(a.tickb.tick){return 1}return 0},clearPendingEvents:function(){this._i=this.events.length;while(this._i--){if(this.events[this._i].pendingDelete){this.events.splice(this._i,1)}}this._len=this.events.length;this._i=0},update:function(time){if(this.paused){return true}this.elapsed=time-this._now;this._now=time;if(this.elapsed>this.timeCap){this.adjustEvents(time-this.elapsed)}this._marked=0;this.clearPendingEvents();if(this.running&&this._now>=this.nextTick&&this._len>0){while(this._i=this.events[this._i].tick){this._newTick=this._now+this.events[this._i].delay-(this._now-this.events[this._i].tick);if(this._newTick<0){this._newTick=this._now+this.events[this._i].delay}if(this.events[this._i].loop===true){this.events[this._i].tick=this._newTick;this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)}else if(this.events[this._i].repeatCount>0){this.events[this._i].repeatCount--;this.events[this._i].tick=this._newTick;this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)}else{this._marked++;this.events[this._i].pendingDelete=true;this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)}this._i++}else{break}}if(this.events.length>this._marked){this.order()}else{this.expired=true;this.onComplete.dispatch(this)}}if(this.expired&&this.autoDestroy){return false}else{return true}},pause:function(){if(!this.running){return}this._codePaused=true;if(this.paused){return}this._pauseStarted=this.game.time.now;this.paused=true},_pause:function(){if(this.paused||!this.running){return}this._pauseStarted=this.game.time.now;this.paused=true},adjustEvents:function(baseTime){for(var i=0;ithis._now){return this.nextTick-this._now}else{return 0}}});Object.defineProperty(Phaser.Timer.prototype,"length",{get:function(){return this.events.length}});Object.defineProperty(Phaser.Timer.prototype,"ms",{get:function(){return this._now-this._started-this._pauseTotal}});Object.defineProperty(Phaser.Timer.prototype,"seconds",{get:function(){return this.ms*.001}});Phaser.Timer.prototype.constructor=Phaser.Timer;Phaser.TimerEvent=function(timer,delay,tick,repeatCount,loop,callback,callbackContext,args){this.timer=timer;this.delay=delay;this.tick=tick;this.repeatCount=repeatCount-1;this.loop=loop;this.callback=callback;this.callbackContext=callbackContext;this.args=args;this.pendingDelete=false};Phaser.TimerEvent.prototype.constructor=Phaser.TimerEvent;Phaser.AnimationManager=function(sprite){this.sprite=sprite;this.game=sprite.game;this.currentFrame=null;this.currentAnim=null;this.updateIfVisible=true;this.isLoaded=false;this._frameData=null;this._anims={};this._outputFrames=[]};Phaser.AnimationManager.prototype={loadFrameData:function(frameData){this._frameData=frameData;this.frame=0;this.isLoaded=true},add:function(name,frames,frameRate,loop,useNumericIndex){if(this._frameData===null){console.warn("No FrameData available for Phaser.Animation "+name);return}frames=frames||[];frameRate=frameRate||60;if(typeof loop==="undefined"){loop=false}if(typeof useNumericIndex==="undefined"){if(frames&&typeof frames[0]==="number"){useNumericIndex=true}else{useNumericIndex=false}}if(this.sprite.events.onAnimationStart===null){this.sprite.events.onAnimationStart=new Phaser.Signal;this.sprite.events.onAnimationComplete=new Phaser.Signal;this.sprite.events.onAnimationLoop=new Phaser.Signal}this._outputFrames.length=0;this._frameData.getFrameIndexes(frames,useNumericIndex,this._outputFrames);this._anims[name]=new Phaser.Animation(this.game,this.sprite,name,this._frameData,this._outputFrames,frameRate,loop);this.currentAnim=this._anims[name];this.currentFrame=this.currentAnim.currentFrame;this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);if(this.sprite.__tilePattern){this.__tilePattern=false;this.tilingTexture=false}return this._anims[name]},validateFrames:function(frames,useNumericIndex){if(typeof useNumericIndex=="undefined"){useNumericIndex=true}for(var i=0;ithis._frameData.total){return false}}else{if(this._frameData.checkFrameName(frames[i])===false){return false}}}return true},play:function(name,frameRate,loop,killOnComplete){if(this._anims[name]){if(this.currentAnim===this._anims[name]){if(this.currentAnim.isPlaying===false){this.currentAnim.paused=false;return this.currentAnim.play(frameRate,loop,killOnComplete)}}else{if(this.currentAnim&&this.currentAnim.isPlaying){this.currentAnim.stop()}this.currentAnim=this._anims[name];this.currentAnim.paused=false;return this.currentAnim.play(frameRate,loop,killOnComplete)}}},stop:function(name,resetFrame){if(typeof resetFrame=="undefined"){resetFrame=false}if(typeof name=="string"){if(this._anims[name]){this.currentAnim=this._anims[name];this.currentAnim.stop(resetFrame)}}else{if(this.currentAnim){this.currentAnim.stop(resetFrame)}}},update:function(){if(this.updateIfVisible&&!this.sprite.visible){return false}if(this.currentAnim&&this.currentAnim.update()===true){this.currentFrame=this.currentAnim.currentFrame;return true}return false},getAnimation:function(name){if(typeof name==="string"){if(this._anims[name]){return this._anims[name]}}return null},refreshFrame:function(){this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);if(this.sprite.__tilePattern){this.__tilePattern=false;this.tilingTexture=false}},destroy:function(){var anim=null;for(var anim in this._anims){if(this._anims.hasOwnProperty(anim)){this._anims[anim].destroy()}}this._anims={};this._frameData=null;this._frameIndex=0;this.currentAnim=null;this.currentFrame=null}};Phaser.AnimationManager.prototype.constructor=Phaser.AnimationManager;Object.defineProperty(Phaser.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}});Object.defineProperty(Phaser.AnimationManager.prototype,"frameTotal",{get:function(){if(this._frameData){return this._frameData.total}else{return-1}}});Object.defineProperty(Phaser.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(value){this.currentAnim.paused=value}});Object.defineProperty(Phaser.AnimationManager.prototype,"frame",{get:function(){if(this.currentFrame){return this._frameIndex}},set:function(value){if(typeof value==="number"&&this._frameData&&this._frameData.getFrame(value)!==null){this.currentFrame=this._frameData.getFrame(value);if(this.currentFrame){this._frameIndex=value;this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);if(this.sprite.__tilePattern){this.__tilePattern=false;this.tilingTexture=false}}}}});Object.defineProperty(Phaser.AnimationManager.prototype,"frameName",{get:function(){if(this.currentFrame){return this.currentFrame.name}},set:function(value){if(typeof value==="string"&&this._frameData&&this._frameData.getFrameByName(value)!==null){this.currentFrame=this._frameData.getFrameByName(value);if(this.currentFrame){this._frameIndex=this.currentFrame.index;this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);if(this.sprite.__tilePattern){this.__tilePattern=false;this.tilingTexture=false}}}else{console.warn("Cannot set frameName: "+value)}}});Phaser.Animation=function(game,parent,name,frameData,frames,delay,loop){this.game=game;this._parent=parent;this._frameData=frameData;this.name=name;this._frames=[];this._frames=this._frames.concat(frames);this.delay=1e3/delay;this.loop=loop;this.loopCount=0;this.killOnComplete=false;this.isFinished=false;this.isPlaying=false;this.isPaused=false;this._pauseStartTime=0;this._frameIndex=0;this._frameDiff=0;this._frameSkip=1;this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]);this.onStart=new Phaser.Signal;this.onComplete=new Phaser.Signal;this.onLoop=new Phaser.Signal;this.game.onPause.add(this.onPause,this);this.game.onResume.add(this.onResume,this)};Phaser.Animation.prototype={play:function(frameRate,loop,killOnComplete){if(typeof frameRate==="number"){this.delay=1e3/frameRate}if(typeof loop==="boolean"){this.loop=loop}if(typeof killOnComplete!=="undefined"){this.killOnComplete=killOnComplete}this.isPlaying=true;this.isFinished=false;this.paused=false;this.loopCount=0;this._timeLastFrame=this.game.time.now;this._timeNextFrame=this.game.time.now+this.delay;this._frameIndex=0;this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]);this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);if(this._parent.__tilePattern){this._parent.__tilePattern=false;this._parent.tilingTexture=false}this._parent.events.onAnimationStart.dispatch(this._parent,this);this.onStart.dispatch(this._parent,this);return this},restart:function(){this.isPlaying=true;this.isFinished=false;this.paused=false;this.loopCount=0;this._timeLastFrame=this.game.time.now;this._timeNextFrame=this.game.time.now+this.delay;this._frameIndex=0;this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]);this.onStart.dispatch(this._parent,this)},setFrame:function(frameId,useLocalFrameIndex){var frameIndex;if(typeof useLocalFrameIndex==="undefined"){useLocalFrameIndex=false}if(typeof frameId==="string"){for(var i=0;i=this._timeNextFrame){this._frameSkip=1;this._frameDiff=this.game.time.now-this._timeNextFrame;this._timeLastFrame=this.game.time.now;if(this._frameDiff>this.delay){this._frameSkip=Math.floor(this._frameDiff/this.delay);this._frameDiff-=this._frameSkip*this.delay}this._timeNextFrame=this.game.time.now+(this.delay-this._frameDiff);this._frameIndex+=this._frameSkip;if(this._frameIndex>=this._frames.length){if(this.loop){this._frameIndex%=this._frames.length;this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]);if(this.currentFrame){this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);if(this._parent.__tilePattern){this._parent.__tilePattern=false;this._parent.tilingTexture=false}}this.loopCount++;this._parent.events.onAnimationLoop.dispatch(this._parent,this);this.onLoop.dispatch(this._parent,this)}else{this.complete()}}else{this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]);if(this.currentFrame){this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);if(this._parent.__tilePattern){this._parent.__tilePattern=false;this._parent.tilingTexture=false}}}return true}return false},destroy:function(){this.game.onPause.remove(this.onPause,this);this.game.onResume.remove(this.onResume,this);this.game=null;this._parent=null;this._frames=null;this._frameData=null;this.currentFrame=null;this.isPlaying=false;this.onStart.dispose();this.onLoop.dispose();this.onComplete.dispose()},complete:function(){this.isPlaying=false;this.isFinished=true;this.paused=false;this._parent.events.onAnimationComplete.dispatch(this._parent,this);this.onComplete.dispatch(this._parent,this);if(this.killOnComplete){this._parent.kill()}}};Phaser.Animation.prototype.constructor=Phaser.Animation;Object.defineProperty(Phaser.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(value){this.isPaused=value;if(value){this._pauseStartTime=this.game.time.now}else{if(this.isPlaying){this._timeNextFrame=this.game.time.now+this.delay}}}});Object.defineProperty(Phaser.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}});Object.defineProperty(Phaser.Animation.prototype,"frame",{get:function(){if(this.currentFrame!==null){return this.currentFrame.index}else{return this._frameIndex}},set:function(value){this.currentFrame=this._frameData.getFrame(this._frames[value]);if(this.currentFrame!==null){this._frameIndex=value;this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid])}}});Object.defineProperty(Phaser.Animation.prototype,"speed",{get:function(){return Math.round(1e3/this.delay)},set:function(value){if(value>=1){this.delay=1e3/value}}});Phaser.Animation.generateFrameNames=function(prefix,start,stop,suffix,zeroPad){if(typeof suffix=="undefined"){suffix=""}var output=[];var frame="";if(start=stop;i--){if(typeof zeroPad=="number"){frame=Phaser.Utils.pad(i.toString(),zeroPad,"0",1)}else{frame=i.toString()}frame=prefix+frame+suffix;output.push(frame)}}return output};Phaser.Frame=function(index,x,y,width,height,name,uuid){this.index=index;this.x=x;this.y=y;this.width=width;this.height=height;this.name=name;this.uuid=uuid;this.centerX=Math.floor(width/2);this.centerY=Math.floor(height/2);this.distance=Phaser.Math.distance(0,0,width,height);this.rotated=false;this.rotationDirection="cw";this.trimmed=false;this.sourceSizeW=width;this.sourceSizeH=height;this.spriteSourceSizeX=0;this.spriteSourceSizeY=0;this.spriteSourceSizeW=0;this.spriteSourceSizeH=0};Phaser.Frame.prototype={setTrim:function(trimmed,actualWidth,actualHeight,destX,destY,destWidth,destHeight){this.trimmed=trimmed;if(trimmed){this.width=actualWidth;this.height=actualHeight;this.sourceSizeW=actualWidth;this.sourceSizeH=actualHeight;this.centerX=Math.floor(actualWidth/2);this.centerY=Math.floor(actualHeight/2);this.spriteSourceSizeX=destX;this.spriteSourceSizeY=destY;this.spriteSourceSizeW=destWidth;this.spriteSourceSizeH=destHeight}},getRect:function(out){if(typeof out==="undefined"){out=new Phaser.Rectangle(this.x,this.y,this.width,this.height)}else{out.setTo(this.x,this.y,this.width,this.height)}return out}};Phaser.Frame.prototype.constructor=Phaser.Frame;Phaser.FrameData=function(){this._frames=[];this._frameNames=[]};Phaser.FrameData.prototype={addFrame:function(frame){frame.index=this._frames.length;this._frames.push(frame);if(frame.name!==""){this._frameNames[frame.name]=frame.index}return frame},getFrame:function(index){if(index>this._frames.length){index=0}return this._frames[index]},getFrameByName:function(name){if(typeof this._frameNames[name]==="number"){return this._frames[this._frameNames[name]]}return null},checkFrameName:function(name){if(this._frameNames[name]==null){return false}return true},getFrameRange:function(start,end,output){if(typeof output==="undefined"){output=[]}for(var i=start;i<=end;i++){output.push(this._frames[i])}return output},getFrames:function(frames,useNumericIndex,output){if(typeof useNumericIndex==="undefined"){useNumericIndex=true}if(typeof output==="undefined"){output=[]}if(typeof frames==="undefined"||frames.length===0){for(var i=0;iwidth){x=margin;y+=frameHeight+spacing}}return data},JSONData:function(game,json,cacheKey){if(!json["frames"]){console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array");console.log(json);return}var data=new Phaser.FrameData;var frames=json["frames"];var newFrame;for(var i=0;i tag");return}var data=new Phaser.FrameData;var frames=xml.getElementsByTagName("SubTexture");var newFrame;var uuid;var name;var frame;var x;var y;var width;var height;var frameX;var frameY;var frameWidth;var frameHeight;for(var i=0;i0){for(var i=0;i0){for(var i=0;i0){for(var i=0;i0){this._fileIndex=0;this._progressChunk=100/this._fileList.length;this.loadFile()}else{this.progress=100;this.progressFloat=100;this.hasLoaded=true;this.onLoadComplete.dispatch()}},loadFile:function(){if(!this._fileList[this._fileIndex]){console.warn("Phaser.Loader loadFile invalid index "+this._fileIndex);return}var file=this._fileList[this._fileIndex];var _this=this;this.onFileStart.dispatch(this.progress,file.key);switch(file.type){case"image":case"spritesheet":case"textureatlas":case"bitmapfont":file.data=new Image;file.data.name=file.key;file.data.onload=function(){return _this.fileComplete(_this._fileIndex)};file.data.onerror=function(){return _this.fileError(_this._fileIndex)};if(this.crossOrigin){file.data.crossOrigin=this.crossOrigin}file.data.src=this.baseURL+file.url;break;case"audio":file.url=this.getAudioURL(file.url);if(file.url!==null){if(this.game.sound.usingWebAudio){this._xhr.open("GET",this.baseURL+file.url,true);this._xhr.responseType="arraybuffer";this._xhr.onload=function(){return _this.fileComplete(_this._fileIndex)};this._xhr.onerror=function(){return _this.fileError(_this._fileIndex)};this._xhr.send()}else if(this.game.sound.usingAudioTag){if(this.game.sound.touchLocked){file.data=new Audio;file.data.name=file.key;file.data.preload="auto";file.data.src=this.baseURL+file.url;this.fileComplete(this._fileIndex)}else{file.data=new Audio;file.data.name=file.key;file.data.onerror=function(){return _this.fileError(_this._fileIndex)};file.data.preload="auto";file.data.src=this.baseURL+file.url;file.data.addEventListener("canplaythrough",Phaser.GAMES[this.game.id].load.fileComplete(this._fileIndex),false);file.data.load()}}}else{this.fileError(this._fileIndex)}break;case"json":if(window.XDomainRequest){this._ajax=new window.XDomainRequest;this._ajax.timeout=3e3;this._ajax.onerror=function(){return _this.dataLoadError(_this._fileIndex)};this._ajax.ontimeout=function(){return _this.dataLoadError(_this._fileIndex)};this._ajax.onprogress=function(){};this._ajax.onload=function(){return _this.jsonLoadComplete(_this._fileIndex)};this._ajax.open("GET",this.baseURL+file.url,true);this._ajax.send()}else{this._xhr.open("GET",this.baseURL+file.url,true);this._xhr.responseType="text";this._xhr.onload=function(){return _this.jsonLoadComplete(_this._fileIndex)};this._xhr.onerror=function(){return _this.dataLoadError(_this._fileIndex)};this._xhr.send()}break;case"tilemap":this._xhr.open("GET",this.baseURL+file.url,true);this._xhr.responseType="text";if(file.format===Phaser.Tilemap.TILED_JSON){this._xhr.onload=function(){return _this.jsonLoadComplete(_this._fileIndex)}}else if(file.format===Phaser.Tilemap.CSV){this._xhr.onload=function(){return _this.csvLoadComplete(_this._fileIndex)}}else{throw new Error("Phaser.Loader. Invalid Tilemap format: "+file.format)}this._xhr.onerror=function(){return _this.dataLoadError(_this._fileIndex)};this._xhr.send();break;case"text":case"script":case"physics":this._xhr.open("GET",this.baseURL+file.url,true);this._xhr.responseType="text";this._xhr.onload=function(){return _this.fileComplete(_this._fileIndex)};this._xhr.onerror=function(){return _this.fileError(_this._fileIndex)};this._xhr.send();break;case"binary":this._xhr.open("GET",this.baseURL+file.url,true);this._xhr.responseType="arraybuffer";this._xhr.onload=function(){return _this.fileComplete(_this._fileIndex)};this._xhr.onerror=function(){return _this.fileError(_this._fileIndex)};this._xhr.send();break}},getAudioURL:function(urls){var extension;if(typeof urls==="string"){urls=[urls]}for(var i=0;i100){this.progress=100}if(this.preloadSprite!==null){if(this.preloadSprite.direction===0){this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress);this.preloadSprite.sprite.crop(this.preloadSprite.rect)}else{this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress);this.preloadSprite.sprite.crop(this.preloadSprite.rect)}}this.onFileComplete.dispatch(this.progress,this._fileList[previousIndex].key,success,this.totalLoadedFiles(),this._fileList.length);if(this.totalQueuedFiles()>0){this._fileIndex++;this.loadFile()}else{this.hasLoaded=true;this.isLoading=false;this.removeAll();this.onLoadComplete.dispatch()}},totalLoadedFiles:function(){var total=0;for(var i=0;i=this.durationMS){if(this.usingWebAudio){if(this.loop){this.onLoop.dispatch(this);if(this.currentMarker===""){this.currentTime=0;this.startTime=this.game.time.now}else{this.onMarkerComplete.dispatch(this.currentMarker,this);this.play(this.currentMarker,0,this.volume,true,true)}}else{this.stop()}}else{if(this.loop){this.onLoop.dispatch(this);this.play(this.currentMarker,0,this.volume,true,true)}else{this.stop()}}}}},play:function(marker,position,volume,loop,forceRestart){if(typeof marker==="undefined"){marker=""}if(typeof forceRestart==="undefined"){forceRestart=true}if(this.isPlaying===true&&forceRestart===false&&this.override===false){return this}if(this.isPlaying&&this.override){if(this.usingWebAudio){if(typeof this._sound.stop==="undefined"){this._sound.noteOff(0)}else{this._sound.stop(0)}}else if(this.usingAudioTag){this._sound.pause();this._sound.currentTime=0}}this.currentMarker=marker;if(marker!==""){if(this.markers[marker]){this.position=this.markers[marker].start;this.volume=this.markers[marker].volume;this.loop=this.markers[marker].loop;this.duration=this.markers[marker].duration;this.durationMS=this.markers[marker].durationMS;if(typeof volume!=="undefined"){this.volume=volume}if(typeof loop!=="undefined"){this.loop=loop}this._tempMarker=marker;this._tempPosition=this.position;this._tempVolume=this.volume;this._tempLoop=this.loop}else{console.warn("Phaser.Sound.play: audio marker "+marker+" doesn't exist");return this}}else{position=position||0;if(typeof volume==="undefined"){volume=this._volume}if(typeof loop==="undefined"){loop=this.loop}this.position=position;this.volume=volume;this.loop=loop;this.duration=0;this.durationMS=0;this._tempMarker=marker;this._tempPosition=position;this._tempVolume=volume;this._tempLoop=loop}if(this.usingWebAudio){if(this.game.cache.isSoundDecoded(this.key)){if(this._buffer==null){this._buffer=this.game.cache.getSoundData(this.key)}this._sound=this.context.createBufferSource();this._sound.buffer=this._buffer;if(this.externalNode){this._sound.connect(this.externalNode.input)}else{this._sound.connect(this.gainNode)}this.totalDuration=this._sound.buffer.duration;if(this.duration===0){this.duration=this.totalDuration;this.durationMS=this.totalDuration*1e3}if(this.loop&&marker===""){this._sound.loop=true}if(typeof this._sound.start==="undefined"){this._sound.noteGrainOn(0,this.position,this.duration)}else{this._sound.start(0,this.position,this.duration)}this.isPlaying=true;this.startTime=this.game.time.now;this.currentTime=0;this.stopTime=this.startTime+this.durationMS;this.onPlay.dispatch(this)}else{this.pendingPlayback=true;if(this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).isDecoding===false){this.game.sound.decode(this.key,this)}}}else{if(this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked){this.game.cache.reloadSound(this.key);this.pendingPlayback=true}else{if(this._sound&&(this.game.device.cocoonJS||this._sound.readyState===4)){this._sound.play();this.totalDuration=this._sound.duration;if(this.duration===0){this.duration=this.totalDuration;this.durationMS=this.totalDuration*1e3}this._sound.currentTime=this.position;this._sound.muted=this._muted;if(this._muted){this._sound.volume=0}else{this._sound.volume=this._volume}this.isPlaying=true;this.startTime=this.game.time.now;this.currentTime=0;this.stopTime=this.startTime+this.durationMS;this.onPlay.dispatch(this)}else{this.pendingPlayback=true}}}return this},restart:function(marker,position,volume,loop){marker=marker||"";position=position||0;volume=volume||1;if(typeof loop=="undefined"){loop=false}this.play(marker,position,volume,loop,true)},pause:function(){if(this.isPlaying&&this._sound){this.stop();this.isPlaying=false;this.paused=true;this.pausedPosition=this.currentTime;this.pausedTime=this.game.time.now;this.onPause.dispatch(this)}},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var p=this.position+this.pausedPosition/1e3;this._sound=this.context.createBufferSource();this._sound.buffer=this._buffer;if(this.externalNode){this._sound.connect(this.externalNode.input)}else{this._sound.connect(this.gainNode)}if(this.loop){this._sound.loop=true}if(typeof this._sound.start==="undefined"){this._sound.noteGrainOn(0,p,this.duration)}else{this._sound.start(0,p,this.duration)}}else{this._sound.play()}this.isPlaying=true;this.paused=false;this.startTime+=this.game.time.now-this.pausedTime;this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound){if(this.usingWebAudio){if(typeof this._sound.stop==="undefined"){this._sound.noteOff(0)}else{try{this._sound.stop(0)}catch(e){}}}else if(this.usingAudioTag){this._sound.pause();this._sound.currentTime=0}}this.isPlaying=false;var prevMarker=this.currentMarker;if(this.currentMarker!==""){this.onMarkerComplete.dispatch(this.currentMarker,this)}this.currentMarker="";this.onStop.dispatch(this,prevMarker)},destroy:function(remove){if(typeof remove==="undefined"){remove=true}this.stop();if(remove){this.game.sound.remove(this)}this.markers={};this.context=null;this._buffer=null;this.externalNode=null;this.onDecoded.dispose();this.onPlay.dispose();this.onPause.dispose();this.onResume.dispose();this.onLoop.dispose();this.onStop.dispose();this.onMute.dispose();this.onMarkerComplete.dispose()}};Phaser.Sound.prototype.constructor=Phaser.Sound;Object.defineProperty(Phaser.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}});Object.defineProperty(Phaser.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}});Object.defineProperty(Phaser.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(value){value=value||null;if(value){this._muted=true;if(this.usingWebAudio){this._muteVolume=this.gainNode.gain.value;this.gainNode.gain.value=0}else if(this.usingAudioTag&&this._sound){this._muteVolume=this._sound.volume;this._sound.volume=0}}else{this._muted=false;if(this.usingWebAudio){this.gainNode.gain.value=this._muteVolume}else if(this.usingAudioTag&&this._sound){this._sound.volume=this._muteVolume}}this.onMute.dispatch(this)}});Object.defineProperty(Phaser.Sound.prototype,"volume",{get:function(){return this._volume},set:function(value){if(this.usingWebAudio){this._volume=value;this.gainNode.gain.value=value}else if(this.usingAudioTag&&this._sound){if(value>=0&&value<=1){this._volume=value;this._sound.volume=value}}}});Phaser.SoundManager=function(game){this.game=game;this.onSoundDecode=new Phaser.Signal;this._codeMuted=false;this._muted=false;this._unlockSource=null;this._volume=1;this._sounds=[];this.context=null;this.usingWebAudio=true;this.usingAudioTag=false;this.noAudio=false;this.connectToMaster=true;this.touchLocked=false;this.channels=32};Phaser.SoundManager.prototype={boot:function(){if(this.game.device.iOS&&this.game.device.webAudio===false){this.channels=1}if(this.game.device.iOS||window["PhaserGlobal"]&&window["PhaserGlobal"].fakeiOSTouchLock){this.game.input.touch.callbackContext=this;this.game.input.touch.touchStartCallback=this.unlock;this.game.input.mouse.callbackContext=this;this.game.input.mouse.mouseDownCallback=this.unlock;this.touchLocked=true}else{this.touchLocked=false}if(window["PhaserGlobal"]){if(window["PhaserGlobal"].disableAudio===true){this.usingWebAudio=false;this.noAudio=true;return}if(window["PhaserGlobal"].disableWebAudio===true){this.usingWebAudio=false;this.usingAudioTag=true;this.noAudio=false;return}}if(!!window["AudioContext"]){try{this.context=new window["AudioContext"]}catch(error){this.context=null;this.usingWebAudio=false;this.noAudio=true}}else if(!!window["webkitAudioContext"]){try{this.context=new window["webkitAudioContext"]}catch(error){this.context=null;this.usingWebAudio=false;this.noAudio=true}}if(!!window["Audio"]&&this.context===null){this.usingWebAudio=false;this.usingAudioTag=true;this.noAudio=false}if(this.context!==null){if(typeof this.context.createGain==="undefined"){this.masterGain=this.context.createGainNode()}else{this.masterGain=this.context.createGain()}this.masterGain.gain.value=1;this.masterGain.connect(this.context.destination)}},unlock:function(){if(this.touchLocked===false){return}if(this.game.device.webAudio===false||window["PhaserGlobal"]&&window["PhaserGlobal"].disableWebAudio===true){this.touchLocked=false;this._unlockSource=null;this.game.input.touch.callbackContext=null;this.game.input.touch.touchStartCallback=null;this.game.input.mouse.callbackContext=null;this.game.input.mouse.mouseDownCallback=null}else{var buffer=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource();this._unlockSource.buffer=buffer;this._unlockSource.connect(this.context.destination);this._unlockSource.noteOn(0)}},stopAll:function(){for(var i=0;i>>24;out.b=(rgba&16711680)>>>16;out.g=(rgba&65280)>>>8;out.r=rgba&255}else{out.r=(rgba&4278190080)>>>24;out.g=(rgba&16711680)>>>16;out.b=(rgba&65280)>>>8;out.a=rgba&255}out.color=rgba;out.rgba="rgba("+out.r+","+out.g+","+out.b+","+out.a/255+")";if(hsl){Phaser.Color.RGBtoHSL(out.r,out.g,out.b,out)}if(hsv){Phaser.Color.RGBtoHSV(out.r,out.g,out.b,out)}return out},fromRGBA:function(rgba,out){if(!out){out=Phaser.Color.createColor()}out.r=(rgba&4278190080)>>>24;out.g=(rgba&16711680)>>>16;out.b=(rgba&65280)>>>8;out.a=rgba&255;out.rgba="rgba("+out.r+","+out.g+","+out.b+","+out.a+")";return out},toRGBA:function(r,g,b,a){return r<<24|g<<16|b<<8|a},RGBtoHSL:function(r,g,b,out){if(!out){out=Phaser.Color.createColor(r,g,b,1)}r/=255;g/=255;b/=255;var min=Math.min(r,g,b);var max=Math.max(r,g,b);out.h=0;out.s=0;out.l=(max+min)/2;if(max!==min){var d=max-min;out.s=out.l>.5?d/(2-max-min):d/(max+min);if(max===r){out.h=(g-b)/d+(g1){t-=1}if(t<1/6){return p+(q-p)*6*t}if(t<1/2){return q}if(t<2/3){return p+(q-p)*(2/3-t)*6}return p},createColor:function(r,g,b,a,h,s,l,v){var out={r:r||0,g:g||0,b:b||0,a:a||1,h:h||0,s:s||0,l:l||0,v:v||0,color:0};out.rgba="rgba("+out.r+","+out.g+","+out.b+","+out.a+")";return out},updateColor:function(out){out.rgba="rgba("+out.r+","+out.g+","+out.b+","+out.a+")";return out},getColor32:function(a,r,g,b){return a<<24|r<<16|g<<8|b},getColor:function(r,g,b){return r<<16|g<<8|b},RGBtoString:function(r,g,b,a,prefix){if(typeof a==="undefined"){a=255}if(typeof prefix==="undefined"){prefix="#"}if(prefix==="#"){return"#"+((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1)}else{return"0x"+Phaser.Color.componentToHex(a)+Phaser.Color.componentToHex(r)+Phaser.Color.componentToHex(g)+Phaser.Color.componentToHex(b)}},hexToRGB:function(hex){var rgb=Phaser.Color.hexToColor(hex);if(rgb){return Phaser.Color.getColor32(rgb.a,rgb.r,rgb.g,rgb.b)}},hexToColor:function(hex,out){if(!out){out=Phaser.Color.createColor()}var shorthandRegex=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;hex=hex.replace(shorthandRegex,function(m,r,g,b){return r+r+g+g+b+b});var result=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);if(result){out.r=parseInt(result[1],16);out.g=parseInt(result[2],16);out.b=parseInt(result[3],16)}return out},componentToHex:function(color){var hex=color.toString(16);return hex.length==1?"0"+hex:hex},HSVColorWheel:function(s,v){if(typeof s==="undefined"){s=1}if(typeof v==="undefined"){v=1}var colors=[];for(var c=0;c<=359;c++){colors.push(Phaser.Color.HSVtoRGB(c/359,s,v))}return colors},HSLColorWheel:function(s,l){if(typeof s==="undefined"){s=.5}if(typeof l==="undefined"){l=.5}var colors=[];for(var c=0;c<=359;c++){colors.push(Phaser.Color.HSLtoRGB(c/359,s,l))}return colors},interpolateColor:function(color1,color2,steps,currentStep,alpha){if(typeof alpha==="undefined"){alpha=255}var src1=Phaser.Color.getRGB(color1);var src2=Phaser.Color.getRGB(color2);var r=(src2.red-src1.red)*currentStep/steps+src1.red;var g=(src2.green-src1.green)*currentStep/steps+src1.green;var b=(src2.blue-src1.blue)*currentStep/steps+src1.blue;return Phaser.Color.getColor32(alpha,r,g,b)},interpolateColorWithRGB:function(color,r,g,b,steps,currentStep){var src=Phaser.Color.getRGB(color);var or=(r-src.red)*currentStep/steps+src.red;var og=(g-src.green)*currentStep/steps+src.green;var ob=(b-src.blue)*currentStep/steps+src.blue;return Phaser.Color.getColor(or,og,ob)},interpolateRGB:function(r1,g1,b1,r2,g2,b2,steps,currentStep){var r=(r2-r1)*currentStep/steps+r1;var g=(g2-g1)*currentStep/steps+g1;var b=(b2-b1)*currentStep/steps+b1;return Phaser.Color.getColor(r,g,b)},getRandomColor:function(min,max,alpha){if(typeof min==="undefined"){min=0}if(typeof max==="undefined"){max=255}if(typeof alpha==="undefined"){alpha=255}if(max>255||min>max){return Phaser.Color.getColor(255,255,255)}var red=min+Math.round(Math.random()*(max-min));var green=min+Math.round(Math.random()*(max-min));var blue=min+Math.round(Math.random()*(max-min));return Phaser.Color.getColor32(alpha,red,green,blue)},getRGB:function(color){if(color>16777215){return{alpha:color>>>24,red:color>>16&255,green:color>>8&255,blue:color&255,a:color>>>24,r:color>>16&255,g:color>>8&255,b:color&255}}else{return{alpha:255,red:color>>16&255,green:color>>8&255,blue:color&255,a:255,r:color>>16&255,g:color>>8&255,b:color&255}}},getWebRGB:function(color){var rgb=Phaser.Color.getRGB(color);return"rgba("+rgb.r.toString()+","+rgb.g.toString()+","+rgb.b.toString()+","+rgb.a.toString()+")"},getAlpha:function(color){return color>>>24},getAlphaFloat:function(color){return(color>>>24)/255},getRed:function(color){return color>>16&255},getGreen:function(color){return color>>8&255},getBlue:function(color){return color&255; },getColorInfo:function(color){var argb=Phaser.Color.getRGB(color);var result=Phaser.Color.RGBtoHexstring(color)+"\n";result=result.concat("Alpha: "+argb.alpha+" Red: "+argb.red+" Green: "+argb.green+" Blue: "+argb.blue)+"\n";return result},RGBtoHexstring:function(color){var argb=Phaser.Color.getRGB(color);return"0x"+Phaser.Color.colorToHexstring(argb.alpha)+Phaser.Color.colorToHexstring(argb.red)+Phaser.Color.colorToHexstring(argb.green)+Phaser.Color.colorToHexstring(argb.blue)},RGBtoWebstring:function(color){var argb=Phaser.Color.getRGB(color);return"#"+Phaser.Color.colorToHexstring(argb.red)+Phaser.Color.colorToHexstring(argb.green)+Phaser.Color.colorToHexstring(argb.blue)},colorToHexstring:function(color){var digits="0123456789ABCDEF";var lsd=color%16;var msd=(color-lsd)/16;var hexified=digits.charAt(msd)+digits.charAt(lsd);return hexified}};Phaser.Physics=function(game,config){config=config||{};this.game=game;this.config=config;this.arcade=null;this.p2=null;this.ninja=null;this.box2d=null;this.chipmunk=null;this.parseConfig()};Phaser.Physics.ARCADE=0;Phaser.Physics.P2JS=1;Phaser.Physics.NINJA=2;Phaser.Physics.BOX2D=3;Phaser.Physics.CHIPMUNK=5;Phaser.Physics.prototype={parseConfig:function(){if((!this.config.hasOwnProperty("arcade")||this.config["arcade"]===true)&&Phaser.Physics.hasOwnProperty("Arcade")){this.arcade=new Phaser.Physics.Arcade(this.game);this.game.time.deltaCap=.2}if(this.config.hasOwnProperty("ninja")&&this.config["ninja"]===true&&Phaser.Physics.hasOwnProperty("Ninja")){this.ninja=new Phaser.Physics.Ninja(this.game)}if(this.config.hasOwnProperty("p2")&&this.config["p2"]===true&&Phaser.Physics.hasOwnProperty("P2")){this.p2=new Phaser.Physics.P2(this.game,this.config)}},startSystem:function(system){if(system===Phaser.Physics.ARCADE){this.arcade=new Phaser.Physics.Arcade(this.game)}else if(system===Phaser.Physics.P2JS){this.p2=new Phaser.Physics.P2(this.game,this.config)}if(system===Phaser.Physics.NINJA){this.ninja=new Phaser.Physics.Ninja(this.game)}else if(system===Phaser.Physics.BOX2D&&this.box2d===null){throw new Error("The Box2D physics system has not been implemented yet.")}else if(system===Phaser.Physics.CHIPMUNK&&this.chipmunk===null){throw new Error("The Chipmunk physics system has not been implemented yet.")}},enable:function(object,system,debug){if(typeof system==="undefined"){system=Phaser.Physics.ARCADE}if(typeof debug==="undefined"){debug=false}if(system===Phaser.Physics.ARCADE){this.arcade.enable(object)}else if(system===Phaser.Physics.P2JS&&this.p2){this.p2.enable(object,debug)}else if(system===Phaser.Physics.NINJA&&this.ninja){this.ninja.enableAABB(object)}},preUpdate:function(){if(this.p2){this.p2.preUpdate()}},update:function(){if(this.p2){this.p2.update()}},setBoundsToWorld:function(){if(this.arcade){this.arcade.setBoundsToWorld()}if(this.ninja){this.ninja.setBoundsToWorld()}if(this.p2){this.p2.setBoundsToWorld()}},clear:function(){if(this.p2){this.p2.clear()}},destroy:function(){if(this.p2){this.p2.destroy()}this.arcade=null;this.ninja=null;this.p2=null}};Phaser.Physics.prototype.constructor=Phaser.Physics;Phaser.Physics.Arcade=function(game){this.game=game;this.gravity=new Phaser.Point;this.bounds=new Phaser.Rectangle(0,0,game.world.width,game.world.height);this.checkCollision={up:true,down:true,left:true,right:true};this.maxObjects=10;this.maxLevels=4;this.OVERLAP_BIAS=4;this.TILE_BIAS=16;this.forceX=false;this.quadTree=new Phaser.QuadTree(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels);this._overlap=0;this._maxOverlap=0;this._velocity1=0;this._velocity2=0;this._newVelocity1=0;this._newVelocity2=0;this._average=0;this._mapData=[];this._result=false;this._total=0;this._angle=0;this._dx=0;this._dy=0};Phaser.Physics.Arcade.prototype.constructor=Phaser.Physics.Arcade;Phaser.Physics.Arcade.prototype={setBounds:function(x,y,width,height){this.bounds.setTo(x,y,width,height)},setBoundsToWorld:function(){this.bounds.setTo(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height)},enable:function(object,children){if(typeof children==="undefined"){children=true}var i=1;if(Array.isArray(object)){i=object.length;while(i--){if(object[i]instanceof Phaser.Group){this.enable(object[i].children,children)}else{this.enableBody(object[i]);if(children&&object[i].hasOwnProperty("children")&&object[i].children.length>0){this.enable(object[i],true)}}}}else{if(object instanceof Phaser.Group){this.enable(object.children,children)}else{this.enableBody(object);if(children&&object.hasOwnProperty("children")&&object.children.length>0){this.enable(object.children,true)}}}},enableBody:function(object){if(object.hasOwnProperty("body")&&object.body===null){object.body=new Phaser.Physics.Arcade.Body(object)}},updateMotion:function(body){this._velocityDelta=this.computeVelocity(0,body,body.angularVelocity,body.angularAcceleration,body.angularDrag,body.maxAngular)-body.angularVelocity;body.angularVelocity+=this._velocityDelta;body.rotation+=body.angularVelocity*this.game.time.physicsElapsed;body.velocity.x=this.computeVelocity(1,body,body.velocity.x,body.acceleration.x,body.drag.x,body.maxVelocity.x);body.velocity.y=this.computeVelocity(2,body,body.velocity.y,body.acceleration.y,body.drag.y,body.maxVelocity.y)},computeVelocity:function(axis,body,velocity,acceleration,drag,max){max=max||1e4;if(axis==1&&body.allowGravity){velocity+=(this.gravity.x+body.gravity.x)*this.game.time.physicsElapsed}else if(axis==2&&body.allowGravity){velocity+=(this.gravity.y+body.gravity.y)*this.game.time.physicsElapsed}if(acceleration){velocity+=acceleration*this.game.time.physicsElapsed}else if(drag){this._drag=drag*this.game.time.physicsElapsed;if(velocity-this._drag>0){velocity-=this._drag}else if(velocity+this._drag<0){velocity+=this._drag}else{velocity=0}}if(velocity>max){velocity=max}else if(velocity<-max){velocity=-max}return velocity},overlap:function(object1,object2,overlapCallback,processCallback,callbackContext){overlapCallback=overlapCallback||null;processCallback=processCallback||null;callbackContext=callbackContext||overlapCallback;this._result=false;this._total=0;if(Array.isArray(object2)){for(var i=0,len=object2.length;i0},collide:function(object1,object2,collideCallback,processCallback,callbackContext){collideCallback=collideCallback||null;processCallback=processCallback||null;callbackContext=callbackContext||collideCallback;this._result=false;this._total=0;if(Array.isArray(object2)){for(var i=0,len=object2.length;i0},collideHandler:function(object1,object2,collideCallback,processCallback,callbackContext,overlapOnly){if(typeof object2==="undefined"&&(object1.type===Phaser.GROUP||object1.type===Phaser.EMITTER)){this.collideGroupVsSelf(object1,collideCallback,processCallback,callbackContext,overlapOnly);return}if(object1&&object2&&object1.exists&&object2.exists){if(object1.type==Phaser.SPRITE||object1.type==Phaser.TILESPRITE){if(object2.type==Phaser.SPRITE||object2.type==Phaser.TILESPRITE){this.collideSpriteVsSprite(object1,object2,collideCallback,processCallback,callbackContext,overlapOnly)}else if(object2.type==Phaser.GROUP||object2.type==Phaser.EMITTER){this.collideSpriteVsGroup(object1,object2,collideCallback,processCallback,callbackContext,overlapOnly)}else if(object2.type==Phaser.TILEMAPLAYER){this.collideSpriteVsTilemapLayer(object1,object2,collideCallback,processCallback,callbackContext)}}else if(object1.type==Phaser.GROUP){if(object2.type==Phaser.SPRITE||object2.type==Phaser.TILESPRITE){this.collideSpriteVsGroup(object2,object1,collideCallback,processCallback,callbackContext,overlapOnly)}else if(object2.type==Phaser.GROUP||object2.type==Phaser.EMITTER){this.collideGroupVsGroup(object1,object2,collideCallback,processCallback,callbackContext,overlapOnly)}else if(object2.type==Phaser.TILEMAPLAYER){this.collideGroupVsTilemapLayer(object1,object2,collideCallback,processCallback,callbackContext)}}else if(object1.type==Phaser.TILEMAPLAYER){if(object2.type==Phaser.SPRITE||object2.type==Phaser.TILESPRITE){this.collideSpriteVsTilemapLayer(object2,object1,collideCallback,processCallback,callbackContext)}else if(object2.type==Phaser.GROUP||object2.type==Phaser.EMITTER){this.collideGroupVsTilemapLayer(object2,object1,collideCallback,processCallback,callbackContext)}}else if(object1.type==Phaser.EMITTER){if(object2.type==Phaser.SPRITE||object2.type==Phaser.TILESPRITE){this.collideSpriteVsGroup(object2,object1,collideCallback,processCallback,callbackContext,overlapOnly)}else if(object2.type==Phaser.GROUP||object2.type==Phaser.EMITTER){this.collideGroupVsGroup(object1,object2,collideCallback,processCallback,callbackContext,overlapOnly)}else if(object2.type==Phaser.TILEMAPLAYER){this.collideGroupVsTilemapLayer(object1,object2,collideCallback,processCallback,callbackContext)}}}},collideSpriteVsSprite:function(sprite1,sprite2,collideCallback,processCallback,callbackContext,overlapOnly){if(!sprite1.body||!sprite2.body){return false}if(this.separate(sprite1.body,sprite2.body,processCallback,callbackContext,overlapOnly)){if(collideCallback){collideCallback.call(callbackContext,sprite1,sprite2)}this._total++}return true},collideSpriteVsGroup:function(sprite,group,collideCallback,processCallback,callbackContext,overlapOnly){if(group.length===0||!sprite.body){return}this.quadTree.clear();this.quadTree.reset(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels);this.quadTree.populate(group);this._potentials=this.quadTree.retrieve(sprite);for(var i=0,len=this._potentials.length;i=body2.right){return false}if(body1.position.y>=body2.bottom){return false}return true},separateX:function(body1,body2,overlapOnly){if(body1.immovable&&body2.immovable){return false}this._overlap=0;if(this.intersects(body1,body2)){this._maxOverlap=body1.deltaAbsX()+body2.deltaAbsX()+this.OVERLAP_BIAS;if(body1.deltaX()===0&&body2.deltaX()===0){body1.embedded=true;body2.embedded=true}else if(body1.deltaX()>body2.deltaX()){this._overlap=body1.right-body2.x;if(this._overlap>this._maxOverlap||body1.checkCollision.right===false||body2.checkCollision.left===false){this._overlap=0}else{body1.touching.none=false;body1.touching.right=true;body2.touching.none=false;body2.touching.left=true}}else if(body1.deltaX()this._maxOverlap||body1.checkCollision.left===false||body2.checkCollision.right===false){this._overlap=0}else{body1.touching.none=false;body1.touching.left=true;body2.touching.none=false;body2.touching.right=true}}if(this._overlap!==0){body1.overlapX=this._overlap;body2.overlapX=this._overlap;if(overlapOnly||body1.customSeparateX||body2.customSeparateX){return true}this._velocity1=body1.velocity.x;this._velocity2=body2.velocity.x;if(!body1.immovable&&!body2.immovable){this._overlap*=.5;body1.x=body1.x-this._overlap;body2.x+=this._overlap;this._newVelocity1=Math.sqrt(this._velocity2*this._velocity2*body2.mass/body1.mass)*(this._velocity2>0?1:-1);this._newVelocity2=Math.sqrt(this._velocity1*this._velocity1*body1.mass/body2.mass)*(this._velocity1>0?1:-1);this._average=(this._newVelocity1+this._newVelocity2)*.5;this._newVelocity1-=this._average;this._newVelocity2-=this._average;body1.velocity.x=this._average+this._newVelocity1*body1.bounce.x;body2.velocity.x=this._average+this._newVelocity2*body2.bounce.x}else if(!body1.immovable){body1.x=body1.x-this._overlap;body1.velocity.x=this._velocity2-this._velocity1*body1.bounce.x}else if(!body2.immovable){body2.x+=this._overlap;body2.velocity.x=this._velocity1-this._velocity2*body2.bounce.x}return true}}return false},separateY:function(body1,body2,overlapOnly){if(body1.immovable&&body2.immovable){return false}this._overlap=0;if(this.intersects(body1,body2)){this._maxOverlap=body1.deltaAbsY()+body2.deltaAbsY()+this.OVERLAP_BIAS;if(body1.deltaY()===0&&body2.deltaY()===0){body1.embedded=true;body2.embedded=true}else if(body1.deltaY()>body2.deltaY()){this._overlap=body1.bottom-body2.y;if(this._overlap>this._maxOverlap||body1.checkCollision.down===false||body2.checkCollision.up===false){this._overlap=0}else{body1.touching.none=false;body1.touching.down=true;body2.touching.none=false;body2.touching.up=true}}else if(body1.deltaY()this._maxOverlap||body1.checkCollision.up===false||body2.checkCollision.down===false){this._overlap=0}else{body1.touching.none=false;body1.touching.up=true;body2.touching.none=false;body2.touching.down=true}}if(this._overlap!==0){body1.overlapY=this._overlap;body2.overlapY=this._overlap;if(overlapOnly||body1.customSeparateY||body2.customSeparateY){return true}this._velocity1=body1.velocity.y;this._velocity2=body2.velocity.y;if(!body1.immovable&&!body2.immovable){this._overlap*=.5;body1.y=body1.y-this._overlap;body2.y+=this._overlap;this._newVelocity1=Math.sqrt(this._velocity2*this._velocity2*body2.mass/body1.mass)*(this._velocity2>0?1:-1);this._newVelocity2=Math.sqrt(this._velocity1*this._velocity1*body1.mass/body2.mass)*(this._velocity1>0?1:-1);this._average=(this._newVelocity1+this._newVelocity2)*.5;this._newVelocity1-=this._average;this._newVelocity2-=this._average;body1.velocity.y=this._average+this._newVelocity1*body1.bounce.y;body2.velocity.y=this._average+this._newVelocity2*body2.bounce.y}else if(!body1.immovable){body1.y=body1.y-this._overlap;body1.velocity.y=this._velocity2-this._velocity1*body1.bounce.y;if(body2.moves){body1.x+=body2.x-body2.prev.x}}else if(!body2.immovable){body2.y+=this._overlap;body2.velocity.y=this._velocity1-this._velocity2*body2.bounce.y;if(body1.moves){body2.x+=body1.x-body1.prev.x}}return true}}return false},separateTile:function(i,body,tile){if(!tile.intersects(body.position.x,body.position.y,body.right,body.bottom)){return false}if(tile.collisionCallback&&!tile.collisionCallback.call(tile.collisionCallbackContext,body.sprite,tile)){return false}else if(tile.layer.callbacks[tile.index]&&!tile.layer.callbacks[tile.index].callback.call(tile.layer.callbacks[tile.index].callbackContext,body.sprite,tile)){return false}if(!tile.faceLeft&&!tile.faceRight&&!tile.faceTop&&!tile.faceBottom){return false}var ox=0;var oy=0;var minX=0;var minY=1;if(body.deltaAbsX()>body.deltaAbsY()){minX=-1}else if(body.deltaAbsX()0&&!body.blocked.right&&tile.collideLeft&&body.checkCollision.right){if(tile.faceLeft&&body.right>tile.left){ox=body.right-tile.left;if(ox>this.TILE_BIAS){ox=0}}}if(ox!==0){this.processTileSeparationX(body,ox)}return ox},tileCheckY:function(body,tile){var oy=0;if(body.deltaY()<0&&!body.blocked.up&&tile.collideDown&&body.checkCollision.up){if(tile.faceBottom&&body.y0&&!body.blocked.down&&tile.collideUp&&body.checkCollision.down){if(tile.faceTop&&body.bottom>tile.top){oy=body.bottom-tile.top;if(oy>this.TILE_BIAS){oy=0}}}if(oy!==0){this.processTileSeparationY(body,oy)}return oy},processTileSeparationX:function(body,x){if(x<0){body.blocked.left=true}else if(x>0){body.blocked.right=true}body.position.x-=x;if(body.bounce.x===0){body.velocity.x=0}else{body.velocity.x=-body.velocity.x*body.bounce.x}},processTileSeparationY:function(body,y){if(y<0){body.blocked.up=true}else if(y>0){body.blocked.down=true}body.position.y-=y;if(body.bounce.y===0){body.velocity.y=0}else{body.velocity.y=-body.velocity.y*body.bounce.y}},getObjectsUnderPointer:function(pointer,group,callback,callbackContext){if(group.length===0||!pointer.exists){return}this.quadTree.clear();this.quadTree.reset(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels);this.quadTree.populate(group);var rect=new Phaser.Rectangle(pointer.x,pointer.y,1,1);var output=[];this._potentials=this.quadTree.retrieve(rect);for(var i=0,len=this._potentials.length;i0){speed=this.distanceBetween(displayObject,destination)/(maxTime/1e3)}displayObject.body.velocity.x=Math.cos(this._angle)*speed;displayObject.body.velocity.y=Math.sin(this._angle)*speed;return this._angle},moveToPointer:function(displayObject,speed,pointer,maxTime){if(typeof speed==="undefined"){speed=60}pointer=pointer||this.game.input.activePointer;if(typeof maxTime==="undefined"){maxTime=0}this._angle=this.angleToPointer(displayObject,pointer);if(maxTime>0){speed=this.distanceToPointer(displayObject,pointer)/(maxTime/1e3)}displayObject.body.velocity.x=Math.cos(this._angle)*speed;displayObject.body.velocity.y=Math.sin(this._angle)*speed;return this._angle},moveToXY:function(displayObject,x,y,speed,maxTime){if(typeof speed==="undefined"){speed=60}if(typeof maxTime==="undefined"){maxTime=0}this._angle=Math.atan2(y-displayObject.y,x-displayObject.x);if(maxTime>0){speed=this.distanceToXY(displayObject,x,y)/(maxTime/1e3)}displayObject.body.velocity.x=Math.cos(this._angle)*speed;displayObject.body.velocity.y=Math.sin(this._angle)*speed;return this._angle},velocityFromAngle:function(angle,speed,point){if(typeof speed==="undefined"){speed=60}point=point||new Phaser.Point;return point.setTo(Math.cos(this.game.math.degToRad(angle))*speed,Math.sin(this.game.math.degToRad(angle))*speed)},velocityFromRotation:function(rotation,speed,point){if(typeof speed==="undefined"){speed=60}point=point||new Phaser.Point;return point.setTo(Math.cos(rotation)*speed,Math.sin(rotation)*speed)},accelerationFromRotation:function(rotation,speed,point){if(typeof speed==="undefined"){speed=60}point=point||new Phaser.Point;return point.setTo(Math.cos(rotation)*speed,Math.sin(rotation)*speed)},accelerateToObject:function(displayObject,destination,speed,xSpeedMax,ySpeedMax){if(typeof speed==="undefined"){speed=60}if(typeof xSpeedMax==="undefined"){xSpeedMax=1e3}if(typeof ySpeedMax==="undefined"){ySpeedMax=1e3}this._angle=this.angleBetween(displayObject,destination);displayObject.body.acceleration.setTo(Math.cos(this._angle)*speed,Math.sin(this._angle)*speed);displayObject.body.maxVelocity.setTo(xSpeedMax,ySpeedMax);return this._angle},accelerateToPointer:function(displayObject,pointer,speed,xSpeedMax,ySpeedMax){if(typeof speed==="undefined"){speed=60}if(typeof pointer==="undefined"){pointer=this.game.input.activePointer}if(typeof xSpeedMax==="undefined"){xSpeedMax=1e3}if(typeof ySpeedMax==="undefined"){ySpeedMax=1e3}this._angle=this.angleToPointer(displayObject,pointer);displayObject.body.acceleration.setTo(Math.cos(this._angle)*speed,Math.sin(this._angle)*speed);displayObject.body.maxVelocity.setTo(xSpeedMax,ySpeedMax);return this._angle},accelerateToXY:function(displayObject,x,y,speed,xSpeedMax,ySpeedMax){if(typeof speed==="undefined"){speed=60}if(typeof xSpeedMax==="undefined"){xSpeedMax=1e3}if(typeof ySpeedMax==="undefined"){ySpeedMax=1e3}this._angle=this.angleToXY(displayObject,x,y);displayObject.body.acceleration.setTo(Math.cos(this._angle)*speed,Math.sin(this._angle)*speed);displayObject.body.maxVelocity.setTo(xSpeedMax,ySpeedMax);return this._angle},distanceBetween:function(source,target){this._dx=source.x-target.x;this._dy=source.y-target.y;return Math.sqrt(this._dx*this._dx+this._dy*this._dy)},distanceToXY:function(displayObject,x,y){this._dx=displayObject.x-x;this._dy=displayObject.y-y;return Math.sqrt(this._dx*this._dx+this._dy*this._dy)},distanceToPointer:function(displayObject,pointer){pointer=pointer||this.game.input.activePointer;this._dx=displayObject.x-pointer.x;this._dy=displayObject.y-pointer.y;return Math.sqrt(this._dx*this._dx+this._dy*this._dy)},angleBetween:function(source,target){this._dx=target.x-source.x;this._dy=target.y-source.y;return Math.atan2(this._dy,this._dx)},angleToXY:function(displayObject,x,y){this._dx=x-displayObject.x;this._dy=y-displayObject.y;return Math.atan2(this._dy,this._dx)},angleToPointer:function(displayObject,pointer){pointer=pointer||this.game.input.activePointer;this._dx=pointer.worldX-displayObject.x;this._dy=pointer.worldY-displayObject.y;return Math.atan2(this._dy,this._dx)}};Phaser.Physics.Arcade.Body=function(sprite){this.sprite=sprite;this.game=sprite.game;this.type=Phaser.Physics.ARCADE;this.offset=new Phaser.Point;this.position=new Phaser.Point(sprite.x,sprite.y);this.prev=new Phaser.Point(this.position.x,this.position.y);this.allowRotation=true;this.rotation=sprite.rotation;this.preRotation=sprite.rotation;this.sourceWidth=sprite.texture.frame.width;this.sourceHeight=sprite.texture.frame.height;this.width=sprite.width;this.height=sprite.height;this.halfWidth=Math.abs(sprite.width/2);this.halfHeight=Math.abs(sprite.height/2);this.center=new Phaser.Point(sprite.x+this.halfWidth,sprite.y+this.halfHeight);this.velocity=new Phaser.Point;this.newVelocity=new Phaser.Point(0,0);this.deltaMax=new Phaser.Point(0,0);this.acceleration=new Phaser.Point;this.drag=new Phaser.Point;this.allowGravity=true;this.gravity=new Phaser.Point(0,0);this.bounce=new Phaser.Point;this.maxVelocity=new Phaser.Point(1e4,1e4);this.angularVelocity=0;this.angularAcceleration=0;this.angularDrag=0;this.maxAngular=1e3;this.mass=1;this.angle=0;this.speed=0;this.facing=Phaser.NONE;this.immovable=false;this.moves=true;this.customSeparateX=false;this.customSeparateY=false;this.overlapX=0;this.overlapY=0;this.embedded=false;this.collideWorldBounds=false;this.checkCollision={none:false,any:true,up:true,down:true,left:true,right:true};this.touching={none:true,up:false,down:false,left:false,right:false};this.wasTouching={none:true,up:false,down:false,left:false,right:false};this.blocked={up:false,down:false,left:false,right:false};this.tilePadding=new Phaser.Point;this.phase=0;this._reset=true;this._sx=sprite.scale.x;this._sy=sprite.scale.y;this._dx=0;this._dy=0};Phaser.Physics.Arcade.Body.prototype={updateBounds:function(){var asx=Math.abs(this.sprite.scale.x);var asy=Math.abs(this.sprite.scale.y);if(asx!==this._sx||asy!==this._sy){this.width=this.sourceWidth*asx;this.height=this.sourceHeight*asy;this.halfWidth=Math.floor(this.width/2);this.halfHeight=Math.floor(this.height/2);this._sx=asx;this._sy=asy;this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight);this._reset=true}},preUpdate:function(){this.phase=1;this.wasTouching.none=this.touching.none;this.wasTouching.up=this.touching.up;this.wasTouching.down=this.touching.down;this.wasTouching.left=this.touching.left;this.wasTouching.right=this.touching.right;this.touching.none=true;this.touching.up=false;this.touching.down=false;this.touching.left=false;this.touching.right=false;this.blocked.up=false;this.blocked.down=false;this.blocked.left=false;this.blocked.right=false;this.embedded=false;this.updateBounds();this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.width+this.offset.x;this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.height+this.offset.y;this.rotation=this.sprite.angle;this.preRotation=this.rotation;if(this._reset||this.sprite._cache[4]===1){this.prev.x=this.position.x;this.prev.y=this.position.y}if(this.moves){this.game.physics.arcade.updateMotion(this);this.newVelocity.set(this.velocity.x*this.game.time.physicsElapsed,this.velocity.y*this.game.time.physicsElapsed);this.position.x+=this.newVelocity.x;this.position.y+=this.newVelocity.y;if(this.position.x!==this.prev.x||this.position.y!==this.prev.y){this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y);this.angle=Math.atan2(this.velocity.y,this.velocity.x)}if(this.collideWorldBounds){this.checkWorldBounds()}}this._dx=this.deltaX();this._dy=this.deltaY();this._reset=false},postUpdate:function(){if(this.phase===2){return}this.phase=2;if(this.deltaX()<0){this.facing=Phaser.LEFT}else if(this.deltaX()>0){this.facing=Phaser.RIGHT}if(this.deltaY()<0){this.facing=Phaser.UP}else if(this.deltaY()>0){this.facing=Phaser.DOWN}if(this.moves){this._dx=this.deltaX();this._dy=this.deltaY();if(this.deltaMax.x!==0&&this._dx!==0){if(this._dx<0&&this._dx<-this.deltaMax.x){this._dx=-this.deltaMax.x}else if(this._dx>0&&this._dx>this.deltaMax.x){this._dx=this.deltaMax.x}}if(this.deltaMax.y!==0&&this._dy!==0){if(this._dy<0&&this._dy<-this.deltaMax.y){this._dy=-this.deltaMax.y}else if(this._dy>0&&this._dy>this.deltaMax.y){this._dy=this.deltaMax.y}}this.sprite.x+=this._dx;this.sprite.y+=this._dy}this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight);if(this.allowRotation){this.sprite.angle+=this.deltaZ()}this.prev.x=this.position.x;this.prev.y=this.position.y},destroy:function(){this.sprite=null},checkWorldBounds:function(){if(this.position.xthis.game.physics.arcade.bounds.right&&this.game.physics.arcade.checkCollision.right){this.position.x=this.game.physics.arcade.bounds.right-this.width;this.velocity.x*=-this.bounce.x;this.blocked.right=true}if(this.position.ythis.game.physics.arcade.bounds.bottom&&this.game.physics.arcade.checkCollision.down){this.position.y=this.game.physics.arcade.bounds.bottom-this.height;this.velocity.y*=-this.bounce.y;this.blocked.down=true}},setSize:function(width,height,offsetX,offsetY){offsetX=offsetX||this.offset.x;offsetY=offsetY||this.offset.y;this.sourceWidth=width;this.sourceHeight=height;this.width=this.sourceWidth*this._sx;this.height=this.sourceHeight*this._sy;this.halfWidth=Math.floor(this.width/2);this.halfHeight=Math.floor(this.height/2);this.offset.setTo(offsetX,offsetY);this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},reset:function(x,y){this.velocity.set(0);this.acceleration.set(0);this.angularVelocity=0;this.angularAcceleration=0;this.position.x=x-this.sprite.anchor.x*this.width+this.offset.x;this.position.y=y-this.sprite.anchor.y*this.height+this.offset.y;this.prev.x=this.position.x;this.prev.y=this.position.y;this.rotation=this.sprite.angle;this.preRotation=this.rotation;this._sx=this.sprite.scale.x;this._sy=this.sprite.scale.y;this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},hitTest:function(x,y){return Phaser.Rectangle.contains(this,x,y)},onFloor:function(){return this.blocked.down},onWall:function(){return this.blocked.left||this.blocked.right},deltaAbsX:function(){return this.deltaX()>0?this.deltaX():-this.deltaX()},deltaAbsY:function(){return this.deltaY()>0?this.deltaY():-this.deltaY()},deltaX:function(){return this.position.x-this.prev.x},deltaY:function(){return this.position.y-this.prev.y},deltaZ:function(){return this.rotation-this.preRotation}};Object.defineProperty(Phaser.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}});Object.defineProperty(Phaser.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}});Object.defineProperty(Phaser.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(value){this.position.x=value}});Object.defineProperty(Phaser.Physics.Arcade.Body.prototype,"y",{ get:function(){return this.position.y},set:function(value){this.position.y=value}});Phaser.Physics.Arcade.Body.render=function(context,body,filled,color){if(typeof filled==="undefined"){filled=true}color=color||"rgba(0,255,0,0.4)";if(filled){context.fillStyle=color;context.fillRect(body.position.x-body.game.camera.x,body.position.y-body.game.camera.y,body.width,body.height)}else{context.strokeStyle=color;context.strokeRect(body.position.x-body.game.camera.x,body.position.y-body.game.camera.y,body.width,body.height)}};Phaser.Physics.Arcade.Body.renderBodyInfo=function(debug,body){debug.line("x: "+body.x.toFixed(2),"y: "+body.y.toFixed(2),"width: "+body.width,"height: "+body.height);debug.line("velocity x: "+body.velocity.x.toFixed(2),"y: "+body.velocity.y.toFixed(2),"deltaX: "+body._dx.toFixed(2),"deltaY: "+body._dy.toFixed(2));debug.line("acceleration x: "+body.acceleration.x.toFixed(2),"y: "+body.acceleration.y.toFixed(2),"speed: "+body.speed.toFixed(2),"angle: "+body.angle.toFixed(2));debug.line("gravity x: "+body.gravity.x,"y: "+body.gravity.y,"bounce x: "+body.bounce.x.toFixed(2),"y: "+body.bounce.y.toFixed(2));debug.line("touching left: "+body.touching.left,"right: "+body.touching.right,"up: "+body.touching.up,"down: "+body.touching.down);debug.line("blocked left: "+body.blocked.left,"right: "+body.blocked.right,"up: "+body.blocked.up,"down: "+body.blocked.down)};Phaser.Physics.Arcade.Body.prototype.constructor=Phaser.Physics.Arcade.Body;Phaser.Particles=function(game){this.game=game;this.emitters={};this.ID=0};Phaser.Particles.prototype={add:function(emitter){this.emitters[emitter.name]=emitter;return emitter},remove:function(emitter){delete this.emitters[emitter.name]},update:function(){for(var key in this.emitters){if(this.emitters[key].exists){this.emitters[key].update()}}}};Phaser.Particles.prototype.constructor=Phaser.Particles;Phaser.Particles.Arcade={};Phaser.Particles.Arcade.Emitter=function(game,x,y,maxParticles){this.maxParticles=maxParticles||50;Phaser.Group.call(this,game);this.name="emitter"+this.game.particles.ID++;this.type=Phaser.EMITTER;this.width=1;this.height=1;this.minParticleSpeed=new Phaser.Point(-100,-100);this.maxParticleSpeed=new Phaser.Point(100,100);this.minParticleScale=1;this.maxParticleScale=1;this.scaleData=null;this.minRotation=-360;this.maxRotation=360;this.minParticleAlpha=1;this.maxParticleAlpha=1;this.alphaData=null;this.gravity=100;this.particleClass=Phaser.Particle;this.particleDrag=new Phaser.Point;this.angularDrag=0;this.frequency=100;this.lifespan=2e3;this.bounce=new Phaser.Point;this.on=false;this.particleAnchor=new Phaser.Point(.5,.5);this.blendMode=Phaser.blendModes.NORMAL;this.emitX=x;this.emitY=y;this.autoScale=false;this.autoAlpha=false;this.particleBringToTop=false;this.particleSendToBack=false;this._minParticleScale=new Phaser.Point(1,1);this._maxParticleScale=new Phaser.Point(1,1);this._quantity=0;this._timer=0;this._counter=0;this._explode=true;this._frames=null};Phaser.Particles.Arcade.Emitter.prototype=Object.create(Phaser.Group.prototype);Phaser.Particles.Arcade.Emitter.prototype.constructor=Phaser.Particles.Arcade.Emitter;Phaser.Particles.Arcade.Emitter.prototype.update=function(){if(this.on){if(this._explode){this._counter=0;do{this.emitParticle();this._counter++}while(this._counter=this._timer){this.emitParticle();this._counter++;if(this._quantity>0){if(this._counter>=this._quantity){this.on=false}}this._timer=this.game.time.now+this.frequency}}}var i=this.children.length;while(i--){if(this.children[i].exists){this.children[i].update()}}};Phaser.Particles.Arcade.Emitter.prototype.makeParticles=function(keys,frames,quantity,collide,collideWorldBounds){if(typeof frames==="undefined"){frames=0}if(typeof quantity==="undefined"){quantity=this.maxParticles}if(typeof collide==="undefined"){collide=false}if(typeof collideWorldBounds==="undefined"){collideWorldBounds=false}var particle;var i=0;var rndKey=keys;var rndFrame=frames;this._frames=frames;while(i1||this.height>1){particle.reset(this.game.rnd.integerInRange(this.left,this.right),this.game.rnd.integerInRange(this.top,this.bottom))}else{particle.reset(this.emitX,this.emitY)}particle.angle=0;particle.lifespan=this.lifespan;if(this.particleBringToTop){this.bringToTop(particle)}else if(this.particleSendToBack){this.sendToBack(particle)}if(this.autoScale){particle.setScaleData(this.scaleData)}else if(this.minParticleScale!==1||this.maxParticleScale!==1){particle.scale.set(this.game.rnd.realInRange(this.minParticleScale,this.maxParticleScale))}else if(this._minParticleScale.x!==this._maxParticleScale.x||this._minParticleScale.y!==this._maxParticleScale.y){particle.scale.set(this.game.rnd.realInRange(this._minParticleScale.x,this._maxParticleScale.x),this.game.rnd.realInRange(this._minParticleScale.y,this._maxParticleScale.y))}if(Array.isArray(this._frames==="object")){particle.frame=this.game.rnd.pick(this._frames)}else{particle.frame=this._frames}if(this.autoAlpha){particle.setAlphaData(this.alphaData)}else{particle.alpha=this.game.rnd.realInRange(this.minParticleAlpha,this.maxParticleAlpha)}particle.blendMode=this.blendMode;particle.body.updateBounds();particle.body.bounce.setTo(this.bounce.x,this.bounce.y);particle.body.velocity.x=this.game.rnd.integerInRange(this.minParticleSpeed.x,this.maxParticleSpeed.x);particle.body.velocity.y=this.game.rnd.integerInRange(this.minParticleSpeed.y,this.maxParticleSpeed.y);particle.body.angularVelocity=this.game.rnd.integerInRange(this.minRotation,this.maxRotation);particle.body.gravity.y=this.gravity;particle.body.drag.x=this.particleDrag.x;particle.body.drag.y=this.particleDrag.y;particle.body.angularDrag=this.angularDrag;particle.onEmit()};Phaser.Particles.Arcade.Emitter.prototype.setSize=function(width,height){this.width=width;this.height=height};Phaser.Particles.Arcade.Emitter.prototype.setXSpeed=function(min,max){min=min||0;max=max||0;this.minParticleSpeed.x=min;this.maxParticleSpeed.x=max};Phaser.Particles.Arcade.Emitter.prototype.setYSpeed=function(min,max){min=min||0;max=max||0;this.minParticleSpeed.y=min;this.maxParticleSpeed.y=max};Phaser.Particles.Arcade.Emitter.prototype.setRotation=function(min,max){min=min||0;max=max||0;this.minRotation=min;this.maxRotation=max};Phaser.Particles.Arcade.Emitter.prototype.setAlpha=function(min,max,rate,ease,yoyo){if(typeof min==="undefined"){min=1}if(typeof max==="undefined"){max=1}if(typeof rate==="undefined"){rate=0}if(typeof ease==="undefined"){ease=Phaser.Easing.Linear.None}if(typeof yoyo==="undefined"){yoyo=false}this.minParticleAlpha=min;this.maxParticleAlpha=max;this.autoAlpha=false;if(rate>0&&min!==max){var tweenData={v:min};var tween=this.game.make.tween(tweenData).to({v:max},rate,ease);tween.yoyo(yoyo);this.alphaData=tween.generateData(60);this.alphaData.reverse();this.autoAlpha=true}};Phaser.Particles.Arcade.Emitter.prototype.setScale=function(minX,maxX,minY,maxY,rate,ease,yoyo){if(typeof minX==="undefined"){minX=1}if(typeof maxX==="undefined"){maxX=1}if(typeof minY==="undefined"){minY=1}if(typeof maxY==="undefined"){maxY=1}if(typeof rate==="undefined"){rate=0}if(typeof ease==="undefined"){ease=Phaser.Easing.Linear.None}if(typeof yoyo==="undefined"){yoyo=false}this.minParticleScale=1;this.maxParticleScale=1;this._minParticleScale.set(minX,minY);this._maxParticleScale.set(maxX,maxY);this.autoScale=false;if(rate>0&&minX!==maxX||minY!==maxY){var tweenData={x:minX,y:minY};var tween=this.game.make.tween(tweenData).to({x:maxX,y:maxY},rate,ease);tween.yoyo(yoyo);this.scaleData=tween.generateData(60);this.scaleData.reverse();this.autoScale=true}};Phaser.Particles.Arcade.Emitter.prototype.at=function(object){if(object.center){this.emitX=object.center.x;this.emitY=object.center.y}else{this.emitX=object.world.x+object.anchor.x*object.width;this.emitY=object.world.y+object.anchor.y*object.height}};Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(value){this.emitX=value}});Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(value){this.emitY=value}});Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.width/2)}});Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.width/2)}});Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.height/2)}});Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.height/2)}});Phaser.Tile=function(layer,index,x,y,width,height){this.layer=layer;this.index=index;this.x=x;this.y=y;this.worldX=x*width;this.worldY=y*height;this.width=width;this.height=height;this.centerX=Math.abs(width/2);this.centerY=Math.abs(height/2);this.alpha=1;this.properties={};this.scanned=false;this.faceTop=false;this.faceBottom=false;this.faceLeft=false;this.faceRight=false;this.collideLeft=false;this.collideRight=false;this.collideUp=false;this.collideDown=false;this.collisionCallback=null;this.collisionCallbackContext=this};Phaser.Tile.prototype={containsPoint:function(x,y){return!(xthis.right||y>this.bottom)},intersects:function(x,y,right,bottom){if(right<=this.worldX){return false}if(bottom<=this.worldY){return false}if(x>=this.worldX+this.width){return false}if(y>=this.worldY+this.height){return false}return true},setCollisionCallback:function(callback,context){this.collisionCallback=callback;this.collisionCallbackContext=context},destroy:function(){this.collisionCallback=null;this.collisionCallbackContext=null;this.properties=null},setCollision:function(left,right,up,down){this.collideLeft=left;this.collideRight=right;this.collideUp=up;this.collideDown=down},resetCollision:function(){this.collideLeft=false;this.collideRight=false;this.collideUp=false;this.collideDown=false;this.faceTop=false;this.faceBottom=false;this.faceLeft=false;this.faceRight=false},isInteresting:function(collides,faces){if(collides&&faces){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback}else if(collides){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}else if(faces){return this.faceTop||this.faceBottom||this.faceLeft||this.faceRight}return false},copy:function(tile){this.index=tile.index;this.alpha=tile.alpha;this.properties=tile.properties;this.collideUp=tile.collideUp;this.collideDown=tile.collideDown;this.collideLeft=tile.collideLeft;this.collideRight=tile.collideRight;this.collisionCallback=tile.collisionCallback;this.collisionCallbackContext=tile.collisionCallbackContext}};Phaser.Tile.prototype.constructor=Phaser.Tile;Object.defineProperty(Phaser.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}});Object.defineProperty(Phaser.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}});Object.defineProperty(Phaser.Tile.prototype,"left",{get:function(){return this.worldX}});Object.defineProperty(Phaser.Tile.prototype,"right",{get:function(){return this.worldX+this.width}});Object.defineProperty(Phaser.Tile.prototype,"top",{get:function(){return this.worldY}});Object.defineProperty(Phaser.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}});Phaser.Tilemap=function(game,key,tileWidth,tileHeight,width,height){this.game=game;this.key=key;var data=Phaser.TilemapParser.parse(this.game,key,tileWidth,tileHeight,width,height);if(data===null){return}this.width=data.width;this.height=data.height;this.tileWidth=data.tileWidth;this.tileHeight=data.tileHeight;this.orientation=data.orientation;this.format=data.format;this.version=data.version;this.properties=data.properties;this.widthInPixels=data.widthInPixels;this.heightInPixels=data.heightInPixels;this.layers=data.layers;this.tilesets=data.tilesets;this.tiles=data.tiles;this.objects=data.objects;this.collideIndexes=[];this.collision=data.collision;this.images=data.images;this.currentLayer=0;this.debugMap=[];this._results=[];this._tempA=0;this._tempB=0};Phaser.Tilemap.CSV=0;Phaser.Tilemap.TILED_JSON=1;Phaser.Tilemap.NORTH=0;Phaser.Tilemap.EAST=1;Phaser.Tilemap.SOUTH=2;Phaser.Tilemap.WEST=3;Phaser.Tilemap.prototype={create:function(name,width,height,tileWidth,tileHeight,group){if(typeof group==="undefined"){group=this.game.world}this.width=width;this.height=height;this.setTileSize(tileWidth,tileHeight);this.layers.length=0;return this.createBlankLayer(name,width,height,tileWidth,tileHeight,group)},setTileSize:function(tileWidth,tileHeight){this.tileWidth=tileWidth;this.tileHeight=tileHeight;this.widthInPixels=this.width*tileWidth;this.heightInPixels=this.height*tileHeight},addTilesetImage:function(tileset,key,tileWidth,tileHeight,tileMargin,tileSpacing,gid){if(typeof tileWidth==="undefined"){tileWidth=this.tileWidth}if(typeof tileHeight==="undefined"){tileHeight=this.tileHeight}if(typeof tileMargin==="undefined"){tileMargin=0}if(typeof tileSpacing==="undefined"){tileSpacing=0}if(typeof gid==="undefined"){gid=0}if(tileWidth===0){tileWidth=32}if(tileHeight===0){tileHeight=32}if(typeof key==="undefined"){if(typeof tileset==="string"){key=tileset;if(!this.game.cache.checkImageKey(key)){console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+key+'"');return null}}else{return null}}if(typeof tileset==="string"){tileset=this.getTilesetIndex(tileset);if(tileset===null&&this.format===Phaser.Tilemap.TILED_JSON){console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+key+'"');return null}}if(this.tilesets[tileset]){this.tilesets[tileset].setImage(this.game.cache.getImage(key));return this.tilesets[tileset]}else{var newSet=new Phaser.Tileset(key,gid,tileWidth,tileHeight,tileMargin,tileSpacing,{});newSet.setImage(this.game.cache.getImage(key));this.tilesets.push(newSet);var i=this.tilesets.length-1;var x=tileMargin;var y=tileMargin;var count=0;var countX=0;var countY=0;for(var t=gid;tthis.layers.length){console.warn("Tilemap.createLayer: Invalid layer ID given: "+index);return}return group.add(new Phaser.TilemapLayer(this.game,this,index,width,height))},createBlankLayer:function(name,width,height,tileWidth,tileHeight,group){if(typeof group==="undefined"){group=this.game.world}if(this.getLayerIndex(name)!==null){console.warn("Tilemap.createBlankLayer: Layer with matching name already exists");return}var layer={name:name,x:0,y:0,width:width,height:height,widthInPixels:width*tileWidth,heightInPixels:height*tileHeight,alpha:1,visible:true,properties:{},indexes:[],callbacks:[],bodies:[],data:null};var row;var output=[];for(var y=0;ythis.game.width){w=this.game.width}if(h>this.game.height){h=this.game.height}var output=new Phaser.TilemapLayer(this.game,this,this.layers.length-1,w,h);output.name=name;return group.add(output)},getIndex:function(location,name){for(var i=0;istop){return}for(var index=start;index<=stop;index++){this.setCollisionByIndex(index,collides,layer,false)}if(recalculate){this.calculateFaces(layer)}},setCollisionByExclusion:function(indexes,collides,layer,recalculate){if(typeof collides==="undefined"){collides=true}if(typeof recalculate==="undefined"){recalculate=true}layer=this.getLayer(layer);for(var i=0,len=this.tiles.length;i-1){this.collideIndexes.splice(i,1)}}for(var y=0;y0){return this.layers[layer].data[y-1][x]}return null},getTileBelow:function(layer,x,y){if(y0){return this.layers[layer].data[y][x-1]}return null},getTileRight:function(layer,x,y){if(x=0&&x=0&&y=0&&x=0&&y-1){this.layers[layer].data[y][x].setCollision(true,true,true,true)}else{this.layers[layer].data[y][x].resetCollision()}this.layers[layer].dirty=true;this.calculateFaces(layer);return this.layers[layer].data[y][x]}return null},putTileWorldXY:function(tile,x,y,tileWidth,tileHeight,layer){layer=this.getLayer(layer);x=this.game.math.snapToFloor(x,tileWidth)/tileWidth;y=this.game.math.snapToFloor(y,tileHeight)/tileHeight;return this.putTile(tile,x,y,layer)},searchTileIndex:function(index,skip,reverse,layer){if(typeof skip==="undefined"){skip=0}if(typeof reverse==="undefined"){reverse=false}layer=this.getLayer(layer);var c=0;if(reverse){for(var y=this.layers[layer].height-1;y>=0;y--){for(var x=this.layers[layer].width-1;x>=0;x--){if(this.layers[layer].data[y][x].index===index){if(c===skip){return this.layers[layer].data[y][x]}else{c++}}}}}else{for(var y=0;y=0&&x=0&&ythis.layers[layer].width){width=this.layers[layer].width}if(height>this.layers[layer].height){height=this.layers[layer].height}this._results.length=0;this._results.push({x:x,y:y,width:width,height:height,layer:layer});for(var ty=y;ty1){if(this.debugMap[this.layers[this.currentLayer].data[y][x]]){args.push("background: "+this.debugMap[this.layers[this.currentLayer].data[y][x]])}else{args.push("background: #ffffff")}}else{args.push("background: rgb(0, 0, 0)")}}txt+="\n"}args[0]=txt;console.log.apply(console,args)},destroy:function(){this.removeAllLayers();this.data=[];this.game=null}};Phaser.Tilemap.prototype.constructor=Phaser.Tilemap;Object.defineProperty(Phaser.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(value){if(value!==this.currentLayer){this.setLayer(value)}}});Phaser.TilemapLayer=function(game,tilemap,index,width,height){this.game=game;this.map=tilemap;this.index=index;this.layer=tilemap.layers[index];this.canvas=Phaser.Canvas.create(width,height,"",true);this.context=this.canvas.getContext("2d");this.baseTexture=new PIXI.BaseTexture(this.canvas);this.texture=new PIXI.Texture(this.baseTexture);this.textureFrame=new Phaser.Frame(0,0,0,width,height,"tilemapLayer",game.rnd.uuid());Phaser.Image.call(this,this.game,0,0,this.texture,this.textureFrame);this.name="";this.type=Phaser.TILEMAPLAYER;this.fixedToCamera=true;this.cameraOffset=new Phaser.Point(0,0);this.tileColor="rgb(255, 255, 255)";this.debug=false;this.debugAlpha=.5;this.debugColor="rgba(0, 255, 0, 1)";this.debugFill=false;this.debugFillColor="rgba(0, 255, 0, 0.2)";this.debugCallbackColor="rgba(255, 0, 0, 1)";this.scrollFactorX=1;this.scrollFactorY=1;this.dirty=true;this.rayStepRate=4;this._mc={cw:tilemap.tileWidth,ch:tilemap.tileHeight,ga:1,dx:0,dy:0,dw:0,dh:0,tx:0,ty:0,tw:0,th:0,tl:0,maxX:0,maxY:0,startX:0,startY:0,x:0,y:0,prevX:0,prevY:0};this._results=[];this.updateMax()};Phaser.TilemapLayer.prototype=Object.create(Phaser.Image.prototype);Phaser.TilemapLayer.prototype.constructor=Phaser.TilemapLayer;Phaser.TilemapLayer.prototype.postUpdate=function(){Phaser.Image.prototype.postUpdate.call(this);this.scrollX=this.game.camera.x*this.scrollFactorX;this.scrollY=this.game.camera.y*this.scrollFactorY;this.render();if(this._cache[7]===1){this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x;this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y}};Phaser.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels,this.layer.heightInPixels)};Phaser.TilemapLayer.prototype._fixX=function(x){if(x<0){x=0}if(this.scrollFactorX===1){return x}return this._mc.x+(x-this._mc.x/this.scrollFactorX)};Phaser.TilemapLayer.prototype._unfixX=function(x){if(this.scrollFactorX===1){return x}return this._mc.x/this.scrollFactorX+(x-this._mc.x)};Phaser.TilemapLayer.prototype._fixY=function(y){if(y<0){y=0}if(this.scrollFactorY===1){return y}return this._mc.y+(y-this._mc.y/this.scrollFactorY); };Phaser.TilemapLayer.prototype._unfixY=function(y){if(this.scrollFactorY===1){return y}return this._mc.y/this.scrollFactorY+(y-this._mc.y)};Phaser.TilemapLayer.prototype.getTileX=function(x){return this.game.math.snapToFloor(this._fixX(x),this.map.tileWidth)/this.map.tileWidth};Phaser.TilemapLayer.prototype.getTileY=function(y){return this.game.math.snapToFloor(this._fixY(y),this.map.tileHeight)/this.map.tileHeight};Phaser.TilemapLayer.prototype.getTileXY=function(x,y,point){point.x=this.getTileX(x);point.y=this.getTileY(y);return point};Phaser.TilemapLayer.prototype.getRayCastTiles=function(line,stepRate,collides,interestingFace){if(typeof stepRate==="undefined"||stepRate===null){stepRate=this.rayStepRate}if(typeof collides==="undefined"){collides=false}if(typeof interestingFace==="undefined"){interestingFace=false}var tiles=this.getTiles(line.x,line.y,line.width,line.height,collides,interestingFace);if(tiles.length===0){return[]}var coords=line.coordinatesOnLine(stepRate);var total=coords.length;var results=[];for(var i=0;ithis.layer.widthInPixels){width=this.layer.widthInPixels}if(height>this.layer.heightInPixels){height=this.layer.heightInPixels}this._mc.tx=this.game.math.snapToFloor(x,this._mc.cw)/this._mc.cw;this._mc.ty=this.game.math.snapToFloor(y,this._mc.ch)/this._mc.ch;this._mc.tw=(this.game.math.snapToCeil(width,this._mc.cw)+this._mc.cw)/this._mc.cw;this._mc.th=(this.game.math.snapToCeil(height,this._mc.ch)+this._mc.ch)/this._mc.ch;this._results.length=0;for(var wy=this._mc.ty;wythis.layer.width){this._mc.maxX=this.layer.width}if(this._mc.maxY>this.layer.height){this._mc.maxY=this.layer.height}}this.dirty=true};Phaser.TilemapLayer.prototype.render=function(){if(this.layer.dirty){this.dirty=true}if(!this.dirty||!this.visible){return}this._mc.prevX=this._mc.dx;this._mc.prevY=this._mc.dy;this._mc.dx=-(this._mc.x-this._mc.startX*this.map.tileWidth);this._mc.dy=-(this._mc.y-this._mc.startY*this.map.tileHeight);this._mc.tx=this._mc.dx;this._mc.ty=this._mc.dy;this.context.clearRect(0,0,this.canvas.width,this.canvas.height);this.context.fillStyle=this.tileColor;var tile;var set;if(this.debug){this.context.globalAlpha=this.debugAlpha}for(var y=this._mc.startY,lenY=this._mc.startY+this._mc.maxY;y-1){set=this.map.tilesets[this.map.tiles[tile.index][2]];if(this.debug===false&&tile.alpha!==this.context.globalAlpha){this.context.globalAlpha=tile.alpha}set.draw(this.context,Math.floor(this._mc.tx),Math.floor(this._mc.ty),tile.index);if(tile.debug){this.context.fillStyle="rgba(0, 255, 0, 0.4)";this.context.fillRect(Math.floor(this._mc.tx),Math.floor(this._mc.ty),this.map.tileWidth,this.map.tileHeight)}}}this._mc.tx+=this.map.tileWidth}this._mc.tx=this._mc.dx;this._mc.ty+=this.map.tileHeight}if(this.debug){this.context.globalAlpha=1;this.renderDebug()}if(this.game.renderType===Phaser.WEBGL){PIXI.updateWebGLTexture(this.baseTexture,this.game.renderer.gl)}this.dirty=false;this.layer.dirty=false;return true};Phaser.TilemapLayer.prototype.renderDebug=function(){this._mc.tx=this._mc.dx;this._mc.ty=this._mc.dy;this.context.strokeStyle=this.debugColor;this.context.fillStyle=this.debugFillColor;for(var y=this._mc.startY,lenY=this._mc.startY+this._mc.maxY;y=0&&this.layer.widthInPixels>this.width){this._mc.x=value;if(this._mc.x>this.layer.widthInPixels-this.width){this._mc.x=this.layer.widthInPixels-this.width}this._mc.startX=this.game.math.floor(this._mc.x/this.map.tileWidth);if(this._mc.startX<0){this._mc.startX=0}if(this._mc.startX+this._mc.maxX>this.layer.width){this._mc.startX=this.layer.width-this._mc.maxX}this.dirty=true}}});Object.defineProperty(Phaser.TilemapLayer.prototype,"scrollY",{get:function(){return this._mc.y},set:function(value){if(value!==this._mc.y&&value>=0&&this.layer.heightInPixels>this.height){this._mc.y=value;if(this._mc.y>this.layer.heightInPixels-this.height){this._mc.y=this.layer.heightInPixels-this.height}this._mc.startY=this.game.math.floor(this._mc.y/this.map.tileHeight);if(this._mc.startY<0){this._mc.startY=0}if(this._mc.startY+this._mc.maxY>this.layer.height){this._mc.startY=this.layer.height-this._mc.maxY}this.dirty=true}}});Object.defineProperty(Phaser.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(value){this._mc.cw=value;this.dirty=true}});Object.defineProperty(Phaser.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(value){this._mc.ch=value;this.dirty=true}});Phaser.TilemapParser={parse:function(game,key,tileWidth,tileHeight,width,height){if(typeof tileWidth==="undefined"){tileWidth=32}if(typeof tileHeight==="undefined"){tileHeight=32}if(typeof width==="undefined"){width=10}if(typeof height==="undefined"){height=10}if(typeof key==="undefined"){return this.getEmptyData()}if(key===null){return this.getEmptyData(tileWidth,tileHeight,width,height)}var map=game.cache.getTilemapData(key);if(map){if(map.format===Phaser.Tilemap.CSV){return this.parseCSV(key,map.data,tileWidth,tileHeight)}else if(!map.format||map.format===Phaser.Tilemap.TILED_JSON){return this.parseTiledJSON(map.data)}}else{console.warn("Phaser.TilemapParser.parse - No map data found for key "+key)}},parseCSV:function(key,data,tileWidth,tileHeight){var map=this.getEmptyData();data=data.trim();var output=[];var rows=data.split("\n");var height=rows.length;var width=0;for(var y=0;y0){row.push(new Phaser.Tile(layer,json.layers[i].data[t],x,output.length,json.tilewidth,json.tileheight))}else{row.push(new Phaser.Tile(layer,-1,x,output.length,json.tilewidth,json.tileheight))}x++;if(x===json.layers[i].width){output.push(row);x=0;row=[]}}layer.data=output;layers.push(layer)}map.layers=layers;var images=[];for(var i=0;i0){this.enable(object[i],type,id,radius,true)}}}}else{if(object instanceof Phaser.Group){this.enable(object.children,type,id,radius,children)}else{this.enableBody(object,type,id,radius);if(children&&object.hasOwnProperty("children")&&object.children.length>0){this.enable(object.children,type,id,radius,true)}}}},enableBody:function(object,type,id,radius){if(object.hasOwnProperty("body")&&object.body===null){object.body=new Phaser.Physics.Ninja.Body(this,object,type,id,radius);object.anchor.set(.5)}},setBounds:function(x,y,width,height){this.bounds.setTo(x,y,width,height)},setBoundsToWorld:function(){this.bounds.setTo(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height)},clearTilemapLayerBodies:function(map,layer){layer=map.getLayer(layer);var i=map.layers[layer].bodies.length;while(i--){map.layers[layer].bodies[i].destroy()}map.layers[layer].bodies.length=[]},convertTilemap:function(map,layer,slopeMap){layer=map.getLayer(layer);this.clearTilemapLayerBodies(map,layer);for(var y=0,h=map.layers[layer].height;y0},collide:function(object1,object2,collideCallback,processCallback,callbackContext){collideCallback=collideCallback||null;processCallback=processCallback||null;callbackContext=callbackContext||collideCallback;this._result=false;this._total=0;if(Array.isArray(object2)){for(var i=0,len=object2.length;i0},collideHandler:function(object1,object2,collideCallback,processCallback,callbackContext,overlapOnly){if(typeof object2==="undefined"&&(object1.type===Phaser.GROUP||object1.type===Phaser.EMITTER)){this.collideGroupVsSelf(object1,collideCallback,processCallback,callbackContext,overlapOnly);return}if(object1&&object2&&object1.exists&&object2.exists){if(object1.type==Phaser.SPRITE||object1.type==Phaser.TILESPRITE){if(object2.type==Phaser.SPRITE||object2.type==Phaser.TILESPRITE){this.collideSpriteVsSprite(object1,object2,collideCallback,processCallback,callbackContext,overlapOnly)}else if(object2.type==Phaser.GROUP||object2.type==Phaser.EMITTER){this.collideSpriteVsGroup(object1,object2,collideCallback,processCallback,callbackContext,overlapOnly)}else if(object2.type==Phaser.TILEMAPLAYER){this.collideSpriteVsTilemapLayer(object1,object2,collideCallback,processCallback,callbackContext)}}else if(object1.type==Phaser.GROUP){if(object2.type==Phaser.SPRITE||object2.type==Phaser.TILESPRITE){this.collideSpriteVsGroup(object2,object1,collideCallback,processCallback,callbackContext,overlapOnly)}else if(object2.type==Phaser.GROUP||object2.type==Phaser.EMITTER){this.collideGroupVsGroup(object1,object2,collideCallback,processCallback,callbackContext,overlapOnly)}else if(object2.type==Phaser.TILEMAPLAYER){this.collideGroupVsTilemapLayer(object1,object2,collideCallback,processCallback,callbackContext)}}else if(object1.type==Phaser.TILEMAPLAYER){if(object2.type==Phaser.SPRITE||object2.type==Phaser.TILESPRITE){this.collideSpriteVsTilemapLayer(object2,object1,collideCallback,processCallback,callbackContext)}else if(object2.type==Phaser.GROUP||object2.type==Phaser.EMITTER){this.collideGroupVsTilemapLayer(object2,object1,collideCallback,processCallback,callbackContext)}}else if(object1.type==Phaser.EMITTER){if(object2.type==Phaser.SPRITE||object2.type==Phaser.TILESPRITE){this.collideSpriteVsGroup(object2,object1,collideCallback,processCallback,callbackContext,overlapOnly)}else if(object2.type==Phaser.GROUP||object2.type==Phaser.EMITTER){this.collideGroupVsGroup(object1,object2,collideCallback,processCallback,callbackContext,overlapOnly)}else if(object2.type==Phaser.TILEMAPLAYER){this.collideGroupVsTilemapLayer(object1,object2,collideCallback,processCallback,callbackContext)}}}},collideSpriteVsSprite:function(sprite1,sprite2,collideCallback,processCallback,callbackContext,overlapOnly){if(this.separate(sprite1.body,sprite2.body,processCallback,callbackContext,overlapOnly)){if(collideCallback){collideCallback.call(callbackContext,sprite1,sprite2)}this._total++}},collideSpriteVsGroup:function(sprite,group,collideCallback,processCallback,callbackContext,overlapOnly){if(group.length===0){return}for(var i=0,len=group.children.length;i0){this.facing=Phaser.RIGHT}if(this.velocity.y<0){this.facing=Phaser.UP}else if(this.velocity.y>0){this.facing=Phaser.DOWN}},setZeroVelocity:function(){this.shape.oldpos.x=this.shape.pos.x;this.shape.oldpos.y=this.shape.pos.y},moveTo:function(speed,angle){var magnitude=speed*this.game.time.physicsElapsed;var angle=this.game.math.degToRad(angle);this.shape.pos.x=this.shape.oldpos.x+magnitude*Math.cos(angle);this.shape.pos.y=this.shape.oldpos.y+magnitude*Math.sin(angle)},moveFrom:function(speed,angle){var magnitude=-speed*this.game.time.physicsElapsed;var angle=this.game.math.degToRad(angle);this.shape.pos.x=this.shape.oldpos.x+magnitude*Math.cos(angle);this.shape.pos.y=this.shape.oldpos.y+magnitude*Math.sin(angle)},moveLeft:function(speed){var fx=-speed*this.game.time.physicsElapsed;this.shape.pos.x=this.shape.oldpos.x+Math.min(this.maxSpeed,Math.max(-this.maxSpeed,this.shape.pos.x-this.shape.oldpos.x+fx))},moveRight:function(speed){var fx=speed*this.game.time.physicsElapsed;this.shape.pos.x=this.shape.oldpos.x+Math.min(this.maxSpeed,Math.max(-this.maxSpeed,this.shape.pos.x-this.shape.oldpos.x+fx))},moveUp:function(speed){var fx=-speed*this.game.time.physicsElapsed;this.shape.pos.y=this.shape.oldpos.y+Math.min(this.maxSpeed,Math.max(-this.maxSpeed,this.shape.pos.y-this.shape.oldpos.y+fx))},moveDown:function(speed){var fx=speed*this.game.time.physicsElapsed;this.shape.pos.y=this.shape.oldpos.y+Math.min(this.maxSpeed,Math.max(-this.maxSpeed,this.shape.pos.y-this.shape.oldpos.y+fx))},reset:function(){this.velocity.set(0);this.shape.pos.x=this.sprite.x;this.shape.pos.y=this.sprite.y;this.shape.oldpos.copyFrom(this.shape.pos)},deltaAbsX:function(){return this.deltaX()>0?this.deltaX():-this.deltaX()},deltaAbsY:function(){return this.deltaY()>0?this.deltaY():-this.deltaY()},deltaX:function(){return this.shape.pos.x-this.shape.oldpos.x},deltaY:function(){return this.shape.pos.y-this.shape.oldpos.y},destroy:function(){this.sprite=null;this.system=null;this.aabb=null;this.tile=null;this.circle=null;this.shape.destroy();this.shape=null}};Object.defineProperty(Phaser.Physics.Ninja.Body.prototype,"x",{get:function(){return this.shape.pos.x},set:function(value){this.shape.pos.x=value}});Object.defineProperty(Phaser.Physics.Ninja.Body.prototype,"y",{get:function(){return this.shape.pos.y},set:function(value){this.shape.pos.y=value}});Object.defineProperty(Phaser.Physics.Ninja.Body.prototype,"width",{get:function(){return this.shape.width}});Object.defineProperty(Phaser.Physics.Ninja.Body.prototype,"height",{get:function(){return this.shape.height}});Object.defineProperty(Phaser.Physics.Ninja.Body.prototype,"bottom",{get:function(){return this.shape.pos.y+this.shape.yw}});Object.defineProperty(Phaser.Physics.Ninja.Body.prototype,"right",{get:function(){return this.shape.pos.x+this.shape.xw}});Object.defineProperty(Phaser.Physics.Ninja.Body.prototype,"speed",{get:function(){return Math.sqrt(this.shape.velocity.x*this.shape.velocity.x+this.shape.velocity.y*this.shape.velocity.y)}});Object.defineProperty(Phaser.Physics.Ninja.Body.prototype,"angle",{get:function(){return Math.atan2(this.shape.velocity.y,this.shape.velocity.x)}});Phaser.Physics.Ninja.AABB=function(body,x,y,width,height){this.body=body;this.system=body.system;this.pos=new Phaser.Point(x,y);this.oldpos=new Phaser.Point(x,y);this.xw=Math.abs(width/2);this.yw=Math.abs(height/2);this.width=width;this.height=height;this.oH=0;this.oV=0;this.velocity=new Phaser.Point;this.aabbTileProjections={};this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_FULL]=this.projAABB_Full;this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_45DEG]=this.projAABB_45Deg;this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_CONCAVE]=this.projAABB_Concave;this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_CONVEX]=this.projAABB_Convex;this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_22DEGs]=this.projAABB_22DegS;this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_22DEGb]=this.projAABB_22DegB;this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_67DEGs]=this.projAABB_67DegS;this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_67DEGb]=this.projAABB_67DegB;this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_HALF]=this.projAABB_Half};Phaser.Physics.Ninja.AABB.prototype.constructor=Phaser.Physics.Ninja.AABB;Phaser.Physics.Ninja.AABB.COL_NONE=0;Phaser.Physics.Ninja.AABB.COL_AXIS=1;Phaser.Physics.Ninja.AABB.COL_OTHER=2;Phaser.Physics.Ninja.AABB.prototype={integrate:function(){var px=this.pos.x;var py=this.pos.y;this.pos.x+=this.body.drag*this.pos.x-this.body.drag*this.oldpos.x;this.pos.y+=this.body.drag*this.pos.y-this.body.drag*this.oldpos.y+this.system.gravity*this.body.gravityScale;this.velocity.set(this.pos.x-px,this.pos.y-py);this.oldpos.set(px,py)},reportCollisionVsWorld:function(px,py,dx,dy){var p=this.pos;var o=this.oldpos;var vx=p.x-o.x;var vy=p.y-o.y;var dp=vx*dx+vy*dy;var nx=dp*dx;var ny=dp*dy;var tx=vx-nx;var ty=vy-ny;var b,bx,by,fx,fy;if(dp<0){fx=tx*this.body.friction;fy=ty*this.body.friction;b=1+this.body.bounce;bx=nx*b;by=ny*b;if(dx===1){this.body.touching.left=true}else if(dx===-1){this.body.touching.right=true}if(dy===1){this.body.touching.up=true}else if(dy===-1){this.body.touching.down=true}}else{bx=by=fx=fy=0}p.x+=px;p.y+=py;o.x+=px+bx+fx;o.y+=py+by+fy},reverse:function(){var vx=this.pos.x-this.oldpos.x;var vy=this.pos.y-this.oldpos.y;if(this.oldpos.xthis.pos.x){this.oldpos.x=this.pos.x-vx}if(this.oldpos.ythis.pos.y){this.oldpos.y=this.pos.y-vy}},reportCollisionVsBody:function(px,py,dx,dy,obj){var vx1=this.pos.x-this.oldpos.x;var vy1=this.pos.y-this.oldpos.y;var dp1=vx1*dx+vy1*dy;if(this.body.immovable&&obj.body.immovable){px*=.5;py*=.5;this.pos.add(px,py);this.oldpos.set(this.pos.x,this.pos.y);obj.pos.subtract(px,py);obj.oldpos.set(obj.pos.x,obj.pos.y);return}else if(!this.body.immovable&&!obj.body.immovable){px*=.5;py*=.5;this.pos.add(px,py);obj.pos.subtract(px,py);if(dp1<0){this.reverse();obj.reverse()}}else if(!this.body.immovable){this.pos.subtract(px,py);if(dp1<0){this.reverse()}}else if(!obj.body.immovable){obj.pos.subtract(px,py);if(dp1<0){obj.reverse()}}},collideWorldBounds:function(){var dx=this.system.bounds.x-(this.pos.x-this.xw); if(01&&this.id<30){height=width}this.xw=Math.abs(width/2);this.yw=Math.abs(height/2);this.width=width;this.height=height;this.velocity=new Phaser.Point;this.signx=0;this.signy=0;this.sx=0;this.sy=0;this.body.gravityScale=0;this.body.collideWorldBounds=false;if(this.id>0){this.setType(this.id)}};Phaser.Physics.Ninja.Tile.prototype.constructor=Phaser.Physics.Ninja.Tile;Phaser.Physics.Ninja.Tile.prototype={integrate:function(){var px=this.pos.x;var py=this.pos.y;this.pos.x+=this.body.drag*this.pos.x-this.body.drag*this.oldpos.x;this.pos.y+=this.body.drag*this.pos.y-this.body.drag*this.oldpos.y+this.system.gravity*this.body.gravityScale;this.velocity.set(this.pos.x-px,this.pos.y-py);this.oldpos.set(px,py)},collideWorldBounds:function(){var dx=this.system.bounds.x-(this.pos.x-this.xw);if(00){len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len}return out};vec2.dot=function(a,b){return a[0]*b[0]+a[1]*b[1]};vec2.cross=function(out,a,b){var z=a[0]*b[1]-a[1]*b[0];out[0]=out[1]=0;out[2]=z;return out};vec2.lerp=function(out,a,b,t){var ax=a[0],ay=a[1];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);return out};vec2.transformMat2=function(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[2]*y;out[1]=m[1]*x+m[3]*y;return out};vec2.transformMat2d=function(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[2]*y+m[4];out[1]=m[1]*x+m[3]*y+m[5];return out};vec2.transformMat3=function(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[3]*y+m[6];out[1]=m[1]*x+m[4]*y+m[7];return out};vec2.transformMat4=function(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[4]*y+m[12];out[1]=m[1]*x+m[5]*y+m[13];return out};vec2.forEach=function(){var vec=vec2.create();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=2}if(!offset){offset=0}if(count){l=Math.min(count*stride+offset,a.length)}else{l=a.length}for(i=offset;i=0&&s<=1&&t>=0&&t<=1}},{"./Scalar":5}],3:[function(require,module,exports){module.exports=Point;function Point(){}Point.area=function(a,b,c){return(b[0]-a[0])*(c[1]-a[1])-(c[0]-a[0])*(b[1]-a[1])};Point.left=function(a,b,c){return Point.area(a,b,c)>0};Point.leftOn=function(a,b,c){return Point.area(a,b,c)>=0};Point.right=function(a,b,c){return Point.area(a,b,c)<0};Point.rightOn=function(a,b,c){return Point.area(a,b,c)<=0};var tmpPoint1=[],tmpPoint2=[];Point.collinear=function(a,b,c,thresholdAngle){if(!thresholdAngle)return Point.area(a,b,c)==0;else{var ab=tmpPoint1,bc=tmpPoint2;ab[0]=b[0]-a[0];ab[1]=b[1]-a[1];bc[0]=c[0]-b[0];bc[1]=c[1]-b[1];var dot=ab[0]*bc[0]+ab[1]*bc[1],magA=Math.sqrt(ab[0]*ab[0]+ab[1]*ab[1]),magB=Math.sqrt(bc[0]*bc[0]+bc[1]*bc[1]),angle=Math.acos(dot/(magA*magB));return anglepoly.vertices.length)throw new Error("lol2");if(from<0)throw new Error("lol3");for(var i=from;iv[br][0]){br=i}}if(!Point.left(this.at(br-1),this.at(br),this.at(br+1))){this.reverse()}};Polygon.prototype.reverse=function(){var tmp=[];for(var i=0,N=this.vertices.length;i!==N;i++){tmp.push(this.vertices.pop())}this.vertices=tmp};Polygon.prototype.isReflex=function(i){return Point.right(this.at(i-1),this.at(i),this.at(i+1))};var tmpLine1=[],tmpLine2=[];Polygon.prototype.canSee=function(a,b){var p,dist,l1=tmpLine1,l2=tmpLine2;if(Point.leftOn(this.at(a+1),this.at(a),this.at(b))&&Point.rightOn(this.at(a-1),this.at(a),this.at(b))){return false}dist=Point.sqdist(this.at(a),this.at(b));for(var i=0;i!==this.vertices.length;++i){if((i+1)%this.vertices.length===a||i===a)continue;if(Point.leftOn(this.at(a),this.at(b),this.at(i+1))&&Point.rightOn(this.at(a),this.at(b),this.at(i))){l1[0]=this.at(a);l1[1]=this.at(b);l2[0]=this.at(i);l2[1]=this.at(i+1);p=Line.lineInt(l1,l2);if(Point.sqdist(this.at(a),p)0)return this.slice(edges);else return[this]};Polygon.prototype.slice=function(cutEdges){if(cutEdges.length==0)return[this];if(cutEdges instanceof Array&&cutEdges.length&&cutEdges[0]instanceof Array&&cutEdges[0].length==2&&cutEdges[0][0]instanceof Array){var polys=[this];for(var i=0;imaxlevel){console.warn("quickDecomp: max level ("+maxlevel+") reached.");return result}for(var i=0;iupperIndex){upperIndex+=this.vertices.length}closestDist=Number.MAX_VALUE;if(upperIndex3&&i>=0;--i){if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){this.vertices.splice(i%this.vertices.length,1);i--;num++}}return num}},{"./Line":2,"./Point":3,"./Scalar":5}],5:[function(require,module,exports){module.exports=Scalar;function Scalar(){}Scalar.eq=function(a,b,precision){precision=precision||0;return Math.abs(a-b) (http://steffe.se)",keywords:["p2.js","p2","physics","engine","2d"],main:"./src/p2.js",engines:{node:"*"},repository:{type:"git",url:"https://github.com/schteppe/p2.js.git"},bugs:{url:"https://github.com/schteppe/p2.js/issues"},licenses:[{type:"MIT"}],devDependencies:{grunt:"~0.4.0","grunt-contrib-jshint":"~0.9.2","grunt-contrib-nodeunit":"~0.1.2","grunt-contrib-uglify":"~0.4.0","grunt-contrib-watch":"~0.5.0","grunt-browserify":"~2.0.1","z-schema":"~2.4.6"},dependencies:{"poly-decomp":"0.1.0","gl-matrix":"2.1.0"}}},{}],8:[function(require,module,exports){var vec2=require("../math/vec2"),Utils=require("../utils/Utils");module.exports=AABB;function AABB(options){this.lowerBound=vec2.create();if(options&&options.lowerBound){vec2.copy(this.lowerBound,options.lowerBound)}this.upperBound=vec2.create();if(options&&options.upperBound){vec2.copy(this.upperBound,options.upperBound)}}var tmp=vec2.create();AABB.prototype.setFromPoints=function(points,position,angle){var l=this.lowerBound,u=this.upperBound;vec2.set(l,Number.MAX_VALUE,Number.MAX_VALUE);vec2.set(u,-Number.MAX_VALUE,-Number.MAX_VALUE);for(var i=0;iu[j]){u[j]=p[j]}if(p[j]this.upperBound[i]){this.upperBound[i]=aabb.upperBound[i]}}};AABB.prototype.overlaps=function(aabb){var l1=this.lowerBound,u1=this.upperBound,l2=aabb.lowerBound,u2=aabb.upperBound;return(l2[0]<=u1[0]&&u1[0]<=u2[0]||l1[0]<=u2[0]&&u2[0]<=u1[0])&&(l2[1]<=u1[1]&&u1[1]<=u2[1]||l1[1]<=u2[1]&&u2[1]<=u1[1])}},{"../math/vec2":30,"../utils/Utils":47}],9:[function(require,module,exports){var vec2=require("../math/vec2");var Body=require("../objects/Body");module.exports=Broadphase;function Broadphase(type){this.type=type;this.result=[];this.world=null;this.boundingVolumeType=Broadphase.AABB}Broadphase.AABB=1;Broadphase.BOUNDING_CIRCLE=2;Broadphase.prototype.setWorld=function(world){this.world=world};Broadphase.prototype.getCollisionPairs=function(world){throw new Error("getCollisionPairs must be implemented in a subclass!")};var dist=vec2.create();Broadphase.boundingRadiusCheck=function(bodyA,bodyB){vec2.sub(dist,bodyA.position,bodyB.position);var d2=vec2.squaredLength(dist),r=bodyA.boundingRadius+bodyB.boundingRadius;return d2<=r*r};Broadphase.aabbCheck=function(bodyA,bodyB){if(bodyA.aabbNeedsUpdate){bodyA.updateAABB()}if(bodyB.aabbNeedsUpdate){bodyB.updateAABB()}return bodyA.aabb.overlaps(bodyB.aabb)};Broadphase.prototype.boundingVolumeCheck=function(bodyA,bodyB){var result;switch(this.boundingVolumeType){case Broadphase.BOUNDING_CIRCLE:result=Broadphase.boundingRadiusCheck(bodyA,bodyB);break;case Broadphase.AABB:result=Broadphase.aabbCheck(bodyA,bodyB);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return result};Broadphase.canCollide=function(bodyA,bodyB){if(bodyA.motionState===Body.STATIC&&bodyB.motionState===Body.STATIC){return false}if(bodyA.motionState===Body.KINEMATIC&&bodyB.motionState===Body.STATIC||bodyA.motionState===Body.STATIC&&bodyB.motionState===Body.KINEMATIC){return false}if(bodyA.motionState===Body.KINEMATIC&&bodyB.motionState===Body.KINEMATIC){return false}if(bodyA.sleepState===Body.SLEEPING&&bodyB.sleepState===Body.SLEEPING){return false}if(bodyA.sleepState===Body.SLEEPING&&bodyB.motionState===Body.STATIC||bodyB.sleepState===Body.SLEEPING&&bodyA.motionState===Body.STATIC){return false}return true};Broadphase.NAIVE=1;Broadphase.SAP=2},{"../math/vec2":30,"../objects/Body":31}],10:[function(require,module,exports){var Circle=require("../shapes/Circle"),Plane=require("../shapes/Plane"),Particle=require("../shapes/Particle"),Broadphase=require("../collision/Broadphase"),vec2=require("../math/vec2"),Utils=require("../utils/Utils");module.exports=GridBroadphase;function GridBroadphase(options){Broadphase.apply(this);options=Utils.defaults(options,{xmin:-100,xmax:100,ymin:-100,ymax:100,nx:10,ny:10});this.xmin=options.xmin;this.ymin=options.ymin;this.xmax=options.xmax;this.ymax=options.ymax;this.nx=options.nx;this.ny=options.ny;this.binsizeX=(this.xmax-this.xmin)/this.nx;this.binsizeY=(this.ymax-this.ymin)/this.ny}GridBroadphase.prototype=new Broadphase;GridBroadphase.prototype.getCollisionPairs=function(world){var result=[],bodies=world.bodies,Ncolliding=bodies.length,binsizeX=this.binsizeX,binsizeY=this.binsizeY,nx=this.nx,ny=this.ny,xmin=this.xmin,ymin=this.ymin,xmax=this.xmax,ymax=this.ymax;var bins=[],Nbins=nx*ny;for(var i=0;i=0&&idxpos0&&pos0){for(var i=0;ir*r){return 0}if(justTest){return true}var c=this.createContactEquation(bodyA,bodyB,si,sj);sub(c.normalA,offsetB,offsetA);vec2.normalize(c.normalA,c.normalA);vec2.scale(c.contactPointA,c.normalA,radiusA);vec2.scale(c.contactPointB,c.normalA,-radiusB);add(c.contactPointA,c.contactPointA,offsetA);sub(c.contactPointA,c.contactPointA,bodyA.position);add(c.contactPointB,c.contactPointB,offsetB);sub(c.contactPointB,c.contactPointB,bodyB.position);this.contactEquations.push(c);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}return 1};Narrowphase.prototype[Shape.PLANE|Shape.CONVEX]=Narrowphase.prototype[Shape.PLANE|Shape.RECTANGLE]=Narrowphase.prototype.planeConvex=function(bi,si,xi,ai,bj,sj,xj,aj,justTest){var convexBody=bj,convexOffset=xj,convexShape=sj,convexAngle=aj,planeBody=bi,planeShape=si,planeOffset=xi,planeAngle=ai;var worldVertex=tmp1,worldNormal=tmp2,dist=tmp3;var numReported=0;vec2.rotate(worldNormal,yAxis,planeAngle);for(var i=0;i0)return 0;if(justTest)return true;var c=this.createContactEquation(planeBody,particleBody,sj,si);vec2.copy(c.normalA,worldNormal);vec2.scale(dist,c.normalA,d);sub(c.contactPointA,particleOffset,dist);sub(c.contactPointA,c.contactPointA,planeBody.position);sub(c.contactPointB,particleOffset,particleBody.position);this.contactEquations.push(c);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}return 1};Narrowphase.prototype[Shape.CIRCLE|Shape.PARTICLE]=Narrowphase.prototype.circleParticle=function(bi,si,xi,ai,bj,sj,xj,aj,justTest){var circleBody=bi,circleShape=si,circleOffset=xi,particleBody=bj,particleShape=sj,particleOffset=xj,dist=tmp1;sub(dist,particleOffset,circleOffset);if(vec2.squaredLength(dist)>circleShape.radius*circleShape.radius)return 0;if(justTest)return true;var c=this.createContactEquation(circleBody,particleBody,si,sj);vec2.copy(c.normalA,dist);vec2.normalize(c.normalA,c.normalA);vec2.scale(c.contactPointA,c.normalA,circleShape.radius);add(c.contactPointA,c.contactPointA,circleOffset);sub(c.contactPointA,c.contactPointA,circleBody.position);sub(c.contactPointB,particleOffset,particleBody.position);this.contactEquations.push(c);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(c))}return 1};var capsulePlane_tmpCircle=new Circle(1),capsulePlane_tmp1=vec2.create(),capsulePlane_tmp2=vec2.create(),capsulePlane_tmp3=vec2.create();Narrowphase.prototype[Shape.PLANE|Shape.CAPSULE]=Narrowphase.prototype.planeCapsule=function(bi,si,xi,ai,bj,sj,xj,aj,justTest){var end1=capsulePlane_tmp1,end2=capsulePlane_tmp2,circle=capsulePlane_tmpCircle,dst=capsulePlane_tmp3;vec2.set(end1,-sj.length/2,0);vec2.rotate(end1,end1,aj);add(end1,end1,xj);vec2.set(end2,sj.length/2,0);vec2.rotate(end2,end2,aj);add(end2,end2,xj);circle.radius=sj.radius;var numContacts1=this.circlePlane(bj,circle,end1,0,bi,si,xi,ai,justTest),numContacts2=this.circlePlane(bj,circle,end2,0,bi,si,xi,ai,justTest);if(justTest)return numContacts1||numContacts2;else return numContacts1+numContacts2};Narrowphase.prototype.capsulePlane=function(bi,si,xi,ai,bj,sj,xj,aj,justTest){console.warn("Narrowphase.prototype.capsulePlane() is deprecated. Use .planeCapsule() instead!");return this.planeCapsule(bj,sj,xj,aj,bi,si,xi,ai,justTest)};Narrowphase.prototype[Shape.CIRCLE|Shape.PLANE]=Narrowphase.prototype.circlePlane=function(bi,si,xi,ai,bj,sj,xj,aj,justTest){var circleBody=bi,circleShape=si,circleOffset=xi,planeBody=bj,shapeB=sj,planeOffset=xj,planeAngle=aj;planeAngle=planeAngle||0;var planeToCircle=tmp1,worldNormal=tmp2,temp=tmp3;sub(planeToCircle,circleOffset,planeOffset);vec2.rotate(worldNormal,yAxis,planeAngle);var d=dot(worldNormal,planeToCircle);if(d>circleShape.radius){return 0}if(justTest){return true}var contact=this.createContactEquation(planeBody,circleBody,sj,si);vec2.copy(contact.normalA,worldNormal);vec2.scale(contact.contactPointB,contact.normalA,-circleShape.radius);add(contact.contactPointB,contact.contactPointB,circleOffset);sub(contact.contactPointB,contact.contactPointB,circleBody.position);vec2.scale(temp,contact.normalA,d);sub(contact.contactPointA,planeToCircle,temp);add(contact.contactPointA,contact.contactPointA,planeOffset);sub(contact.contactPointA,contact.contactPointA,planeBody.position);this.contactEquations.push(contact);if(this.enableFriction){this.frictionEquations.push(this.createFrictionFromContact(contact))}return 1};Narrowphase.convexPrecision=1e-7;Narrowphase.prototype[Shape.CONVEX]=Narrowphase.prototype[Shape.CONVEX|Shape.RECTANGLE]=Narrowphase.prototype[Shape.RECTANGLE]=Narrowphase.prototype.convexConvex=function(bi,si,xi,ai,bj,sj,xj,aj,justTest,precision){var sepAxis=tmp1,worldPoint=tmp2,worldPoint0=tmp3,worldPoint1=tmp4,worldEdge=tmp5,projected=tmp6,penetrationVec=tmp7,dist=tmp8,worldNormal=tmp9,numContacts=0,precision=precision||Narrowphase.convexPrecision;var found=Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis);if(!found){return 0}sub(dist,xj,xi);if(dot(sepAxis,dist)>0){vec2.scale(sepAxis,sepAxis,-1)}var closestEdge1=Narrowphase.getClosestEdge(si,ai,sepAxis,true),closestEdge2=Narrowphase.getClosestEdge(sj,aj,sepAxis);if(closestEdge1===-1||closestEdge2===-1){return 0}for(var k=0;k<2;k++){var closestEdgeA=closestEdge1,closestEdgeB=closestEdge2,shapeA=si,shapeB=sj,offsetA=xi,offsetB=xj,angleA=ai,angleB=aj,bodyA=bi,bodyB=bj;if(k===0){var tmp;tmp=closestEdgeA;closestEdgeA=closestEdgeB;closestEdgeB=tmp;tmp=shapeA;shapeA=shapeB;shapeB=tmp;tmp=offsetA;offsetA=offsetB;offsetB=tmp;tmp=angleA;angleA=angleB;angleB=tmp;tmp=bodyA;bodyA=bodyB;bodyB=tmp}for(var j=closestEdgeB;j=3){if(justTest){return true}var c=this.createContactEquation(bodyA,bodyB,shapeA,shapeB);numContacts++;var v0=shapeA.vertices[closestEdgeA%shapeA.vertices.length],v1=shapeA.vertices[(closestEdgeA+1)%shapeA.vertices.length];vec2.rotate(worldPoint0,v0,angleA);vec2.rotate(worldPoint1,v1,angleA);add(worldPoint0,worldPoint0,offsetA);add(worldPoint1,worldPoint1,offsetA);sub(worldEdge,worldPoint1,worldPoint0);vec2.rotate90cw(c.normalA,worldEdge);vec2.normalize(c.normalA,c.normalA);sub(dist,worldPoint,worldPoint0);var d=dot(c.normalA,dist);vec2.scale(penetrationVec,c.normalA,d);sub(c.contactPointA,worldPoint,offsetA);sub(c.contactPointA,c.contactPointA,penetrationVec);add(c.contactPointA,c.contactPointA,offsetA);sub(c.contactPointA,c.contactPointA,bodyA.position);sub(c.contactPointB,worldPoint,offsetB);add(c.contactPointB,c.contactPointB,offsetB);sub(c.contactPointB,c.contactPointB,bodyB.position);this.contactEquations.push(c);if(this.enableFriction)this.frictionEquations.push(this.createFrictionFromContact(c))}}}return numContacts};var pcoa_tmp1=vec2.fromValues(0,0);Narrowphase.projectConvexOntoAxis=function(convexShape,convexOffset,convexAngle,worldAxis,result){var max=null,min=null,v,value,localAxis=pcoa_tmp1;vec2.rotate(localAxis,worldAxis,-convexAngle);for(var i=0;imax)max=value;if(min===null||valuemax){var t=min;min=max;max=t}var offset=dot(convexOffset,worldAxis);vec2.set(result,min+offset,max+offset)};var fsa_tmp1=vec2.fromValues(0,0),fsa_tmp2=vec2.fromValues(0,0),fsa_tmp3=vec2.fromValues(0,0),fsa_tmp4=vec2.fromValues(0,0),fsa_tmp5=vec2.fromValues(0,0),fsa_tmp6=vec2.fromValues(0,0);Narrowphase.findSeparatingAxis=function(c1,offset1,angle1,c2,offset2,angle2,sepAxis){var maxDist=null,overlap=false,found=false,edge=fsa_tmp1,worldPoint0=fsa_tmp2,worldPoint1=fsa_tmp3,normal=fsa_tmp4,span1=fsa_tmp5,span2=fsa_tmp6;for(var j=0;j!==2;j++){var c=c1,angle=angle1;if(j===1){c=c2;angle=angle2}for(var i=0;i!==c.vertices.length;i++){vec2.rotate(worldPoint0,c.vertices[i],angle);vec2.rotate(worldPoint1,c.vertices[(i+1)%c.vertices.length],angle);sub(edge,worldPoint1,worldPoint0);vec2.rotate90cw(normal,edge);vec2.normalize(normal,normal);Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1);Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2);var a=span1,b=span2,swapped=false;if(span1[0]>span2[0]){b=span1;a=span2;swapped=true}var dist=b[0]-a[1];overlap=dist<=Narrowphase.convexPrecision;if(maxDist===null||dist>maxDist){vec2.copy(sepAxis,normal);maxDist=dist;found=overlap}}}return found};var gce_tmp1=vec2.fromValues(0,0),gce_tmp2=vec2.fromValues(0,0),gce_tmp3=vec2.fromValues(0,0);Narrowphase.getClosestEdge=function(c,angle,axis,flip){var localAxis=gce_tmp1,edge=gce_tmp2,normal=gce_tmp3;vec2.rotate(localAxis,axis,-angle);if(flip){vec2.scale(localAxis,localAxis,-1)}var closestEdge=-1,N=c.vertices.length;for(var i=0;i!==N;i++){sub(edge,c.vertices[(i+1)%N],c.vertices[i%N]);vec2.rotate90cw(normal,edge);vec2.normalize(normal,normal);var d=dot(normal,localAxis);if(closestEdge==-1||d>maxDot){closestEdge=i%N;maxDot=d}}return closestEdge};var circleHeightfield_candidate=vec2.create(),circleHeightfield_dist=vec2.create(),circleHeightfield_v0=vec2.create(),circleHeightfield_v1=vec2.create(),circleHeightfield_minCandidate=vec2.create(),circleHeightfield_worldNormal=vec2.create(),circleHeightfield_minCandidateNormal=vec2.create();Narrowphase.prototype[Shape.CIRCLE|Shape.HEIGHTFIELD]=Narrowphase.prototype.circleHeightfield=function(circleBody,circleShape,circlePos,circleAngle,hfBody,hfShape,hfPos,hfAngle,justTest,radius){var data=hfShape.data,radius=radius||circleShape.radius,w=hfShape.elementWidth,dist=circleHeightfield_dist,candidate=circleHeightfield_candidate,minCandidate=circleHeightfield_minCandidate,minCandidateNormal=circleHeightfield_minCandidateNormal,worldNormal=circleHeightfield_worldNormal,v0=circleHeightfield_v0,v1=circleHeightfield_v1;var idxA=Math.floor((circlePos[0]-radius-hfPos[0])/w),idxB=Math.ceil((circlePos[0]+radius-hfPos[0])/w);if(idxA<0)idxA=0;if(idxB>=data.length)idxB=data.length-1;var max=data[idxA],min=data[idxB];for(var i=idxA;imax)max=data[i]}if(circlePos[1]-radius>max)return justTest?false:0;if(circlePos[1]+radius=v0[0]&&candidate[0]0){for(var i=idxA;i<=idxB;i++){vec2.set(v0,i*w,data[i]);vec2.add(v0,v0,hfPos);vec2.sub(dist,circlePos,v0);if(vec2.squaredLength(dist)=data.length)idxB=data.length-1;var max=data[idxA],min=data[idxB];for(var i=idxA;imax)max=data[i]}if(convexBody.aabb.lowerBound[1]>max){return justTest?false:0}var found=false;var numContacts=0;for(var i=idxA;i=0;j--){if(a[j].aabb.lowerBound[axisIndex]<=v.aabb.lowerBound[axisIndex]){break}a[j+1]=a[j]}a[j+1]=v}return a};SAPBroadphase.prototype.getCollisionPairs=function(world){var bodies=this.axisList,result=this.result,axisIndex=this.axisIndex;result.length=0;var l=bodies.length;while(l--){var b=bodies[l];if(b.aabbNeedsUpdate){b.updateAABB()}}SAPBroadphase.sortAxisList(bodies,axisIndex);for(var i=0,N=bodies.length|0;i!==N;i++){var bi=bodies[i];for(var j=i+1;jupperLimit){vec2.scale(upperLimitEquation.normalA,worldAxisA,-1);vec2.sub(upperLimitEquation.contactPointA,worldAnchorA,bodyA.position);vec2.sub(upperLimitEquation.contactPointB,worldAnchorB,bodyB.position);vec2.scale(tmp,worldAxisA,upperLimit);vec2.add(upperLimitEquation.contactPointA,upperLimitEquation.contactPointA,tmp);if(eqs.indexOf(upperLimitEquation)==-1)eqs.push(upperLimitEquation)}else{var idx=eqs.indexOf(upperLimitEquation);if(idx!=-1)eqs.splice(idx,1)}if(this.lowerLimitEnabled&&relPositionupperLimit){upperLimitEquation.angle=upperLimit;if(eqs.indexOf(upperLimitEquation)==-1)eqs.push(upperLimitEquation)}else{var idx=eqs.indexOf(upperLimitEquation);if(idx!=-1)eqs.splice(idx,1)}if(this.lowerLimitEnabled&&relAngle>1;if(n<3)return[];var tgs=[];var avl=[];for(var i=0;i3){var i0=avl[(i+0)%al];var i1=avl[(i+1)%al];var i2=avl[(i+2)%al];var ax=p[2*i0],ay=p[2*i0+1];var bx=p[2*i1],by=p[2*i1+1];var cx=p[2*i2],cy=p[2*i2+1];var earFound=false;if(PolyK._convex(ax,ay,bx,by,cx,cy)){earFound=true;for(var j=0;j3*al)break}tgs.push(avl[0],avl[1],avl[2]);return tgs};PolyK._PointInTriangle=function(px,py,ax,ay,bx,by,cx,cy){var v0x=cx-ax;var v0y=cy-ay;var v1x=bx-ax;var v1y=by-ay;var v2x=px-ax;var v2y=py-ay;var dot00=v0x*v0x+v0y*v0y;var dot01=v0x*v1x+v0y*v1y;var dot02=v0x*v2x+v0y*v2y;var dot11=v1x*v1x+v1y*v1y;var dot12=v1x*v2x+v1y*v2y;var invDenom=1/(dot00*dot11-dot01*dot01);var u=(dot11*dot02-dot01*dot12)*invDenom;var v=(dot00*dot12-dot01*dot02)*invDenom;return u>=0&&v>=0&&u+v<1};PolyK._convex=function(ax,ay,bx,by,cx,cy){return(ay-by)*(cx-bx)+(bx-ax)*(cy-by)>=0};module.exports=PolyK},{}],30:[function(require,module,exports){var vec2=require("../../build/vec2").vec2;vec2.crossLength=function(a,b){return a[0]*b[1]-a[1]*b[0]};vec2.crossVZ=function(out,vec,zcomp){vec2.rotate(out,vec,-Math.PI/2);vec2.scale(out,out,zcomp);return out};vec2.crossZV=function(out,zcomp,vec){vec2.rotate(out,vec,Math.PI/2);vec2.scale(out,out,zcomp);return out};vec2.rotate=function(out,a,angle){var c=Math.cos(angle),s=Math.sin(angle),x=a[0],y=a[1];out[0]=c*x-s*y;out[1]=s*x+c*y};vec2.rotate90cw=function(out,a){out[0]=a[1];out[1]=-a[0]};vec2.toLocalFrame=function(out,worldPoint,framePosition,frameAngle){vec2.copy(out,worldPoint);vec2.sub(out,out,framePosition);vec2.rotate(out,out,-frameAngle)};vec2.toGlobalFrame=function(out,localPoint,framePosition,frameAngle){vec2.copy(out,localPoint);vec2.rotate(out,out,frameAngle);vec2.add(out,out,framePosition)};vec2.centroid=function(out,a,b,c){vec2.add(out,a,b);vec2.add(out,out,c);vec2.scale(out,out,1/3);return out};module.exports=vec2},{"../../build/vec2":1}],31:[function(require,module,exports){var vec2=require("../math/vec2"),decomp=require("poly-decomp"),Convex=require("../shapes/Convex"),AABB=require("../collision/AABB"),EventEmitter=require("../events/EventEmitter");module.exports=Body;function Body(options){options=options||{};EventEmitter.call(this);this.id=++Body._idCounter;this.world=null;this.shapes=[];this.shapeOffsets=[];this.shapeAngles=[];this.mass=options.mass||0;this.invMass=0;this.inertia=0;this.invInertia=0;this.fixedRotation=!!options.fixedRotation||false;this.position=vec2.fromValues(0,0);if(options.position){vec2.copy(this.position,options.position)}this.interpolatedPosition=vec2.fromValues(0,0);this.interpolatedAngle=0;this.previousPosition=vec2.fromValues(0,0);this.previousAngle=0;this.velocity=vec2.fromValues(0,0);if(options.velocity){vec2.copy(this.velocity,options.velocity)}this.vlambda=vec2.fromValues(0,0);this.wlambda=0;this.angle=options.angle||0;this.angularVelocity=options.angularVelocity||0;this.force=vec2.create();if(options.force)vec2.copy(this.force,options.force);this.angularForce=options.angularForce||0;this.damping=typeof options.damping=="number"?options.damping:.1;this.angularDamping=typeof options.angularDamping=="number"?options.angularDamping:.1;this.motionState=this.mass===0?Body.STATIC:Body.DYNAMIC;this.boundingRadius=0;this.aabb=new AABB;this.aabbNeedsUpdate=true;this.allowSleep=true;this.wantsToSleep=false;this.sleepState=Body.AWAKE;this.sleepSpeedLimit=.2;this.sleepTimeLimit=1;this.gravityScale=1;this.timeLastSleepy=0;this.concavePath=null;this.lastDampingScale=1;this.lastAngularDampingScale=1;this.lastDampingTimeStep=-1;this._wakeUpAfterNarrowphase=false;this.updateMassProperties()}Body.prototype=new EventEmitter;Body._idCounter=0;Body.prototype.setDensity=function(density){var totalArea=this.getArea();this.mass=totalArea*density;this.updateMassProperties()};Body.prototype.getArea=function(){var totalArea=0;for(var i=0;iradius){radius=offset+r}}this.boundingRadius=radius};Body.prototype.addShape=function(shape,offset,angle){angle=angle||0;if(offset){offset=vec2.fromValues(offset[0],offset[1])}else{offset=vec2.fromValues(0,0)}this.shapes.push(shape);this.shapeOffsets.push(offset);this.shapeAngles.push(angle);this.updateMassProperties();this.updateBoundingRadius();this.aabbNeedsUpdate=true};Body.prototype.removeShape=function(shape){var idx=this.shapes.indexOf(shape);if(idx!==-1){this.shapes.splice(idx,1);this.shapeOffsets.splice(idx,1);this.shapeAngles.splice(idx,1);this.aabbNeedsUpdate=true;return true}else{return false}};Body.prototype.updateMassProperties=function(){if(this.motionState===Body.STATIC||this.motionState===Body.KINEMATIC){this.mass=Number.MAX_VALUE;this.invMass=0;this.inertia=Number.MAX_VALUE;this.invInertia=0}else{var shapes=this.shapes,N=shapes.length,m=this.mass/N,I=0;if(!this.fixedRotation){for(var i=0;i0?1/I:0}else{this.inertia=Number.MAX_VALUE;this.invInertia=0}this.invMass=1/this.mass}};var Body_applyForce_r=vec2.create();Body.prototype.applyForce=function(force,worldPoint){var r=Body_applyForce_r;vec2.sub(r,worldPoint,this.position);vec2.add(this.force,this.force,force);var rotForce=vec2.crossLength(r,force);this.angularForce+=rotForce};Body.prototype.toLocalFrame=function(out,worldPoint){vec2.toLocalFrame(out,worldPoint,this.position,this.angle)};Body.prototype.toWorldFrame=function(out,localPoint){vec2.toGlobalFrame(out,localPoint,this.position,this.angle)};Body.prototype.fromPolygon=function(path,options){options=options||{};for(var i=this.shapes.length;i>=0;--i)this.removeShape(this.shapes[i]);var p=new decomp.Polygon;p.vertices=path;p.makeCCW();if(typeof options.removeCollinearPoints=="number"){p.removeCollinearPoints(options.removeCollinearPoints)}if(typeof options.skipSimpleCheck=="undefined"){if(!p.isSimple())return false}this.concavePath=p.vertices.slice(0);for(var i=0;i=speedLimitSquared){this.idleTime=0;this.sleepState=Body.AWAKE}else{this.idleTime+=dt;this.sleepState=Body.SLEEPY}if(this.idleTime>this.sleepTimeLimit){if(!dontSleep){this.sleep()}else{this.wantsToSleep=true}}};Body.prototype.getVelocityFromPosition=function(store,timeStep){store=store||vec2.create();vec2.sub(store,this.position,this.previousPosition);vec2.scale(store,store,1/timeStep);return store};Body.prototype.getAngularVelocityFromPosition=function(timeStep){return(this.angle-this.previousAngle)/timeStep};Body.sleepyEvent={type:"sleepy"};Body.sleepEvent={type:"sleep"};Body.wakeUpEvent={type:"wakeup"};Body.DYNAMIC=1;Body.STATIC=2;Body.KINEMATIC=4;Body.AWAKE=0;Body.SLEEPY=1;Body.SLEEPING=2},{"../collision/AABB":8,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":36,"poly-decomp":6}],32:[function(require,module,exports){var vec2=require("../math/vec2");var Utils=require("../utils/Utils");module.exports=Spring;function Spring(bodyA,bodyB,options){options=Utils.defaults(options,{restLength:1,stiffness:100,damping:1,localAnchorA:[0,0],localAnchorB:[0,0]});this.restLength=options.restLength;this.stiffness=options.stiffness;this.damping=options.damping;this.bodyA=bodyA;this.bodyB=bodyB;this.localAnchorA=vec2.create();vec2.copy(this.localAnchorA,options.localAnchorA);this.localAnchorB=vec2.create();vec2.copy(this.localAnchorB,options.localAnchorB);if(options.worldAnchorA){this.setWorldAnchorA(options.worldAnchorA)}if(options.worldAnchorB){this.setWorldAnchorB(options.worldAnchorB)}}Spring.prototype.setWorldAnchorA=function(worldAnchorA){this.bodyA.toLocalFrame(this.localAnchorA,worldAnchorA)};Spring.prototype.setWorldAnchorB=function(worldAnchorB){this.bodyB.toLocalFrame(this.localAnchorB,worldAnchorB)};Spring.prototype.getWorldAnchorA=function(result){this.bodyA.toWorldFrame(result,this.localAnchorA)};Spring.prototype.getWorldAnchorB=function(result){this.bodyB.toWorldFrame(result,this.localAnchorB)};var applyForce_r=vec2.create(),applyForce_r_unit=vec2.create(),applyForce_u=vec2.create(),applyForce_f=vec2.create(),applyForce_worldAnchorA=vec2.create(),applyForce_worldAnchorB=vec2.create(),applyForce_ri=vec2.create(),applyForce_rj=vec2.create(),applyForce_tmp=vec2.create();Spring.prototype.applyForce=function(){var k=this.stiffness,d=this.damping,l=this.restLength,bodyA=this.bodyA,bodyB=this.bodyB,r=applyForce_r,r_unit=applyForce_r_unit,u=applyForce_u,f=applyForce_f,tmp=applyForce_tmp;var worldAnchorA=applyForce_worldAnchorA,worldAnchorB=applyForce_worldAnchorB,ri=applyForce_ri,rj=applyForce_rj;this.getWorldAnchorA(worldAnchorA);this.getWorldAnchorB(worldAnchorB);vec2.sub(ri,worldAnchorA,bodyA.position);vec2.sub(rj,worldAnchorB,bodyB.position);vec2.sub(r,worldAnchorB,worldAnchorA);var rlen=vec2.len(r);vec2.normalize(r_unit,r);vec2.sub(u,bodyB.velocity,bodyA.velocity);vec2.crossZV(tmp,bodyB.angularVelocity,rj);vec2.add(u,u,tmp);vec2.crossZV(tmp,bodyA.angularVelocity,ri);vec2.sub(u,u,tmp);vec2.scale(f,r_unit,-k*(rlen-l)-d*vec2.dot(u,r_unit));vec2.sub(bodyA.force,bodyA.force,f);vec2.add(bodyB.force,bodyB.force,f);var ri_x_f=vec2.crossLength(ri,f);var rj_x_f=vec2.crossLength(rj,f);bodyA.angularForce-=ri_x_f;bodyB.angularForce+=rj_x_f}},{"../math/vec2":30,"../utils/Utils":47}],33:[function(require,module,exports){module.exports={AABB:require("./collision/AABB"),AngleLockEquation:require("./equations/AngleLockEquation"),Body:require("./objects/Body"),Broadphase:require("./collision/Broadphase"),Capsule:require("./shapes/Capsule"),Circle:require("./shapes/Circle"),Constraint:require("./constraints/Constraint"),ContactEquation:require("./equations/ContactEquation"),ContactMaterial:require("./material/ContactMaterial"),Convex:require("./shapes/Convex"),DistanceConstraint:require("./constraints/DistanceConstraint"),Equation:require("./equations/Equation"),EventEmitter:require("./events/EventEmitter"),FrictionEquation:require("./equations/FrictionEquation"),GearConstraint:require("./constraints/GearConstraint"),GridBroadphase:require("./collision/GridBroadphase"),GSSolver:require("./solver/GSSolver"),Heightfield:require("./shapes/Heightfield"),Line:require("./shapes/Line"),LockConstraint:require("./constraints/LockConstraint"),Material:require("./material/Material"),Narrowphase:require("./collision/Narrowphase"),NaiveBroadphase:require("./collision/NaiveBroadphase"),Particle:require("./shapes/Particle"),Plane:require("./shapes/Plane"),RevoluteConstraint:require("./constraints/RevoluteConstraint"),PrismaticConstraint:require("./constraints/PrismaticConstraint"),Rectangle:require("./shapes/Rectangle"),RotationalVelocityEquation:require("./equations/RotationalVelocityEquation"),SAPBroadphase:require("./collision/SAPBroadphase"),Shape:require("./shapes/Shape"),Solver:require("./solver/Solver"),Spring:require("./objects/Spring"),Utils:require("./utils/Utils"),World:require("./world/World"),vec2:require("./math/vec2"),version:require("../package.json").version}},{"../package.json":7,"./collision/AABB":8,"./collision/Broadphase":9,"./collision/GridBroadphase":10,"./collision/NaiveBroadphase":11,"./collision/Narrowphase":12,"./collision/SAPBroadphase":13,"./constraints/Constraint":14,"./constraints/DistanceConstraint":15,"./constraints/GearConstraint":16,"./constraints/LockConstraint":17,"./constraints/PrismaticConstraint":18,"./constraints/RevoluteConstraint":19,"./equations/AngleLockEquation":20,"./equations/ContactEquation":21,"./equations/Equation":22,"./equations/FrictionEquation":23,"./equations/RotationalVelocityEquation":25,"./events/EventEmitter":26,"./material/ContactMaterial":27,"./material/Material":28,"./math/vec2":30,"./objects/Body":31,"./objects/Spring":32,"./shapes/Capsule":34,"./shapes/Circle":35,"./shapes/Convex":36,"./shapes/Heightfield":37,"./shapes/Line":38,"./shapes/Particle":39,"./shapes/Plane":40,"./shapes/Rectangle":41,"./shapes/Shape":42,"./solver/GSSolver":43,"./solver/Solver":44,"./utils/Utils":47,"./world/World":51}],34:[function(require,module,exports){var Shape=require("./Shape"),vec2=require("../math/vec2");module.exports=Capsule;function Capsule(length,radius){this.length=length||1;this.radius=radius||1;Shape.call(this,Shape.CAPSULE)}Capsule.prototype=new Shape;Capsule.prototype.computeMomentOfInertia=function(mass){var r=this.radius,w=this.length+r,h=r*2;return mass*(h*h+w*w)/12};Capsule.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius+this.length/2};Capsule.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius+this.radius*2*this.length};var r=vec2.create();Capsule.prototype.computeAABB=function(out,position,angle){var radius=this.radius;vec2.set(r,this.length,0);vec2.rotate(r,r,angle);vec2.set(out.upperBound,Math.max(r[0]+radius,-r[0]+radius),Math.max(r[1]+radius,-r[1]+radius));vec2.set(out.lowerBound,Math.min(r[0]-radius,-r[0]-radius),Math.min(r[1]-radius,-r[1]-radius));vec2.add(out.lowerBound,out.lowerBound,position);vec2.add(out.upperBound,out.upperBound,position)}},{"../math/vec2":30,"./Shape":42}],35:[function(require,module,exports){var Shape=require("./Shape"),vec2=require("../math/vec2");module.exports=Circle;function Circle(radius){this.radius=radius||1;Shape.call(this,Shape.CIRCLE)}Circle.prototype=new Shape;Circle.prototype.computeMomentOfInertia=function(mass){var r=this.radius;return mass*r*r/2};Circle.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius};Circle.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius};Circle.prototype.computeAABB=function(out,position,angle){var r=this.radius;vec2.set(out.upperBound,r,r);vec2.set(out.lowerBound,-r,-r);if(position){vec2.add(out.lowerBound,out.lowerBound,position);vec2.add(out.upperBound,out.upperBound,position)}}},{"../math/vec2":30,"./Shape":42}],36:[function(require,module,exports){var Shape=require("./Shape"),vec2=require("../math/vec2"),polyk=require("../math/polyk"),decomp=require("poly-decomp");module.exports=Convex;function Convex(vertices){this.vertices=[];for(var i=0;ir2)r2=l2}this.boundingRadius=Math.sqrt(r2)};Convex.triangleArea=function(a,b,c){return((b[0]-a[0])*(c[1]-a[1])-(c[0]-a[0])*(b[1]-a[1]))*.5};Convex.prototype.updateArea=function(){this.updateTriangles();this.area=0;var triangles=this.triangles,verts=this.vertices;for(var i=0;i!==triangles.length;i++){var t=triangles[i],a=verts[t[0]],b=verts[t[1]],c=verts[t[2]];var m=Convex.triangleArea(a,b,c);this.area+=m}};Convex.prototype.computeAABB=function(out,position,angle){out.setFromPoints(this.vertices,position,angle)}},{"../math/polyk":29,"../math/vec2":30,"./Shape":42,"poly-decomp":6}],37:[function(require,module,exports){var Shape=require("./Shape"),vec2=require("../math/vec2"),Utils=require("../utils/Utils");module.exports=Heightfield;function Heightfield(data,options){options=Utils.defaults(options,{maxValue:null,minValue:null,elementWidth:.1});if(options.minValue===null||options.maxValue===null){options.maxValue=data[0];options.minValue=data[0];for(var i=0;i!==data.length;i++){var v=data[i];if(v>options.maxValue){options.maxValue=v}if(vmaxForce*dt){deltalambda=maxForce*dt-lambdaj}lambda[j]+=deltalambda;eq.addToWlambda(deltalambda);return deltalambda}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":47,"./Solver":44}],44:[function(require,module,exports){var Utils=require("../utils/Utils"),EventEmitter=require("../events/EventEmitter");module.exports=Solver;function Solver(options,type){options=options||{};EventEmitter.call(this);this.type=type;this.equations=[];this.equationSortFunction=options.equationSortFunction||false}Solver.prototype=new EventEmitter;Solver.prototype.solve=function(dt,world){throw new Error("Solver.solve should be implemented by subclasses!")};var mockWorld={bodies:[]};Solver.prototype.solveIsland=function(dt,island){this.removeAllEquations();if(island.equations.length){this.addEquations(island.equations);mockWorld.bodies.length=0;island.getBodies(mockWorld.bodies);if(mockWorld.bodies.length){this.solve(dt,mockWorld)}}};Solver.prototype.sortEquations=function(){if(this.equationSortFunction){this.equations.sort(this.equationSortFunction)}};Solver.prototype.addEquation=function(eq){if(eq.enabled){this.equations.push(eq)}};Solver.prototype.addEquations=function(eqs){for(var i=0,N=eqs.length;i!==N;i++){var eq=eqs[i];if(eq.enabled){this.equations.push(eq)}}};Solver.prototype.removeEquation=function(eq){var i=this.equations.indexOf(eq);if(i!==-1){this.equations.splice(i,1)}};Solver.prototype.removeAllEquations=function(){this.equations.length=0};Solver.GS=1;Solver.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":47}],45:[function(require,module,exports){var TupleDictionary=require("./TupleDictionary");var Utils=require("./Utils");module.exports=OverlapKeeper;function OverlapKeeper(){this.overlappingLastState=new TupleDictionary;this.overlappingCurrentState=new TupleDictionary;this.recordPool=[];this.tmpDict=new TupleDictionary;this.tmpArray1=[]}OverlapKeeper.prototype.tick=function(){var last=this.overlappingLastState;var current=this.overlappingCurrentState;var l=current.keys.length;while(l--){var key=current.keys[l];this.recordPool.push(current.getByKey(key))}last.reset();last.copy(current);current.reset()};OverlapKeeper.prototype.setOverlapping=function(bodyA,shapeA,bodyB,shapeB){var last=this.overlappingLastState;var current=this.overlappingCurrentState;if(!current.get(shapeA.id,shapeB.id)){var data;if(this.recordPool.length){data=this.recordPool.pop()}else{data=new OverlapKeeperRecord(bodyA,shapeA,bodyB,shapeB)}current.set(shapeA.id,shapeB.id,data)}};OverlapKeeper.prototype.getNewOverlaps=function(result){return this.getDiff(this.overlappingLastState,this.overlappingCurrentState,result)};OverlapKeeper.prototype.getEndOverlaps=function(result){return this.getDiff(this.overlappingCurrentState,this.overlappingLastState,result)};OverlapKeeper.prototype.getDiff=function(dictA,dictB,result){var result=result||[];var last=dictA;var current=dictB;result.length=0;var l=current.keys.length;while(l--){var key=current.keys[l];var data=current.data[key];if(!data){throw new Error("Key "+key+" had no data!")}var lastData=last.data[key];if(!lastData){result.push(data)}}return result};OverlapKeeper.prototype.isNewOverlap=function(shapeA,shapeB){var idA=shapeA.id|0,idB=shapeB.id|0;return!!!this.overlappingLastState.get(idA,idB)&&!!this.overlappingCurrentState.get(idA,idB)};OverlapKeeper.prototype.getNewBodyOverlaps=function(result){this.tmpArray1.length=0;var overlaps=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(overlaps,result)};OverlapKeeper.prototype.getEndBodyOverlaps=function(result){this.tmpArray1.length=0;var overlaps=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(overlaps,result)};OverlapKeeper.prototype.getBodyDiff=function(overlaps,result){result=result||[];var accumulator=this.tmpDict;var l=overlaps.length;while(l--){var data=overlaps[l];accumulator.set(data.bodyA.id|0,data.bodyB.id|0,data)}l=accumulator.keys.length;while(l--){var data=accumulator.keys[l];result.push(data.bodyA,data.bodyB)}accumulator.reset();return result};function OverlapKeeperRecord(bodyA,shapeA,bodyB,shapeB){this.shapeA=shapeA;this.shapeB=shapeB;this.bodyA=bodyA;this.bodyB=bodyB}OverlapKeeperRecord.prototype.set=function(bodyA,shapeA,bodyB,shapeB){OverlapKeeperRecord.call(this,bodyA,shapeA,bodyB,shapeB)}},{"./TupleDictionary":46,"./Utils":47}],46:[function(require,module,exports){var Utils=require("./Utils");module.exports=TupleDictionary;function TupleDictionary(){this.data=[];this.keys=[]}TupleDictionary.prototype.getKey=function(id1,id2){id1=id1|0;id2=id2|0;if((id1|0)===(id2|0)){return-1}return((id1|0)>(id2|0)?id1<<16|id2&65535:id2<<16|id1&65535)|0};TupleDictionary.prototype.getByKey=function(key){key=key|0;return this.data[key]};TupleDictionary.prototype.get=function(i,j){i=i|0;j=j|0;var key=this.getKey(i,j)|0;return this.data[key]};TupleDictionary.prototype.set=function(i,j,value){if(!value){throw new Error("No data!")}i=i|0;j=j|0;var key=this.getKey(i,j)|0;if(!this.get(i,j)){this.keys.push(key)}this.data[key]=value;return key};TupleDictionary.prototype.reset=function(){var data=this.data,keys=this.keys;var l=keys.length|0;while(l--){var key=keys[l]|0;data[key]=undefined}keys.length=0};TupleDictionary.prototype.copy=function(dict){this.reset();Utils.appendArray(this.keys,dict.keys);var l=dict.keys.length|0;while(l--){var key=dict.keys[l]|0;this.data[key]=dict.data[key]}}},{"./Utils":47}],47:[function(require,module,exports){module.exports=Utils;function Utils(){}Utils.appendArray=function(a,b){if(b.length<15e4){a.push.apply(a,b)}else{for(var i=0,len=b.length;i!==len;++i){a.push(b[i])}}};Utils.splice=function(array,index,howmany){howmany=howmany||1;for(var i=index,len=array.length-howmany;i=0;i-=2){for(var j=result.length-2;j>=0;j-=2){if(ignoredPairs[i]===result[j]&&ignoredPairs[i+1]===result[j+1]||ignoredPairs[i+1]===result[j]&&ignoredPairs[i]===result[j+1]){result.splice(j,2)}}}var Nconstraints=constraints.length;for(i=0;i!==Nconstraints;i++){var c=constraints[i];if(!c.collideConnected){for(var j=result.length-2;j>=0;j-=2){if(c.bodyA===result[j]&&c.bodyB===result[j+1]||c.bodyB===result[j]&&c.bodyA===result[j+1]){result.splice(j,2)}}}}this.postBroadphaseEvent.pairs=result;this.emit(this.postBroadphaseEvent);np.reset(this);for(var i=0,Nresults=result.length;i!==Nresults;i+=2){var bi=result[i],bj=result[i+1];for(var k=0,Nshapesi=bi.shapes.length;k!==Nshapesi;k++){var si=bi.shapes[k],xi=bi.shapeOffsets[k],ai=bi.shapeAngles[k];for(var l=0,Nshapesj=bj.shapes.length;l!==Nshapesj;l++){var sj=bj.shapes[l],xj=bj.shapeOffsets[l],aj=bj.shapeAngles[l];var cm=this.defaultContactMaterial;if(si.material&&sj.material){var tmp=this.getContactMaterial(si.material,sj.material);if(tmp){cm=tmp}}this.runNarrowphase(np,bi,si,xi,ai,bj,sj,xj,aj,cm,this.frictionGravity)}}}for(var i=0;i!==Nbodies;i++){var body=bodies[i];if(body._wakeUpAfterNarrowphase){body.wakeUp();body._wakeUpAfterNarrowphase=false}}if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(endOverlaps);var e=this.endContactEvent;var l=endOverlaps.length;while(l--){var data=endOverlaps[l];e.shapeA=data.shapeA;e.shapeB=data.shapeB;e.bodyA=data.bodyA;e.bodyB=data.bodyA;this.emit(e)}}this.overlapKeeper.tick();var preSolveEvent=this.preSolveEvent;preSolveEvent.contactEquations=np.contactEquations;preSolveEvent.frictionEquations=np.frictionEquations;this.emit(preSolveEvent);var Nconstraints=constraints.length;for(i=0;i!==Nconstraints;i++){constraints[i].update()}if(np.contactEquations.length||np.frictionEquations.length||constraints.length){if(this.islandSplit){islandManager.equations.length=0;Utils.appendArray(islandManager.equations,np.contactEquations);Utils.appendArray(islandManager.equations,np.frictionEquations);for(i=0;i!==Nconstraints;i++){Utils.appendArray(islandManager.equations,constraints[i].equations)}islandManager.split(this);for(var i=0;i!==islandManager.islands.length;i++){var island=islandManager.islands[i];if(island.equations.length){solver.solveIsland(dt,island)}}}else{solver.addEquations(np.contactEquations);solver.addEquations(np.frictionEquations);for(i=0;i!==Nconstraints;i++){solver.addEquations(constraints[i].equations)}if(this.solveConstraints){solver.solve(dt,this)}solver.removeAllEquations()}}for(var i=0;i!==Nbodies;i++){var body=bodies[i];if(body.sleepState!==Body.SLEEPING&&body.motionState!==Body.STATIC){World.integrateBody(body,dt)}}for(var i=0;i!==Nbodies;i++){bodies[i].setZeroForce()}if(doProfiling){t1=performance.now();that.lastStepTime=t1-t0}if(this.emitImpactEvent&&this.has("impact")){var ev=this.impactEvent;for(var i=0;i!==np.contactEquations.length;i++){var eq=np.contactEquations[i];if(eq.firstImpact){ev.bodyA=eq.bodyA;ev.bodyB=eq.bodyB;ev.shapeA=eq.shapeA;ev.shapeB=eq.shapeB;ev.contactEquation=eq;this.emit(ev)}}}if(this.enableBodySleeping){for(i=0;i!==Nbodies;i++){bodies[i].sleepTick(this.time,false,dt)}}else if(this.enableIslandSleeping&&this.islandSplit){for(i=0;i!==Nbodies;i++){bodies[i].sleepTick(this.time,true,dt)}for(var i=0;i0;np.frictionCoefficient=cm.friction;var reducedMass;if(bi.motionState===Body.STATIC||bi.motionState===Body.KINEMATIC){reducedMass=bj.mass}else if(bj.motionState===Body.STATIC||bj.motionState===Body.KINEMATIC){reducedMass=bi.mass}else{reducedMass=bi.mass*bj.mass/(bi.mass+bj.mass)}np.slipForce=cm.friction*glen*reducedMass;np.restitution=cm.restitution;np.surfaceVelocity=cm.surfaceVelocity;np.frictionStiffness=cm.frictionStiffness;np.frictionRelaxation=cm.frictionRelaxation;np.stiffness=cm.stiffness;np.relaxation=cm.relaxation;var resolver=np[si.type|sj.type],numContacts=0;if(resolver){var sensor=si.sensor||sj.sensor;var numFrictionBefore=np.frictionEquations.length;if(si.type=speedLimitSquaredB*2){bi._wakeUpAfterNarrowphase=true}}if(bj.allowSleep&&bj.motionState===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&bi.sleepState===Body.AWAKE&&bi.motionState!==Body.STATIC){var speedSquaredA=vec2.squaredLength(bi.velocity)+Math.pow(bi.angularVelocity,2);var speedLimitSquaredA=Math.pow(bi.sleepSpeedLimit,2);if(speedSquaredA>=speedLimitSquaredA*2){bj._wakeUpAfterNarrowphase=true}}this.overlapKeeper.setOverlapping(bi,si,bj,sj);if(this.has("beginContact")&&this.overlapKeeper.isNewOverlap(si,sj)){var e=this.beginContactEvent;e.shapeA=si;e.shapeB=sj;e.bodyA=bi;e.bodyB=bj;e.contactEquations.length=0;if(typeof numContacts==="number"){for(var i=np.contactEquations.length-numContacts;i1){for(var i=np.frictionEquations.length-numFrictionEquations;i=0;i--){this.removeConstraint(cs[i])}var bodies=this.bodies;for(var i=bodies.length-1;i>=0;i--){this.removeBody(bodies[i])}var springs=this.springs;for(var i=springs.length-1;i>=0;i--){this.removeSpring(springs[i])}var cms=this.contactMaterials;for(var i=cms.length-1;i>=0;i--){this.removeContactMaterial(cms[i])}World.apply(this)};World.prototype.clone=function(){var world=new World;world.fromJSON(this.toJSON());return world};var hitTest_tmp1=vec2.create(),hitTest_zero=vec2.fromValues(0,0),hitTest_tmp2=vec2.fromValues(0,0);World.prototype.hitTest=function(worldPoint,bodies,precision){precision=precision||0;var pb=new Body({position:worldPoint}),ps=new Particle,px=worldPoint,pa=0,x=hitTest_tmp1,zero=hitTest_zero,tmp=hitTest_tmp2;pb.addShape(ps);var n=this.narrowphase,result=[];for(var i=0,N=bodies.length;i!==N;i++){var b=bodies[i];for(var j=0,NS=b.shapes.length;j!==NS;j++){var s=b.shapes[j],offset=b.shapeOffsets[j]||zero,angle=b.shapeAngles[j]||0;vec2.rotate(x,offset,b.angle);vec2.add(x,x,b.position);var a=angle+b.angle;if(s instanceof Circle&&n.circleParticle(b,s,x,a,pb,ps,px,pa,true)||s instanceof Convex&&n.particleConvex(pb,ps,px,pa,b,s,x,a,true)||s instanceof Plane&&n.particlePlane(pb,ps,px,pa,b,s,x,a,true)||s instanceof Capsule&&n.particleCapsule(pb,ps,px,pa,b,s,x,a,true)||s instanceof Particle&&vec2.squaredLength(vec2.sub(tmp,x,worldPoint))0){this.enable(object[i],debug,true)}}}}else{if(object instanceof Phaser.Group){this.enable(object.children,debug,children)}else{this.enableBody(object,debug);if(children&&object.hasOwnProperty("children")&&object.children.length>0){this.enable(object.children,debug,true)}}}},enableBody:function(object,debug){if(object.hasOwnProperty("body")&&object.body===null){object.body=new Phaser.Physics.P2.Body(this.game,object,object.x,object.y,1);object.body.debug=debug; object.anchor.set(.5)}},setImpactEvents:function(state){if(state){this.world.on("impact",this.impactHandler,this)}else{this.world.off("impact",this.impactHandler,this)}},setPostBroadphaseCallback:function(callback,context){this.postBroadphaseCallback=callback;this.callbackContext=context;if(callback!==null){this.world.on("postBroadphase",this.postBroadphaseHandler,this)}else{this.world.off("postBroadphase",this.postBroadphaseHandler,this)}},postBroadphaseHandler:function(event){if(this.postBroadphaseCallback){var i=event.pairs.length;while(i-=2){if(event.pairs[i].parent&&event.pairs[i+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,event.pairs[i].parent,event.pairs[i+1].parent)){event.pairs.splice(i,2)}}}},impactHandler:function(event){if(event.bodyA.parent&&event.bodyB.parent){var a=event.bodyA.parent;var b=event.bodyB.parent;if(a._bodyCallbacks[event.bodyB.id]){a._bodyCallbacks[event.bodyB.id].call(a._bodyCallbackContext[event.bodyB.id],a,b,event.shapeA,event.shapeB)}if(b._bodyCallbacks[event.bodyA.id]){b._bodyCallbacks[event.bodyA.id].call(b._bodyCallbackContext[event.bodyA.id],b,a,event.shapeB,event.shapeA)}if(a._groupCallbacks[event.shapeB.collisionGroup]){a._groupCallbacks[event.shapeB.collisionGroup].call(a._groupCallbackContext[event.shapeB.collisionGroup],a,b,event.shapeA,event.shapeB)}if(b._groupCallbacks[event.shapeA.collisionGroup]){b._groupCallbacks[event.shapeA.collisionGroup].call(b._groupCallbackContext[event.shapeA.collisionGroup],b,a,event.shapeB,event.shapeA)}}},beginContactHandler:function(event){this.onBeginContact.dispatch(event.bodyA,event.bodyB,event.shapeA,event.shapeB,event.contactEquations);if(event.bodyA.parent){event.bodyA.parent.onBeginContact.dispatch(event.bodyB.parent,event.shapeA,event.shapeB,event.contactEquations)}if(event.bodyB.parent){event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent,event.shapeB,event.shapeA,event.contactEquations)}},endContactHandler:function(event){this.onEndContact.dispatch(event.bodyA,event.bodyB,event.shapeA,event.shapeB);if(event.bodyA.parent){event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent,event.shapeA,event.shapeB)}if(event.bodyB.parent){event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent,event.shapeB,event.shapeA)}},setBoundsToWorld:function(left,right,top,bottom,setCollisionGroup){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,left,right,top,bottom,setCollisionGroup)},setWorldMaterial:function(material,left,right,top,bottom){if(typeof left==="undefined"){left=true}if(typeof right==="undefined"){right=true}if(typeof top==="undefined"){top=true}if(typeof bottom==="undefined"){bottom=true}if(left&&this.walls.left){this.walls.left.shapes[0].material=material}if(right&&this.walls.right){this.walls.right.shapes[0].material=material}if(top&&this.walls.top){this.walls.top.shapes[0].material=material}if(bottom&&this.walls.bottom){this.walls.bottom.shapes[0].material=material}},updateBoundsCollisionGroup:function(setCollisionGroup){var mask=this.everythingCollisionGroup.mask;if(typeof setCollisionGroup==="undefined"){mask=this.boundsCollisionGroup.mask}if(this.walls.left){this.walls.left.shapes[0].collisionGroup=mask}if(this.walls.right){this.walls.right.shapes[0].collisionGroup=mask}if(this.walls.top){this.walls.top.shapes[0].collisionGroup=mask}if(this.walls.bottom){this.walls.bottom.shapes[0].collisionGroup=mask}},setBounds:function(x,y,width,height,left,right,top,bottom,setCollisionGroup){if(typeof left==="undefined"){left=true}if(typeof right==="undefined"){right=true}if(typeof top==="undefined"){top=true}if(typeof bottom==="undefined"){bottom=true}if(typeof setCollisionGroup==="undefined"){setCollisionGroup=true}if(this.walls.left){this.world.removeBody(this.walls.left)}if(this.walls.right){this.world.removeBody(this.walls.right)}if(this.walls.top){this.world.removeBody(this.walls.top)}if(this.walls.bottom){this.world.removeBody(this.walls.bottom)}if(left){this.walls.left=new p2.Body({mass:0,position:[this.pxmi(x),this.pxmi(y)],angle:1.5707963267948966});this.walls.left.addShape(new p2.Plane);if(setCollisionGroup){this.walls.left.shapes[0].collisionGroup=this.boundsCollisionGroup.mask}this.world.addBody(this.walls.left)}if(right){this.walls.right=new p2.Body({mass:0,position:[this.pxmi(x+width),this.pxmi(y)],angle:-1.5707963267948966});this.walls.right.addShape(new p2.Plane);if(setCollisionGroup){this.walls.right.shapes[0].collisionGroup=this.boundsCollisionGroup.mask}this.world.addBody(this.walls.right)}if(top){this.walls.top=new p2.Body({mass:0,position:[this.pxmi(x),this.pxmi(y)],angle:-3.141592653589793});this.walls.top.addShape(new p2.Plane);if(setCollisionGroup){this.walls.top.shapes[0].collisionGroup=this.boundsCollisionGroup.mask}this.world.addBody(this.walls.top)}if(bottom){this.walls.bottom=new p2.Body({mass:0,position:[this.pxmi(x),this.pxmi(height)]});this.walls.bottom.addShape(new p2.Plane);if(setCollisionGroup){this.walls.bottom.shapes[0].collisionGroup=this.boundsCollisionGroup.mask}this.world.addBody(this.walls.bottom)}},pause:function(){this.paused=true},resume:function(){this.paused=false},update:function(){if(this.paused){return}if(this.useElapsedTime){this.world.step(this.game.time.physicsElapsed)}else{this.world.step(this.frameRate)}},clear:function(){this.world.clear();this.world.off("beginContact",this.beginContactHandler,this);this.world.off("endContact",this.endContactHandler,this);this.postBroadphaseCallback=null;this.callbackContext=null;this.impactCallback=null;this.collisionGroups=[];this._toRemove=[];this._collisionGroupID=2;this.boundsCollidesWith=[]},destroy:function(){this.clear();this.game=null},addBody:function(body){if(body.data.world){return false}else{this.world.addBody(body.data);this.onBodyAdded.dispatch(body);return true}},removeBody:function(body){if(body.data.world==this.world){this.world.removeBody(body.data);this.onBodyRemoved.dispatch(body)}return body},addSpring:function(spring){this.world.addSpring(spring);this.onSpringAdded.dispatch(spring);return spring},removeSpring:function(spring){this.world.removeSpring(spring);this.onSpringRemoved.dispatch(spring);return spring},createDistanceConstraint:function(bodyA,bodyB,distance,maxForce){bodyA=this.getBody(bodyA);bodyB=this.getBody(bodyB);if(!bodyA||!bodyB){console.warn("Cannot create Constraint, invalid body objects given")}else{return this.addConstraint(new Phaser.Physics.P2.DistanceConstraint(this,bodyA,bodyB,distance,maxForce))}},createGearConstraint:function(bodyA,bodyB,angle,ratio){bodyA=this.getBody(bodyA);bodyB=this.getBody(bodyB);if(!bodyA||!bodyB){console.warn("Cannot create Constraint, invalid body objects given")}else{return this.addConstraint(new Phaser.Physics.P2.GearConstraint(this,bodyA,bodyB,angle,ratio))}},createRevoluteConstraint:function(bodyA,pivotA,bodyB,pivotB,maxForce){bodyA=this.getBody(bodyA);bodyB=this.getBody(bodyB);if(!bodyA||!bodyB){console.warn("Cannot create Constraint, invalid body objects given")}else{return this.addConstraint(new Phaser.Physics.P2.RevoluteConstraint(this,bodyA,pivotA,bodyB,pivotB,maxForce))}},createLockConstraint:function(bodyA,bodyB,offset,angle,maxForce){bodyA=this.getBody(bodyA);bodyB=this.getBody(bodyB);if(!bodyA||!bodyB){console.warn("Cannot create Constraint, invalid body objects given")}else{return this.addConstraint(new Phaser.Physics.P2.LockConstraint(this,bodyA,bodyB,offset,angle,maxForce))}},createPrismaticConstraint:function(bodyA,bodyB,lockRotation,anchorA,anchorB,axis,maxForce){bodyA=this.getBody(bodyA);bodyB=this.getBody(bodyB);if(!bodyA||!bodyB){console.warn("Cannot create Constraint, invalid body objects given")}else{return this.addConstraint(new Phaser.Physics.P2.PrismaticConstraint(this,bodyA,bodyB,lockRotation,anchorA,anchorB,axis,maxForce))}},addConstraint:function(constraint){this.world.addConstraint(constraint);this.onConstraintAdded.dispatch(constraint);return constraint},removeConstraint:function(constraint){this.world.removeConstraint(constraint);this.onConstraintRemoved.dispatch(constraint);return constraint},addContactMaterial:function(material){this.world.addContactMaterial(material);this.onContactMaterialAdded.dispatch(material);return material},removeContactMaterial:function(material){this.world.removeContactMaterial(material);this.onContactMaterialRemoved.dispatch(material);return material},getContactMaterial:function(materialA,materialB){return this.world.getContactMaterial(materialA,materialB)},setMaterial:function(material,bodies){var i=bodies.length;while(i--){bodies[i].setMaterial(material)}},createMaterial:function(name,body){name=name||"";var material=new Phaser.Physics.P2.Material(name);this.materials.push(material);if(typeof body!=="undefined"){body.setMaterial(material)}return material},createContactMaterial:function(materialA,materialB,options){if(typeof materialA==="undefined"){materialA=this.createMaterial()}if(typeof materialB==="undefined"){materialB=this.createMaterial()}var contact=new Phaser.Physics.P2.ContactMaterial(materialA,materialB,options);return this.addContactMaterial(contact)},getBodies:function(){var output=[];var i=this.world.bodies.length;while(i--){output.push(this.world.bodies[i].parent)}return output},getBody:function(object){if(object instanceof p2.Body){return object}else if(object instanceof Phaser.Physics.P2.Body){return object.data}else if(object["body"]&&object["body"].type===Phaser.Physics.P2JS){return object.body.data}return null},getSprings:function(){var output=[];var i=this.world.springs.length;while(i--){output.push(this.world.springs[i].parent)}return output},getConstraints:function(){var output=[];var i=this.world.constraints.length;while(i--){output.push(this.world.constraints[i].parent)}return output},hitTest:function(worldPoint,bodies,precision,filterStatic){if(typeof bodies==="undefined"){bodies=this.world.bodies}if(typeof precision==="undefined"){precision=5}if(typeof filterStatic==="undefined"){filterStatic=false}var physicsPosition=[this.pxmi(worldPoint.x),this.pxmi(worldPoint.y)];var query=[];var i=bodies.length;while(i--){if(bodies[i]instanceof Phaser.Physics.P2.Body&&!(filterStatic&&bodies[i].data.motionState===p2.Body.STATIC)){query.push(bodies[i].data)}else if(bodies[i]instanceof p2.Body&&bodies[i].parent&&!(filterStatic&&bodies[i].motionState===p2.Body.STATIC)){query.push(bodies[i])}else if(bodies[i]instanceof Phaser.Sprite&&bodies[i].hasOwnProperty("body")&&!(filterStatic&&bodies[i].body.data.motionState===p2.Body.STATIC)){query.push(bodies[i].body.data)}}return this.world.hitTest(physicsPosition,query,precision)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(object){var bitmask=Math.pow(2,this._collisionGroupID);if(this.walls.left){this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|bitmask}if(this.walls.right){this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|bitmask}if(this.walls.top){this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|bitmask}if(this.walls.bottom){this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|bitmask}this._collisionGroupID++;var group=new Phaser.Physics.P2.CollisionGroup(bitmask);this.collisionGroups.push(group);if(object){this.setCollisionGroup(object,group)}return group},setCollisionGroup:function(object,group){if(object instanceof Phaser.Group){for(var i=0;i-1&&tile.collides){if(optimize){var right=map.getTileRight(layer,x,y);if(width===0){sx=tile.x*tile.width;sy=tile.y*tile.height;width=tile.width}if(right&&right.collides){width+=tile.width}else{var body=this.createBody(sx,sy,0,false);body.addRectangle(width,tile.height,width/2,tile.height/2,0);if(addToWorld){this.addBody(body)}map.layers[layer].bodies.push(body);width=0}}else{var body=this.createBody(tile.x*tile.width,tile.y*tile.height,0,false);body.addRectangle(tile.width,tile.height,tile.width/2,tile.height/2,0);if(addToWorld){this.addBody(body)}map.layers[layer].bodies.push(body)}}}}return map.layers[layer].bodies},mpx:function(v){return v*=20},pxm:function(v){return v*.05},mpxi:function(v){return v*=-20},pxmi:function(v){return v*-.05}};Object.defineProperty(Phaser.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(value){this.world.defaultContactMaterial.friction=value}});Object.defineProperty(Phaser.Physics.P2.prototype,"defaultFriction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(value){this.world.defaultContactMaterial.friction=value}});Object.defineProperty(Phaser.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(value){this.world.defaultContactMaterial.restitution=value}});Object.defineProperty(Phaser.Physics.P2.prototype,"defaultRestitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(value){this.world.defaultContactMaterial.restitution=value}});Object.defineProperty(Phaser.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(value){this.world.defaultContactMaterial=value}});Object.defineProperty(Phaser.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(value){this.world.applySpringForces=value}});Object.defineProperty(Phaser.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(value){this.world.applyDamping=value}});Object.defineProperty(Phaser.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(value){this.world.applyGravity=value}});Object.defineProperty(Phaser.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(value){this.world.solveConstraints=value}});Object.defineProperty(Phaser.Physics.P2.prototype,"time",{get:function(){return this.world.time}});Object.defineProperty(Phaser.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(value){this.world.emitImpactEvent=value}});Object.defineProperty(Phaser.Physics.P2.prototype,"enableBodySleeping",{get:function(){return this.world.enableBodySleeping},set:function(value){this.world.enableBodySleeping=value}});Object.defineProperty(Phaser.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}});Phaser.Physics.P2.FixtureList=function(list){if(!Array.isArray(list)){list=[list]}this.rawList=list;this.init();this.parse(this.rawList)};Phaser.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={};this.groupedFixtures=[];this.allFixtures=[]},setCategory:function(bit,fixtureKey){var setter=function(fixture){fixture.collisionGroup=bit};this.getFixtures(fixtureKey).forEach(setter)},setMask:function(bit,fixtureKey){var setter=function(fixture){fixture.collisionMask=bit};this.getFixtures(fixtureKey).forEach(setter)},setSensor:function(value,fixtureKey){var setter=function(fixture){fixture.sensor=value};this.getFixtures(fixtureKey).forEach(setter)},setMaterial:function(material,fixtureKey){var setter=function(fixture){fixture.material=material};this.getFixtures(fixtureKey).forEach(setter)},getFixtures:function(keys){var fixtures=[];if(keys){if(!(keys instanceof Array)){keys=[keys]}var self=this;keys.forEach(function(key){if(self.namedFixtures[key]){fixtures.push(self.namedFixtures[key])}});return this.flatten(fixtures)}else{return this.allFixtures}},getFixtureByKey:function(key){return this.namedFixtures[key]},getGroup:function(groupID){return this.groupedFixtures[groupID]},parse:function(){var key,value,_ref,_results;_ref=this.rawList;_results=[];for(key in _ref){value=_ref[key];if(!isNaN(key-0)){this.groupedFixtures[key]=this.groupedFixtures[key]||[];this.groupedFixtures[key]=this.groupedFixtures[key].concat(value)}else{this.namedFixtures[key]=this.flatten(value)}_results.push(this.allFixtures=this.flatten(this.groupedFixtures))}},flatten:function(array){var result,self;result=[];self=arguments.callee;array.forEach(function(item){return Array.prototype.push.apply(result,Array.isArray(item)?self(item):[item])});return result}};Phaser.Physics.P2.PointProxy=function(world,destination){this.world=world;this.destination=destination};Phaser.Physics.P2.PointProxy.prototype.constructor=Phaser.Physics.P2.PointProxy;Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.destination[0]},set:function(value){this.destination[0]=this.world.pxm(value)}});Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.destination[1]},set:function(value){this.destination[1]=this.world.pxm(value)}});Phaser.Physics.P2.InversePointProxy=function(world,destination){this.world=world;this.destination=destination};Phaser.Physics.P2.InversePointProxy.prototype.constructor=Phaser.Physics.P2.InversePointProxy;Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.destination[0]},set:function(value){this.destination[0]=this.world.pxm(-value)}});Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.destination[1]},set:function(value){this.destination[1]=this.world.pxm(-value)}});Phaser.Physics.P2.Body=function(game,sprite,x,y,mass){sprite=sprite||null;x=x||0;y=y||0;if(typeof mass==="undefined"){mass=1}this.game=game;this.world=game.physics.p2;this.sprite=sprite;this.type=Phaser.Physics.P2JS;this.offset=new Phaser.Point;this.data=new p2.Body({position:[this.world.pxmi(x),this.world.pxmi(y)],mass:mass});this.data.parent=this;this.velocity=new Phaser.Physics.P2.InversePointProxy(this.world,this.data.velocity);this.force=new Phaser.Physics.P2.InversePointProxy(this.world,this.data.force);this.gravity=new Phaser.Point;this.onBeginContact=new Phaser.Signal;this.onEndContact=new Phaser.Signal;this.collidesWith=[];this.removeNextStep=false;this.debugBody=null;this._collideWorldBounds=true;this._bodyCallbacks={};this._bodyCallbackContext={};this._groupCallbacks={};this._groupCallbackContext={};if(sprite){this.setRectangleFromSprite(sprite);if(sprite.exists){this.game.physics.p2.addBody(this)}}};Phaser.Physics.P2.Body.prototype={createBodyCallback:function(object,callback,callbackContext){var id=-1;if(object["id"]){id=object.id}else if(object["body"]){id=object.body.id}if(id>-1){if(callback===null){delete this._bodyCallbacks[id];delete this._bodyCallbackContext[id]}else{this._bodyCallbacks[id]=callback;this._bodyCallbackContext[id]=callbackContext}}},createGroupCallback:function(group,callback,callbackContext){if(callback===null){delete this._groupCallbacks[group.mask];delete this._groupCallbacksContext[group.mask]}else{this._groupCallbacks[group.mask]=callback;this._groupCallbackContext[group.mask]=callbackContext}},getCollisionMask:function(){var mask=0;if(this._collideWorldBounds){mask=this.game.physics.p2.boundsCollisionGroup.mask}for(var i=0;i=0;i--){this.data.shapes[i].collisionMask=mask}}else{shape.collisionMask=mask}},setCollisionGroup:function(group,shape){var mask=this.getCollisionMask();if(typeof shape==="undefined"){for(var i=this.data.shapes.length-1;i>=0;i--){this.data.shapes[i].collisionGroup=group.mask;this.data.shapes[i].collisionMask=mask}}else{shape.collisionGroup=group.mask;shape.collisionMask=mask}},clearCollision:function(clearGroup,clearMask,shape){if(typeof shape==="undefined"){for(var i=this.data.shapes.length-1;i>=0;i--){if(clearGroup){this.data.shapes[i].collisionGroup=null}if(clearMask){this.data.shapes[i].collisionMask=null}}}else{if(clearGroup){shape.collisionGroup=null}if(clearMask){shape.collisionMask=null}}if(clearGroup){this.collidesWith.length=0}},collides:function(group,callback,callbackContext,shape){if(Array.isArray(group)){for(var i=0;i=0;i--){this.data.shapes[i].collisionMask=mask}}else{shape.collisionMask=mask}},adjustCenterOfMass:function(){this.data.adjustCenterOfMass()},applyDamping:function(dt){this.data.applyDamping(dt)},applyForce:function(force,worldX,worldY){this.data.applyForce(force,[this.world.pxmi(worldX),this.world.pxmi(worldY)])},setZeroForce:function(){this.data.setZeroForce()},setZeroRotation:function(){this.data.angularVelocity=0},setZeroVelocity:function(){this.data.velocity[0]=0;this.data.velocity[1]=0},setZeroDamping:function(){this.data.damping=0;this.data.angularDamping=0},toLocalFrame:function(out,worldPoint){return this.data.toLocalFrame(out,worldPoint)},toWorldFrame:function(out,localPoint){return this.data.toWorldFrame(out,localPoint)},rotateLeft:function(speed){this.data.angularVelocity=this.world.pxm(-speed)},rotateRight:function(speed){this.data.angularVelocity=this.world.pxm(speed)},moveForward:function(speed){var magnitude=this.world.pxmi(-speed);var angle=this.data.angle+Math.PI/2;this.data.velocity[0]=magnitude*Math.cos(angle);this.data.velocity[1]=magnitude*Math.sin(angle)},moveBackward:function(speed){var magnitude=this.world.pxmi(-speed);var angle=this.data.angle+Math.PI/2;this.data.velocity[0]=-(magnitude*Math.cos(angle));this.data.velocity[1]=-(magnitude*Math.sin(angle))},thrust:function(speed){var magnitude=this.world.pxmi(-speed);var angle=this.data.angle+Math.PI/2;this.data.force[0]+=magnitude*Math.cos(angle);this.data.force[1]+=magnitude*Math.sin(angle)},reverse:function(speed){var magnitude=this.world.pxmi(-speed);var angle=this.data.angle+Math.PI/2;this.data.force[0]-=magnitude*Math.cos(angle);this.data.force[1]-=magnitude*Math.sin(angle)},moveLeft:function(speed){this.data.velocity[0]=this.world.pxmi(-speed)},moveRight:function(speed){this.data.velocity[0]=this.world.pxmi(speed)},moveUp:function(speed){this.data.velocity[1]=this.world.pxmi(-speed)},moveDown:function(speed){this.data.velocity[1]=this.world.pxmi(speed)},preUpdate:function(){if(this.removeNextStep){this.removeFromWorld();this.removeNextStep=false}},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0]);this.sprite.y=this.world.mpxi(this.data.position[1]);if(!this.fixedRotation){this.sprite.rotation=this.data.angle}},reset:function(x,y,resetDamping,resetMass){if(typeof resetDamping==="undefined"){resetDamping=false}if(typeof resetMass==="undefined"){resetMass=false}this.setZeroForce();this.setZeroVelocity();this.setZeroRotation();if(resetDamping){this.setZeroDamping()}if(resetMass){this.mass=1}this.x=x;this.y=y},addToWorld:function(){if(this.data.world!==this.game.physics.p2.world){this.game.physics.p2.addBody(this)}},removeFromWorld:function(){if(this.data.world===this.game.physics.p2.world){this.game.physics.p2.removeBodyNextStep(this)}},destroy:function(){this.removeFromWorld();this.clearShapes();this._bodyCallbacks={};this._bodyCallbackContext={};this._groupCallbacks={};this._groupCallbackContext={};if(this.debugBody){this.debugBody.destroy()}this.debugBody=null;this.sprite=null},clearShapes:function(){var i=this.data.shapes.length;while(i--){this.data.removeShape(this.data.shapes[i])}this.shapeChanged()},addShape:function(shape,offsetX,offsetY,rotation){if(typeof offsetX==="undefined"){offsetX=0}if(typeof offsetY==="undefined"){offsetY=0}if(typeof rotation==="undefined"){rotation=0}this.data.addShape(shape,[this.world.pxmi(offsetX),this.world.pxmi(offsetY)],rotation);this.shapeChanged();return shape},addCircle:function(radius,offsetX,offsetY,rotation){var shape=new p2.Circle(this.world.pxm(radius));return this.addShape(shape,offsetX,offsetY,rotation)},addRectangle:function(width,height,offsetX,offsetY,rotation){var shape=new p2.Rectangle(this.world.pxm(width),this.world.pxm(height));return this.addShape(shape,offsetX,offsetY,rotation)},addPlane:function(offsetX,offsetY,rotation){var shape=new p2.Plane;return this.addShape(shape,offsetX,offsetY,rotation)},addParticle:function(offsetX,offsetY,rotation){var shape=new p2.Particle;return this.addShape(shape,offsetX,offsetY,rotation)},addLine:function(length,offsetX,offsetY,rotation){var shape=new p2.Line(this.world.pxm(length));return this.addShape(shape,offsetX,offsetY,rotation)},addCapsule:function(length,radius,offsetX,offsetY,rotation){var shape=new p2.Capsule(this.world.pxm(length),radius);return this.addShape(shape,offsetX,offsetY,rotation)},addPolygon:function(options,points){options=options||{};points=Array.prototype.slice.call(arguments,1);var path=[];if(points.length===1&&Array.isArray(points[0])){path=points[0].slice(0)}else if(Array.isArray(points[0])){path=points[0].slice(0)}else if(typeof points[0]==="number"){for(var i=0,len=points.length;i=0;i--){this.data.shapes[i].material=material}}else{shape.material=material}},shapeChanged:function(){if(this.debugBody){this.debugBody.draw()}},addPhaserPolygon:function(key,object){var data=this.game.cache.getPhysicsData(key,object);var createdFixtures=[];for(var i=0;i_ref1;j=0<=_ref1?++_j:--_j){v=child.vertices[j];p2.vec2.rotate(vrot,v,angle);verts.push([(vrot[0]+offset[0])*this.ppu,-(vrot[1]+offset[1])*this.ppu])}this.drawConvex(sprite,verts,child.triangles,lineColor,color,lw,this.settings.debugPolygons,[offset[0]*this.ppu,-offset[1]*this.ppu])}else if(child instanceof p2.Plane){this.drawPlane(sprite,offset[0]*this.ppu,-offset[1]*this.ppu,color,lineColor,lw*5,lw*10,lw*10,this.ppu*100,angle)}else if(child instanceof p2.Line){this.drawLine(sprite,child.length*this.ppu,lineColor,lw)}else if(child instanceof p2.Rectangle){this.drawRectangle(sprite,offset[0]*this.ppu,-offset[1]*this.ppu,angle,child.width*this.ppu,child.height*this.ppu,lineColor,color,lw)}i++}}},drawRectangle:function(g,x,y,angle,w,h,color,fillColor,lineWidth){if(typeof lineWidth==="undefined"){lineWidth=1}if(typeof color==="undefined"){color=0}g.lineStyle(lineWidth,color,1);g.beginFill(fillColor);g.drawRect(x-w/2,y-h/2,w,h)},drawCircle:function(g,x,y,angle,radius,color,lineWidth){if(typeof lineWidth==="undefined"){lineWidth=1}if(typeof color==="undefined"){color=16777215}g.lineStyle(lineWidth,0,1);g.beginFill(color,1);g.drawCircle(x,y,-radius);g.endFill();g.moveTo(x,y);g.lineTo(x+radius*Math.cos(-angle),y+radius*Math.sin(-angle))},drawLine:function(g,len,color,lineWidth){if(typeof lineWidth==="undefined"){lineWidth=1}if(typeof color==="undefined"){color=0}g.lineStyle(lineWidth*5,color,1);g.moveTo(-len/2,0);g.lineTo(len/2,0)},drawConvex:function(g,verts,triangles,color,fillColor,lineWidth,debug,offset){var colors,i,v,v0,v1,x,x0,x1,y,y0,y1;if(typeof lineWidth==="undefined"){lineWidth=1}if(typeof color==="undefined"){color=0}if(!debug){g.lineStyle(lineWidth,color,1);g.beginFill(fillColor);i=0;while(i!==verts.length){v=verts[i];x=v[0];y=v[1];if(i===0){g.moveTo(x,-y)}else{g.lineTo(x,-y)}i++}g.endFill();if(verts.length>2){g.moveTo(verts[verts.length-1][0],-verts[verts.length-1][1]);return g.lineTo(verts[0][0],-verts[0][1])}}else{colors=[16711680,65280,255];i=0;while(i!==verts.length+1){v0=verts[i%verts.length];v1=verts[(i+1)%verts.length];x0=v0[0];y0=v0[1];x1=v1[0];y1=v1[1];g.lineStyle(lineWidth,colors[i%colors.length],1);g.moveTo(x0,-y0);g.lineTo(x1,-y1);g.drawCircle(x0,-y0,lineWidth*2);i++}g.lineStyle(lineWidth,0,1);return g.drawCircle(offset[0],offset[1],lineWidth*2)}},drawPath:function(g,path,color,fillColor,lineWidth){var area,i,lastx,lasty,p1x,p1y,p2x,p2y,p3x,p3y,v,x,y;if(typeof lineWidth==="undefined"){lineWidth=1}if(typeof color==="undefined"){color=0}g.lineStyle(lineWidth,color,1);if(typeof fillColor==="number"){g.beginFill(fillColor)}lastx=null;lasty=null;i=0;while(i2&&typeof fillColor==="number"){g.moveTo(path[path.length-1][0],path[path.length-1][1]);g.lineTo(path[0][0],path[0][1])}},drawPlane:function(g,x0,x1,color,lineColor,lineWidth,diagMargin,diagSize,maxLength,angle){var max,xd,yd;if(typeof lineWidth==="undefined"){lineWidth=1}if(typeof color==="undefined"){color=16777215}g.lineStyle(lineWidth,lineColor,11);g.beginFill(color);max=maxLength;g.moveTo(x0,-x1);xd=x0+Math.cos(angle)*this.game.width;yd=x1+Math.sin(angle)*this.game.height;g.lineTo(xd,-yd);g.moveTo(x0,-x1);xd=x0+Math.cos(angle)*-this.game.width;yd=x1+Math.sin(angle)*-this.game.height;g.lineTo(xd,-yd)},randomPastelHex:function(){var blue,green,mix,red;mix=[255,255,255];red=Math.floor(Math.random()*256);green=Math.floor(Math.random()*256);blue=Math.floor(Math.random()*256);red=Math.floor((red+3*mix[0])/4);green=Math.floor((green+3*mix[1])/4);blue=Math.floor((blue+3*mix[2])/4);return this.rgbToHex(red,green,blue)},rgbToHex:function(r,g,b){return this.componentToHex(r)+this.componentToHex(g)+this.componentToHex(b)},componentToHex:function(c){var hex;hex=c.toString(16);if(hex.len===2){return hex}else{return hex+"0"}}});Phaser.Physics.P2.Spring=function(world,bodyA,bodyB,restLength,stiffness,damping,worldA,worldB,localA,localB){this.game=world.game;this.world=world;if(typeof restLength==="undefined"){restLength=1}if(typeof stiffness==="undefined"){stiffness=100}if(typeof damping==="undefined"){damping=1}restLength=world.pxm(restLength);var options={restLength:restLength,stiffness:stiffness,damping:damping};if(typeof worldA!=="undefined"&&worldA!==null){options.worldAnchorA=[world.pxm(worldA[0]),world.pxm(worldA[1])]}if(typeof worldB!=="undefined"&&worldB!==null){options.worldAnchorB=[world.pxm(worldB[0]),world.pxm(worldB[1])]}if(typeof localA!=="undefined"&&localA!==null){options.localAnchorA=[world.pxm(localA[0]),world.pxm(localA[1])]}if(typeof localB!=="undefined"&&localB!==null){options.localAnchorB=[world.pxm(localB[0]),world.pxm(localB[1])]}p2.Spring.call(this,bodyA,bodyB,options)};Phaser.Physics.P2.Spring.prototype=Object.create(p2.Spring.prototype);Phaser.Physics.P2.Spring.prototype.constructor=Phaser.Physics.P2.Spring;Phaser.Physics.P2.Material=function(name){this.name=name;p2.Material.call(this)};Phaser.Physics.P2.Material.prototype=Object.create(p2.Material.prototype);Phaser.Physics.P2.Material.prototype.constructor=Phaser.Physics.P2.Material;Phaser.Physics.P2.ContactMaterial=function(materialA,materialB,options){p2.ContactMaterial.call(this,materialA,materialB,options)};Phaser.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype);Phaser.Physics.P2.ContactMaterial.prototype.constructor=Phaser.Physics.P2.ContactMaterial;Phaser.Physics.P2.CollisionGroup=function(bitmask){this.mask=bitmask};Phaser.Physics.P2.DistanceConstraint=function(world,bodyA,bodyB,distance,maxForce){if(typeof distance==="undefined"){distance=100}this.game=world.game;this.world=world;distance=world.pxm(distance);p2.DistanceConstraint.call(this,bodyA,bodyB,distance,{maxForce:maxForce})};Phaser.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype);Phaser.Physics.P2.DistanceConstraint.prototype.constructor=Phaser.Physics.P2.DistanceConstraint;Phaser.Physics.P2.GearConstraint=function(world,bodyA,bodyB,angle,ratio){if(typeof angle==="undefined"){angle=0}if(typeof ratio==="undefined"){ratio=1}this.game=world.game;this.world=world;var options={angle:angle,ratio:ratio};p2.GearConstraint.call(this,bodyA,bodyB,options)};Phaser.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype);Phaser.Physics.P2.GearConstraint.prototype.constructor=Phaser.Physics.P2.GearConstraint;Phaser.Physics.P2.LockConstraint=function(world,bodyA,bodyB,offset,angle,maxForce){if(typeof offset==="undefined"){offset=[0,0]}if(typeof angle==="undefined"){angle=0}if(typeof maxForce==="undefined"){maxForce=Number.MAX_VALUE}this.game=world.game;this.world=world;offset=[world.pxm(offset[0]),world.pxm(offset[1])];var options={localOffsetB:offset,localAngleB:angle,maxForce:maxForce};p2.LockConstraint.call(this,bodyA,bodyB,options)};Phaser.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype);Phaser.Physics.P2.LockConstraint.prototype.constructor=Phaser.Physics.P2.LockConstraint;Phaser.Physics.P2.PrismaticConstraint=function(world,bodyA,bodyB,lockRotation,anchorA,anchorB,axis,maxForce){if(typeof lockRotation==="undefined"){lockRotation=true}if(typeof anchorA==="undefined"){anchorA=[0,0]}if(typeof anchorB==="undefined"){anchorB=[0,0]}if(typeof axis==="undefined"){axis=[0,0]}if(typeof maxForce==="undefined"){maxForce=Number.MAX_VALUE}this.game=world.game;this.world=world;anchorA=[world.pxmi(anchorA[0]),world.pxmi(anchorA[1])];anchorB=[world.pxmi(anchorB[0]),world.pxmi(anchorB[1])];var options={localAnchorA:anchorA,localAnchorB:anchorB,localAxisA:axis,maxForce:maxForce,disableRotationalLock:!lockRotation};p2.PrismaticConstraint.call(this,bodyA,bodyB,options)};Phaser.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype);Phaser.Physics.P2.PrismaticConstraint.prototype.constructor=Phaser.Physics.P2.PrismaticConstraint;Phaser.Physics.P2.RevoluteConstraint=function(world,bodyA,pivotA,bodyB,pivotB,maxForce){if(typeof maxForce==="undefined"){maxForce=Number.MAX_VALUE}this.game=world.game;this.world=world;pivotA=[world.pxmi(pivotA[0]),world.pxmi(pivotA[1])];pivotB=[world.pxmi(pivotB[0]),world.pxmi(pivotB[1])];p2.RevoluteConstraint.call(this,bodyA,pivotA,bodyB,pivotB,{maxForce:maxForce})};Phaser.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype);Phaser.Physics.P2.RevoluteConstraint.prototype.constructor=Phaser.Physics.P2.RevoluteConstraint;